52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
from pathlib import Path
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, joinedload
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.responses import RedirectResponse, FileResponse
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from caricari.httpcommon import get_config
|
|
from caricari import database
|
|
|
|
CONFIG = get_config()
|
|
|
|
app = FastAPI()
|
|
templates = Jinja2Templates(directory=Path(__file__).parent / "templates")
|
|
|
|
engine = create_engine(CONFIG["general"]["db"])
|
|
database.metadata.create_all(engine)
|
|
session_pool = sessionmaker(bind=engine)
|
|
|
|
|
|
@app.get("/")
|
|
def home():
|
|
return "public archive"
|
|
|
|
|
|
@app.get("/dl/{path:path}")
|
|
async def get_file(path: str):
|
|
with session_pool() as conn:
|
|
original = (
|
|
conn.query(database.Original)
|
|
.options(joinedload(database.Original.archived))
|
|
.filter(database.Original.filepath == path)
|
|
.one_or_none()
|
|
)
|
|
if original is None:
|
|
raise HTTPException(status_code=404)
|
|
if not original.archived:
|
|
final_path = Path(CONFIG["general"]["files"]) / original.filepath
|
|
if final_path.exists():
|
|
return FileResponse(
|
|
# XXX: avoid it being an attachment
|
|
final_path,
|
|
media_type=original.mime,
|
|
filename=original.name,
|
|
headers={"X-sha256": original.sha256},
|
|
)
|
|
else:
|
|
return 404
|
|
|
|
# XXX: handle ?accept=
|
|
return RedirectResponse(original.archived[0].link)
|