added cache and FileResponse for range requests to seek meia

This commit is contained in:
dm
2025-08-31 19:16:15 +03:00
parent c256f8834e
commit 1032c08a40

View File

@@ -18,6 +18,7 @@ api_key_header = APIKeyHeader(name="X-API-Key")
FTP_URL = os.getenv("FTP_URL") FTP_URL = os.getenv("FTP_URL")
FTP_LOGIN = os.getenv("FTP_LOGIN") FTP_LOGIN = os.getenv("FTP_LOGIN")
FTP_PASSWORD = os.getenv("FTP_PASSWORD") FTP_PASSWORD = os.getenv("FTP_PASSWORD")
CACHE_DIR = "cache"
def verify_api_key(api_key: str = Security(api_key_header)): def verify_api_key(api_key: str = Security(api_key_header)):
if api_key != API_KEY: if api_key != API_KEY:
@@ -58,29 +59,38 @@ async def save_file(file: UploadFile = File(...), api_key: str = Depends(verify_
ftp.storbinary(f"STOR {FILES_DIR}/{file_url}", buffer) ftp.storbinary(f"STOR {FILES_DIR}/{file_url}", buffer)
ftp.quit() ftp.quit()
cached = os.path.join(CACHE_DIR, file_url)
if os.path.exists(cached):
os.remove(cached)
return {"status": "saved", "filename": file_url} return {"status": "saved", "filename": file_url}
except Exception as e: except Exception as e:
db.remove_file(file_url) db.remove_file(file_url)
return {"status": "error", "message": f"Could not save file {file_url}: {e}"} return {"status": "error", "message": f"Could not save file {file_url}: {e}"}
else: else:
return {"status": "file_exists", "filename": existed_url} return {"status": "file_exists", "filename": existed_url}
@app.get("/file/{filename}") @app.get("/file/{filename}")
async def get_file(filename: str, raw: bool = False, api_key: str = Depends(verify_api_key)): async def get_file(filename: str, raw: bool = False, api_key: str = Depends(verify_api_key)):
local_path = os.path.join(CACHE_DIR, filename)
if not os.path.exists(local_path):
try: try:
ftp = FTP(FTP_URL) ftp = FTP(FTP_URL)
ftp.login(FTP_LOGIN, FTP_PASSWORD) ftp.login(FTP_LOGIN, FTP_PASSWORD)
buffer = BytesIO() with open(local_path, "wb") as f:
ftp.retrbinary(f"RETR {FILES_DIR}/{filename}", buffer.write) ftp.retrbinary(f"RETR {FILES_DIR}/{filename}", f.write)
ftp.quit() ftp.quit()
buffer.seek(0)
except Exception as e: except Exception as e:
raise HTTPException(status_code=404, detail=f"File not found: {e}") raise HTTPException(status_code=404, detail=f"File not found: {e}")
if raw: if raw:
return PlainTextResponse(buffer.getvalue().decode("utf-8", errors="ignore")) with open(local_path, "r", encoding="utf-8", errors="ignore") as f:
return PlainTextResponse(f.read())
return StreamingResponse(buffer, media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{filename}"'}) return FileResponse(local_path, filename=filename)
from ftplib import FTP from ftplib import FTP