from os import path from typing import Literal from fastapi import FastAPI, Response from fastapi.responses import FileResponse from requests import get from uvicorn import run from .config import CACHE_DIR from .metadata import get_collection from .types import Cover app = FastAPI() @app.get("/search/{console}") def search( console: str, sha1: str | None = None, name: str | None = None ) -> list[Cover]: covers = [] games = get_collection(console) for game in games: if sha1 and game.ref.lower() == sha1.lower(): covers.append(game) elif name and name.lower() in game.name.lower(): covers.append(game) return covers @app.get("/asset/{console}/{ref}.{type}", response_class=Response) def asset(console: str, ref: str, type: Literal["logo", "vid"]) -> Response: ext = None if type == "logo": ext = "png" mime = "image" elif type == "vid": ext = "mp4" mime = "video" filepath = f"{CACHE_DIR}/{console}/{ref}.{ext}" if CACHE_DIR and path.exists(filepath): return FileResponse(filepath) covers = get_collection(console) for cover in covers: if cover.model_dump()[type] == ref: res = get(f"https://ipfs.infura.io/ipfs/{ref}") if res.status_code == 200: if CACHE_DIR and path.exists(CACHE_DIR): with open(filepath, "wb") as f: f.write(res.content) return Response(content=res.content, media_type=f"{mime}/{ext}") break return Response(status_code=404) def start() -> None: run(app, host="0.0.0.0")