This repository has been archived on 2025-01-10. You can view files and clone it, but cannot push or open issues or pull requests.
GameCoverApi/gamecoverapi/gamecoverapi.py
2025-01-09 23:01:07 +01:00

60 lines
1.6 KiB
Python

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")