diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..06076af --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.10.10 + +WORKDIR /app + +RUN pip install --upgrade pip + +COPY requirements.txt requirements.txt + +RUN pip install -r requirements.txt + +COPY . . + +EXPOSE 8080 + +ENV PYTHONUNBUFFERED=1 + +CMD ["uvicorn", "--host", "0.0.0.0", "--port", "8080", "main:app"] diff --git a/README.md b/README.md index 8f8782c..dbe19a9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,42 @@ # Backend-API +Hiya! Gabriel here, this repo is for the backend of the app (ai model not included). Some of the features : +- Auth +- Article +- Forum +- Image resizer +- Comment system + +## how to use +install the requirements +```bash +pip install -r requirements.txt +``` +boot uvicorn +```bash +uvicorn main:app +``` +or +```bash +python3 -m uvicorn main:app +``` +ENV list +``` +> PORT +> cres (service account for cloud storage) +> secret +> algorithm +> dbase +> duser +> dpw +> dip +``` + + + # side-API -**Api things in case I forgot** +**Development notes** here me testing before making the api, -before that the sql relation will look like this : +before that the sql relation will look like this : ![enter image description here](https://cdn.discordapp.com/attachments/1023598916857499680/1106228887899357225/image.png) So we got 3 tables in total to make: users, article, comps in article we have 5 parameters: diff --git a/app/auth/jwt_bearer.py b/app/auth/jwt_bearer.py new file mode 100644 index 0000000..11cb4f0 --- /dev/null +++ b/app/auth/jwt_bearer.py @@ -0,0 +1,29 @@ +# authorization (verify the route) +from fastapi import Request, HTTPException +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from .jwt_handler import decodeJWT + + +class jwtBearer(HTTPBearer): + def __init__(self, auto_Error : bool = True): + super(jwtBearer, self).__init__(auto_error=auto_Error) + + async def __call__(self, request : Request): + credentials : HTTPAuthorizationCredentials = await super(jwtBearer, + self).__call__(request) + if credentials: + if not credentials.scheme == "Bearer": + raise HTTPException(status_code = 403, details="token is no longer available :(((") + return credentials.credentials + #for any reason why everything is not according to plan we still will make fun of their's credentials + else: + raise HTTPException(status_code = 403, details="token is no longer available :(((") + + def verify_jwt(self, jwtoken : str): + isTokenValid : bool = False # a false flag + payload = decodeJWT(jwtoken) + if payload: + isTokenValid = True + + + return isTokenValid \ No newline at end of file diff --git a/app/auth/jwt_handler.py b/app/auth/jwt_handler.py new file mode 100644 index 0000000..957679f --- /dev/null +++ b/app/auth/jwt_handler.py @@ -0,0 +1,35 @@ +#this file for encoding and decoding and returning jwts +import hashlib +import jwt +import time +from decouple import config +from typing import Dict + +JWT_SECRET = config("secret") +JWT_ALGORITHM = config("algorithm") + +#deez generated tokens (jwts) +def token_response(token: str): + return{ + "access token": token + } + +def signJWT(userID : str): + payload = { + "userID" : userID, + "expiry" : time.time() + 600 + } + token = jwt.encode(payload,JWT_SECRET, algorithm=JWT_ALGORITHM) + return token_response(token) + + +def decodeJWT(token:str): + try: + decode_token = jwt.decode(token, JWT_SECRET, algorithm=JWT_ALGORITHM) + return decode_token if decode_token['expires'] >= time.time()else None + except: + return {} + + + + diff --git a/app/function.py b/app/function.py new file mode 100644 index 0000000..41750bd --- /dev/null +++ b/app/function.py @@ -0,0 +1,539 @@ +from fastapi import FastAPI, Body, Depends, File, UploadFile, Request +from fastapi.responses import FileResponse +from app.auth.jwt_bearer import jwtBearer +from app.auth.jwt_handler import * +from google.cloud import storage +from dotenv import load_dotenv +from connection import * +from app.model import * +from io import BytesIO +import mysql.connector +from app.function import * +from PIL import Image +import requests +import uvicorn +import random +import json +import jwt +import os +import io + +def decode_user(token2): + decoded_data = jwt.decode(token2,JWT_SECRET,JWT_ALGORITHM) + return decoded_data + +#function.py +def searchUserById(id): + mydb=defineDB() + mycursor = mydb.cursor() + values = (id,) + mycursor.execute("SELECT * FROM users2 WHERE id= %s", values) + # mycursor.execute("SELECT * FROM componenttable WHERE email='dgerbi11@answers.com'") + + myresult = mycursor.fetchall() + name = myresult[0][1] + mycursor.close() + close_db_connection(mydb, "components") + return name + +def getAllForum(): + mydb=defineDB() + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM forum ORDER BY id DESC;") + + myresult = mycursor.fetchall() + forumList = [] + for x in myresult: + artic = { + "id":x[0], + "title":x[1], + "category":x[2], + "location":x[3], + "content":x[4], + "imageURL":x[5], + "likes":x[6] + } + forumList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return forumList + +def getForumName(forumName): + mydb=defineDB() + values = (forumName,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM forum WHERE title LIKE %s;", values) + + myresult = mycursor.fetchall() + forumList = [] + for x in myresult: + artic = { + "id":x[0], + "title":x[1], + "category":x[2], + "location":x[3], + "content":x[4], + "imageURL":x[5], + "likes":x[6], + "Postedby":searchUserById(x[7]) + } + + + + forumList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return forumList + + + +def getArticleName(articleName): + mydb=defineDB() + values = (articleName,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM articles WHERE name LIKE %s;", values) + + myresult = mycursor.fetchall() + forumList = [] + for x in myresult: + artic = { + "id":x[0], + "name":x[1], + "description":x[2], + "articleImageURL":x[3], + "componentID":x[4], + } + + + + forumList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return forumList + + +def getForumByCategory(cate): + mydb=defineDB() + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM forum WHERE category = %s ORDER BY id DESC",(cate,)) + + myresult = mycursor.fetchall() + forumList = [] + for x in myresult: + artic = { + "id":x[0], + "title":x[1], + "category":x[2], + "location":x[3], + "content":x[4], + "imageURL":x[5], + "likes":x[6], + "Postedby":searchUserById(x[7]) + } + + forumList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return forumList + +def getForumById(desuwa): + mydb=defineDB() + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM forum WHERE id =%s ORDER BY id DESC",(desuwa,)) + + myresult = mycursor.fetchall() + forumList = [] + + artic = { + "id":myresult[0][0], + "title":myresult[0][1], + "category":myresult[0][2], + "location":myresult[0][3], + "content":myresult[0][4], + "imageURL":myresult[0][5], + "likes":myresult[0][6], + "Postedby":searchUserById(myresult[0][7]) + } + + forumList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return forumList + +def postForumtest(forum: ForumSchema): + mydb=defineDB() + anu=decode_user() + email=anu["userID"] + mycursor = mydb.cursor() + values = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", values) + myresult = mycursor.fetchall() + userId = myresult + mycursor.close() + close_db_connection(mydb, "components") + return userId + + + + + +def check_user(data: UserLoginSchema): + mydb=defineDB() + mycursor = mydb.cursor() + + email = data.email + password = data.password + res = (email,) + + mycursor.execute("SELECT * FROM users2 WHERE email= %s", res) + myresult = mycursor.fetchall() + mycursor.close() + close_db_connection(mydb, "components") + if (len(myresult) == 1): + res_pass = myresult[0][3] + if (password == res_pass): + return True + return False + +def getCreden(data: UserLoginSchema): + mydb=defineDB() + if check_user(data): + mycursor = mydb.cursor() + email = data.email + res = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", res) + myresult = mycursor.fetchall() + resId = myresult[0][0] + resName = myresult[0][1] + mycursor.close() + close_db_connection(mydb, "components") + return{ + "id":resId, + "Username":resName + } + else: + return{"error":"what the hell are you trying to do 🗿"} + + + + + +def pushUser(data: UserSchema): + mydb=defineDB() + mycursor = mydb.cursor() + + name = data.fullname + email = data.email + password = data.password + resq = (email,) + + mycursor.execute("SELECT * FROM users2 WHERE email= %s", resq) + + myresult = mycursor.fetchall() + + isTaken = "undefined" + + + if (len(myresult) == 1): + isTaken = True + else: + isTaken = False + + if (isTaken): + mycursor.close() + close_db_connection(mydb, "components") + + return False + else: + query = "insert into users2 (name, email, password) values (%s, %s, %s);" + res = (name,email,password) + mycursor.execute(query, res) + mydb.commit() + mycursor.close() + close_db_connection(mydb, "components") + + return True + + +def getbyId(id): + mydb=defineDB() + mycursor = mydb.cursor() + + # mycursor.execute("SELECT * FROM3 comps") + res=(id,) + mycursor.execute("SELECT * FROM comps WHERE id= %s", res) + + myresult = mycursor.fetchall() + id=myresult[0][0] + name=myresult[0][1] + desc=myresult[0][2] + example=myresult[0][3] + + myresult={ + "id":id, + "name":name, + "desc":desc, + "example":example + } + mycursor.close() + close_db_connection(mydb, "components") + return myresult + + + + +def getArticlebyId(compid): + mydb=defineDB() + mycursor = mydb.cursor() + res = (compid,) + mycursor.execute("SELECT * FROM articles WHERE componentId= %s", res) + myresult = mycursor.fetchall() + articleList = [] + for t in myresult: + artic = { + "id":t[0], + "name":t[1], + "desc":t[2], + "articleImageURL":t[3], + "componentId":t[4] + } + articleList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return articleList + + +def getAllArticleby(): + mydb=defineDB() + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM articles ORDER BY id DESC;") + myresult = mycursor.fetchall() + articleList = [] + for t in myresult: + artic = { + "id":t[0], + "name":t[1], + "desc":t[2], + "articleImageURL":t[3], + "componentId":t[4] + } + articleList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return articleList + +def getAllComponents(): + mydb=defineDB() + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM comps ORDER BY id DESC;") + myresult = mycursor.fetchall() + articleList = [] + for t in myresult: + artic = { + "id":t[0], + "name":t[1], + "desc":t[2], + "imageExample":t[3], + } + articleList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return articleList + +def getArticleID2(articleName): + mydb=defineDB() + values = (articleName,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM articles WHERE id=%s;", values) + + myresult = mycursor.fetchall() + forumList = [] + for x in myresult: + compID=(x[4],) + mycursor2 = mydb.cursor() + mycursor2.execute("SELECT * FROM comps WHERE id=%s;", compID) + myresult2 = mycursor2.fetchall() + artic = { + "id":x[0], + "name":x[1], + "description":x[2], + "articleImageURL":x[3], + "componentID":x[4], + "componentName":myresult2[0][1] + } + + + forumList.append(artic) + mycursor.close() + mycursor2.close() + close_db_connection(mydb, "components") + return forumList + +def postForum(forum: ForumSchema,email): + mydb=defineDB() + mycursor = mydb.cursor() + values = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", values) + myresult = mycursor.fetchall() + userId = myresult[0][0] + lilcursorhehe = mydb.cursor() + query = "insert into forum (title, category, location, content, imageUrl, userId) values (%s, %s, %s, %s, %s, %s);" + res = (forum.title, forum.category, forum.location, forum.content, forum.imageUrl,userId) + lilcursorhehe.execute(query, res) + mydb.commit() + mycursor.close() + lilcursorhehe.close() + close_db_connection(mydb, "components") + return { + "error":"false", + "message":"your post has been posted 😱🥶🥶🥶🥶🥶🥶🥶" + } + +def getCommentForum(forumid): + mydb=defineDB() + values = (forumid,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM comment WHERE forumID LIKE %s;", values) + + myresult = mycursor.fetchall() + commentList = [] + for x in myresult: + artic = { + "id":x[0], + "comment":x[1], + "userID":x[2], + "username":x[3], + "replyFrom":x[4], + "forumID":x[5] + } + + + + commentList.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return commentList + + +def postComment(input: CommentSchema,email): + mydb=defineDB() + mycursor = mydb.cursor() + values = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", values) + myresult = mycursor.fetchall() + userId = myresult[0][0] + username = myresult[0][1] + lilcursorhehe = mydb.cursor() + query = "insert into comment (comment, userID, username, replyFrom, forumID) values (%s, %s, %s, %s, %s);" + res = (input.comment, userId, username, 0 , input.forumID) + lilcursorhehe.execute(query, res) + mydb.commit() + mycursor.close() + lilcursorhehe.close() + close_db_connection(mydb, "components") + return { + "error":"false", + "message":"your comment has been posted 😱🥶🥶🥶🥶🥶🥶🥶", + "commentInfo":{ + "Poster":username, + "PosterID":userId, + "forumID":input.forumID, + "comment":input.comment + } + } + + +def replybyCommentID(input: ReplySchema,email): + mydb=defineDB() + mycursor = mydb.cursor() + values = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", values) + myresult = mycursor.fetchall() + userId = myresult[0][0] + username = myresult[0][1] + lilcursorhehe = mydb.cursor() + query = "insert into comment (comment, userID, username, replyFrom, forumID) values (%s, %s, %s, %s, %s);" + res = (input.comment, userId, username, input.replyFrom , input.forumID) + lilcursorhehe.execute(query, res) + mydb.commit() + mycursor.close() + lilcursorhehe.close() + close_db_connection(mydb, "components") + return { + "error":"false", + "message":"your comment has been posted 😱🥶🥶🥶🥶🥶🥶🥶", + "commentInfo":{ + "Poster":username, + "PosterID":userId, + "forumID":input.forumID, + "comment":input.comment + } + } + + + +def getSmallPartsComp(compid): + mydb=defineDB() + values = (compid,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM smallParts WHERE compID = %s;", values) + + myresult = mycursor.fetchall() + smallParts = [] + for x in myresult: + artic = { + "id":x[0], + "name":x[1], + "description":x[2], + "imageURL":x[3], + "compID":x[4], + } + + + + smallParts.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return smallParts + +def getSmallPartsComp(id): + mydb=defineDB() + values = (id,) + mycursor = mydb.cursor() + mycursor.execute("SELECT * FROM smallParts WHERE id = %s;", values) + + myresult = mycursor.fetchall() + smallParts = [] + for x in myresult: + artic = { + "id":x[0], + "name":x[1], + "description":x[2], + "imageURL":x[3], + "compID":x[4], + } + smallParts.append(artic) + mycursor.close() + close_db_connection(mydb, "components") + return smallParts + + +def postForum(forum: ForumSchema,email): + mydb=defineDB() + mycursor = mydb.cursor() + values = (email,) + mycursor.execute("SELECT * FROM users2 WHERE email= %s", values) + myresult = mycursor.fetchall() + userId = myresult[0][0] + lilcursorhehe = mydb.cursor() + query = "insert into forum (title, category, location, content, imageUrl, userId) values (%s, %s, %s, %s, %s, %s);" + res = (forum.title, forum.category, forum.location, forum.content, forum.imageUrl,userId) + lilcursorhehe.execute(query, res) + mydb.commit() + mycursor.close() + lilcursorhehe.close() + close_db_connection(mydb, "components") + return { + "error":"false", + "message":"your post has been posted 😱🥶🥶🥶🥶🥶🥶🥶" + } \ No newline at end of file diff --git a/app/model.py b/app/model.py new file mode 100644 index 0000000..b80cba9 --- /dev/null +++ b/app/model.py @@ -0,0 +1,116 @@ +from pydantic import BaseModel, Field, EmailStr + +# config = { +# 'user': 'root', +# 'password': "J]91kx6G&S:^]'Gu", +# 'host': '34.69.199.102', +# 'database': 'component', +# 'raise_on_warnings': True +# } + +class PostSchema(BaseModel): + id : int = Field(default=None) + title : str = Field(default=None) + content : str = Field(default=None) + class Config: + schema_extra = { + "post_demo" : { + "title" : "some title about animes", + "content" : "some content about animes" + } + + } + + +class UserSchema(BaseModel): + fullname : str = Field(default = None) + email : EmailStr = Field(default = None) + password : str = Field(default = None) + class Config: + the_schema = { + "user_demo": { + "name":"deez", + "email":"deez@nutz.com", + "password":"123" + + } + } + + + +class UserLoginSchema(BaseModel): + email : EmailStr = Field(default = None) + password : str = Field(default = None) + class Config: + the_schema = { + "user_demo": { + "email":"deez@nutz.com", + "password":"123" + + } + + } + +class getComponent(BaseModel): + id : int = Field(default=None) + name : str = Field(default=None) + desc : str = Field(default=None) + example : str = Field(default=None) + class Config: + the_schema = { + "getComp_demo": { + "id":"0", + "name":"cable", + "desc":"some stuff", + "example":"cable.com" + } + + } + + +class ForumSchema(BaseModel): + title : str = Field(default=None) + category : str = Field(default=None) + location : str = Field(default=None) + content : str = Field(default=None) + imageUrl : str = Field(default=None) + class Config: + schema_extra = { + "post_demo" : { + "title" : "some title about animes", + "category" : "anime gelud", + "location" : "isekai", + "content" : "some content about animes", + "imageUrl" : "jpg.jpg" + } + + } + + + +class CommentSchema (BaseModel): + comment : str = Field(default=None) + forumID : int = Field(default=None) + class Config: + schema_extra = { + "post_demo" : { + "comment" : "Bang info lokasi", + "forumID" : 1 + } + + } + + +class ReplySchema (BaseModel): + comment : str = Field(default=None) + replyFrom : int = Field(default=None) + forumID : int = Field(default=None) + class Config: + schema_extra = { + "post_demo" : { + "comment" : "Bang info lokasi", + "replyFrom" : 1, + "forumID" : 1 + } + + } diff --git a/connection.py b/connection.py new file mode 100644 index 0000000..9d35832 --- /dev/null +++ b/connection.py @@ -0,0 +1,51 @@ +import mysql.connector + + +dbase = config("dbase") +duser = config("duser") +dpw = config("dpw") +dip = config("dip") + +# Define a function to open database connection +def open_db_connection(db_name, user, password, host): + # Try to connect to the database + try: + # Create a connection object with the name mydb + mydb = mysql.connector.connect(database=db_name, user=user, password=password, host=host) + # Print a success message + print("Opened connection to database:", db_name) + # Return the connection object + return mydb + # Handle any exceptions + except mysql.connector.Error as e: + # Print an error message + print("Failed to open connection to database:", e) + # Return None + return None + +# Define a function to close database connection +def close_db_connection(mydb, db_name): + # Check if the connection object exists + if mydb: + # Try to close the connection + try: + # Close the connection + mydb.close() + # Print a success message + print("Closed connection to database:", db_name) + # Handle any exceptions + except mysql.connector.Error as e: + # Print an error message + print("Failed to close connection to database:", e) + + + +def defineDB(): + mydb=open_db_connection( + dbase, + duser, + dpw, + dip, + ) + return mydb + diff --git a/main.py b/main.py new file mode 100644 index 0000000..d3c52fe --- /dev/null +++ b/main.py @@ -0,0 +1,601 @@ +from fastapi import FastAPI, Body, Depends, File, UploadFile, Request +from fastapi.responses import FileResponse +from app.auth.jwt_bearer import jwtBearer +from app.auth.jwt_handler import * +from google.cloud import storage +from dotenv import load_dotenv +from connection import * +from app.model import * +from io import BytesIO +import mysql.connector +from app.function import * +from PIL import Image +import requests +import uvicorn +import random +import json +import jwt +import os +import io + +load_dotenv() +key_pi = os.getenv("cres") +# GOOGLE_APPLICATION_CREDENTIALS = key_pi +with open("service_account.json", "w") as file: + file.write(key_pi) +os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./service_account.json" +form = str(random.randint(3, 3265792139879102375)) +bucketName = "techpybarahh" + + + +def storage_thingy(blobName, filePath, bucketName): + storageClient = storage.Client() + dir(storageClient) + bucket = storageClient.bucket(bucketName) + vars(bucket) + bucket = storageClient.get_bucket(bucketName) + blob = bucket.blob(blobName) + blob.upload_from_filename(filePath) + + return blob + + +token = [] + +async def testcoded(request: Request): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + return decode_user(token2) + +def decode_user(token2): + decoded_data = jwt.decode(token2,JWT_SECRET,JWT_ALGORITHM) + return decoded_data + + + +posts = [ + { + "id": 1, + "title": "rent-a-gf", + "text":"stupid *ss anime only psychopath watch this" + + }, + { + "id": 2, + "title": "kimi-no-nawa", + "text": "overrated but ok" + + }, + { + "id": 3, + "title":"demon-slayer", + "text":"overrated af and also it's the equivalent of fortnite in anime industry (only 5 yolds love it)" + + } + + +] + + +users = [] + +app = FastAPI() + + +# Get test +@app.get("/", tags=["test"]) +def greet(): + return{"YAHOOOOO~!":"THE PROPECHY STIGNEAS!"} + + +# Get posts +@app.get("/posts", tags=["posts"]) +def get_posts(): + return{"data": posts} + +# get single post by id +@app.get("/post/{id}", tags=["posts"]) +def get_one_post(id:int): + if id > len(posts): + return{ + "error":"erm, there is no post..." + } + for post in posts: + if post["id"]==id: + return { + "data":post + } + + + + +@app.get("/component/{id}", dependencies=[Depends(jwtBearer())], tags=["components"]) +def comps(id: str): + result = getbyId(id) + return { + "error":"false", + "message":"success", + "componentList":result + } + + + +@app.get("/article/{id}", dependencies=[Depends(jwtBearer())], tags=["articles"]) +def artic(compid: str): + result = getArticlebyId(compid) + return { + "error":"false", + "message":"success", + "articleList":result + } + +@app.get("/allArticle", tags=["articles"]) +def compsed(): + result = getAllArticleby() + return { + "error":"false", + "message":"success", + "componentList":result + } + + +# Post new post +@app.post("/posts", dependencies=[Depends(jwtBearer())], tags=["posts"]) +def add_post(post: PostSchema): + post.id = len(posts)+1 + posts.append(post.dict()) + return{ + "info":"degenericity added" + } + +# User thingy I forgor basically +#@app.post("/user/signup", tags=["user"]) +#def user_signup(user : UserSchema = Body(...)): +# users.append(user) +# return signJWT(user.email) + + + +@app.post("/user/signup", tags=["user"]) +def user_signup(user : UserSchema = Body(...)): + users.append(user) + + if pushUser(user): + return { + "error":"false", + "message":"User Created", + "signupToken":signJWT(user.email) + } + else: + return{ + "error":"true", + "message":"Email already taken 🗿" + } + + + + + +@app.post("/user/login", tags=["user"]) +def user_login(user: UserLoginSchema = Body(...)): + if check_user(user): + token.clear() + nanikore = signJWT(user.email) + token.append(nanikore) + return { + "error":"false", + "message":"login success", + "loginResult":{ + "userId":getCreden(user), + "token":nanikore, + }} + + else: + return{ + "error":"true", + "message":"Invalid login details! 🗿" + } + +async def testcoded(request: Request): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + return {"hasil":token2, + "test-token":decode_user(token2)} + + + + +@app.get("/meneh", dependencies=[Depends(jwtBearer())], tags=["test"]) +def coba(): + wibu=decode_user() + email=wibu["userID"] + return email + +@app.post("/forum/postest", dependencies=[Depends(jwtBearer())], tags=["forum"]) +def posting(forum: ForumSchema = Body(...)): + return postForumtest(forum) + + + +@app.get("/forum/getall", tags=["forum"]) +def forumGetAll(): + + forum = getAllForum() + if (forum): + return{ + "error":"false", + "message":"success", + "forum":forum + } + else: + return{ + "error":"true", + "message":"it's either no forum or you wanna do something terrible 💀" + } + +@app.get("/forum/id/{id}", dependencies=[Depends(jwtBearer())], tags=["forum"]) +def forid(id): + result = getForumById(id) + if(result): + return { + "error":"false", + "message":"success", + "forum":result + } + else: + return { + "error":"true", + "message":"are you serious rait now braw 💀" + } + + +@app.get("/forum/category/{category}", dependencies=[Depends(jwtBearer())], tags=["forum"]) +def forumCategory(category): + forum = getForumByCategory(category) + if (forum): + return{ + "error":"false", + "message":"success", + "forum":forum + } + else: + return{ + "error":"true", + "message":"it's either there's no forum for this category or you wanna do something terrible 💀" + } + + +@app.get("/decode/", dependencies=[Depends(jwtBearer())], tags=["decode"]) +async def testcoded(request: Request): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + jsonResponse = decode_user(token2) + return(jsonResponse["userID"]) + + +@app.get("/components/", tags=["components"]) +def getAllComp(): + output = getAllComponents() + if(output): + return{ + "error":"false", + "message":"success", + "components":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + +@app.get("/forum/title/{title}", tags=["forum"]) +def getForumbyName(title): + output = getForumName(title) + if(output): + return{ + "error":"false", + "message":"success", + "Forum":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + +@app.get("/article/name/{name}", tags=["articles"]) +def getArticlebyName(name): + output = getArticleName(name) + if(output): + return{ + "error":"false", + "message":"success", + "article":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + + + +@app.get("/article/id/{id}", tags=["articles"]) +def getArticlebyName(id): + output = getArticleID2(id) + if(output): + return{ + "error":"false", + "message":"success", + "article":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + + + + + +@app.post("/forum/post", dependencies=[Depends(jwtBearer())], tags=["forum"]) +def posting(request: Request,forum: ForumSchema = Body(...)): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + jsonResponse=decode_user(token2) + email=jsonResponse["userID"] + + postForum(forum,email) + if (forum): + return{ + "error":"false", + "message":"your post has been posted 😱🥶🥶🥶🥶🥶🥶🥶" + + } + else: + return{ + "error":"true", + "message":"what are you trying to do lil bro 💀" + + } + +@app.post("/comments/post", dependencies=[Depends(jwtBearer())],tags=["comments"]) +def postComments(request: Request,post: CommentSchema = Body(...)): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + jsonResponse=decode_user(token2) + email=jsonResponse["userID"] + if (post): + return postComment(post,email) + + + + + + +@app.get("/comments/byforumid/{forumid}", tags=["comments"]) +def getCommentsbyForumId(forumid): + output = getCommentForum(forumid) + if(output): + return{ + "error":"false", + "message":"success", + "article":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + + + + + + +@app.post("/reply/post",dependencies=[Depends(jwtBearer())], tags=["comments"]) +def replyCommentID(request: Request,post: ReplySchema = Body(...)): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + jsonResponse=decode_user(token2) + email=jsonResponse["userID"] + if (post): + return replybyCommentID(post,email) + + + + +@app.get("/smallparts/bycompid/{compid}", tags=["components"]) +def getsmallpartsbycompid(compid): + output = getSmallPartsComp(compid) + if(output): + return{ + "error":"false", + "message":"success", + "smallParts":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + + + +@app.get("/smallparts/byid/{id}", tags=["components"]) +def getsmallpartsbycompid(id): + output = getSmallPartsComp(id) + if(output): + return{ + "error":"false", + "message":"success", + "smallParts":output + } + else: + return{ + "error":"true", + "message":"waduh kenapa nih bang?" + } + + +@app.post("/forum/upimagepost", dependencies=[Depends(jwtBearer())], tags=["forum"]) +async def posting(request: Request,file: UploadFile = File(...)): + authorization_header = request.headers["Authorization"] + token2 = authorization_header.split(" ")[1] + + savedForm = form + extension = file.filename.split(".")[-1] in ("jpg", "jpeg","png") + if not extension: + return "Image must be jpg, jpeg, or png format!" + contents = await file.read() + + image = Image.open(io.BytesIO(contents)) + image.save(file.filename) + + storage_thingy("savedUser/"+"image"+savedForm+"USED"+token2, file.filename, bucketName) + saved = "https://storage.googleapis.com/techpybarahh/savedUser/"+"image"+savedForm+"USED"+token2 + os.remove(file.filename) + + if (saved): + return{ + "error":"false", + "message":"your image has been posted 😱🥶🥶🥶🥶🥶🥶🥶", + "imgURL":saved + + } + else: + return{ + "error":"true", + "message":"what are you trying to do lil bro 💀" + + } + +# #don't worry about this one +# @app.get("/resize",tags=["image"]) +# async def resize_image(file: UploadFile = File(...), width: int = 300, height: int = 300): +# # Read the uploaded image file +# image = Image.open(BytesIO(await file.read())) + +# # Resize the image +# resized_image = image.resize((width, height)) + +# # Save the resized image to disk +# output_path = "resized_image.jpg" # Specify the desired output file path +# resized_image.save(output_path, format="JPEG") + +# return {"message": "Image resized and saved successfully.", "file_path": output_path} + +@app.get("/resize/imageurl",tags=["image"]) +async def resize_image( + image_url: str = "https://storage.googleapis.com/somethingssss/PXL_20230203_102403556.jpg", + width: int = 300, + height: int = 300 + ): + # Fetch the image from the provided URL + response = requests.get(image_url) + response.raise_for_status() + + # Read the fetched image + image = Image.open(BytesIO(response.content)) + + # Resize the image + resized_image = image.resize((width, height)) + + # Save the resized image to disk + output_path = "resized_image.jpg" # Specify the desired output file path + resized_image.save(output_path, format="JPEG") + + # return {"message": "Image resized and saved successfully.", "file_path": output_path} + return FileResponse(output_path) + +@app.get("/crop/imageurl",tags=["image"]) +async def crop_image( + image_url: str = "https://storage.googleapis.com/somethingssss/PXL_20230203_102403556.jpg", + width: int = 300, + height: int = 300 + ): + # Fetch the image from the provided URL + response = requests.get(image_url) + response.raise_for_status() + + # Open the fetched image using PIL + image = Image.open(BytesIO(response.content)) + + # Calculate the aspect ratio of the original image + aspect_ratio = image.width / image.height + + # Calculate the target width based on the desired height and aspect ratio + target_width = int(height * aspect_ratio) + + # Resize the image while maintaining the aspect ratio + resized_image = image.resize((target_width, height)) + + # Calculate the cropping coordinates to remove the extra height + left = 0 + top = (resized_image.height - height) / 2 + right = left + width + bottom = top + height + + # Crop the image to the desired width and height + cropped_image = resized_image.crop((left, top, right, bottom)) + + # Save the cropped image to a BytesIO buffer + output_path = "resized_image.jpg" + cropped_image.save(output_path, "JPEG") + + # Return the image as a response + return FileResponse(output_path) + +@app.get("/crop2/imageurl",tags=["image"]) +async def crop_image2( + image_url: str = "https://storage.googleapis.com/somethingssss/PXL_20230203_102403556.jpg", + width: int = 300, + height: int = 300 + ): + # Fetch the image from the provided URL + response = requests.get(image_url) + response.raise_for_status() + + # Open the fetched image using PIL + image = Image.open(BytesIO(response.content)) + + # Calculate the desired aspect ratio + aspect_ratio = width / height + + # Calculate the actual aspect ratio of the original image + original_aspect_ratio = image.width / image.height + + # Resize the image while maintaining the correct aspect ratio + if original_aspect_ratio > aspect_ratio: + new_width = int(height * original_aspect_ratio) + resized_image = image.resize((new_width, height)) + else: + new_height = int(width / original_aspect_ratio) + resized_image = image.resize((width, new_height)) + + # Create a blank white canvas with the specified dimensions + canvas = Image.new("RGB", (width, height), "white") + + # Paste the resized image onto the canvas + offset = ((width - resized_image.width) // 2, (height - resized_image.height) // 2) + canvas.paste(resized_image, offset) + + # Save the canvas to a BytesIO buffer + # image_buffer = BytesIO() + output_path = "resized_image.jpg" + canvas.save(output_path, "JPEG") + + # Return the image as a response + return FileResponse(output_path) + + + +if __name__ == "__main__": + import uvicorn \ No newline at end of file