diff --git a/caricari/public.py b/caricari/public.py index 5a5372a..1f310dc 100644 --- a/caricari/public.py +++ b/caricari/public.py @@ -3,6 +3,7 @@ from pathlib import Path from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, joinedload from fastapi import FastAPI, HTTPException +from fastapi.requests import Request from fastapi.responses import RedirectResponse, FileResponse from fastapi.templating import Jinja2Templates @@ -23,9 +24,15 @@ session_pool = sessionmaker(bind=engine) def home(): return "public archive" +def get_format(path: str, request: Request) -> str: + # XXX: add some logic involving Accept, user-agent, etc. + return path.split('.')[-1] + @app.get("/dl/{path:path}") -async def get_file(path: str): +async def get_file(request: Request, path: str, fmt: str = 'auto'): + if fmt == 'auto': + fmt = get_format(path, request) with session_pool() as conn: original = ( conn.query(database.Original) @@ -48,5 +55,9 @@ async def get_file(path: str): else: return 404 - # XXX: handle ?accept= + # look for the "best" archived version + right_format = [arc for arc in original.archived + if arc.format == fmt] + if right_format: + return RedirectResponse(right_format[0].link) return RedirectResponse(original.archived[0].link)