from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import FileResponse, PlainTextResponse from sqlalchemy import exists import hashlib import db import os def compute_hash(data: bytes, algorithm="sha256") -> str: h = hashlib.new(algorithm) h.update(data) return h.hexdigest() app = FastAPI() FILES_DIR = "./files" @app.get("/") def root(): return {"message": "hiii from sfs"} @app.get("/{filename}") def get_file(filename: str, raw: bool = False): file_path = os.path.join(FILES_DIR, filename) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File not found") if raw: with open(file_path, "r", encoding="utf-8", errors="ignore") as f: return PlainTextResponse(f.read()) return FileResponse(file_path, filename=filename) @app.post("/") async def save_file(file: UploadFile = File(...)): contents = await file.read() hash = compute_hash(contents) existed_url = db.file_exists(file.size, hash) if not existed_url: file_url = db.add_file(file.filename, file.content_type, file.size, hash) print(f"{FILES_DIR}/{file_url}") with open(f"{FILES_DIR}/{file_url}", "wb") as f: f.write(contents) return {"status": "saved", "filename": file_url} else: return {"status": "file_exists", "filename": existed_url} @app.get("/healthchecker") def healthchecker(): return {"message": "Howdy :3"}