Spaces:
Running
Running
File size: 5,071 Bytes
a85ece7 f1f8646 a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 f1f8646 a85ece7 f1f8646 a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a a85ece7 dee885a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """FastAPI application for the PastFm service."""
from typing import Optional
from datetime import datetime
from xml.sax.saxutils import escape
import uvicorn
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse, Response, JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from config import config, BASE_DIR
from utils import generate_css_bar, generate_bar_elements, LastFmClient, logger
class Item(BaseModel):
"""Pydantic model for URL input."""
url: str
def create_app() -> FastAPI:
"""
Create and configure the FastAPI application.
Returns:
Configured FastAPI instance
"""
app = FastAPI(
title="PastFm API",
description="LastFM scrobble card generator for GitHub profile README",
version="1.1.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
@app.get("/")
async def root() -> RedirectResponse:
"""Redirect to project GitHub page."""
return RedirectResponse(url="https://github.com/arpy8/PastFm")
@app.get("/redirect")
async def redirect() -> RedirectResponse:
"""Redirect to project repository."""
return RedirectResponse(url="https://github.com/arpy8/PastFm")
@app.get("/live")
async def live_banner(
request: Request,
user: str = config.default_user,
color: str = config.default_color,
) -> RedirectResponse:
"""
Generate a timestamped redirect to ensure fresh content.
Args:
request: FastAPI request object
user: LastFM username
color: Hex color code (without #)
Returns:
Redirect to the render endpoint with timestamp
"""
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
return RedirectResponse(url=f"/render?user={user}&color={color}&t={timestamp}")
@app.get("/render")
async def render_banner(
request: Request,
user: str = config.default_user,
color: str = config.default_color,
t: Optional[str] = None,
) -> Response:
"""
Render the LastFM now playing/recently played card.
Args:
request: FastAPI request object
user: LastFM username
color: Hex color code (without #)
t: Timestamp for cache busting
Returns:
SVG image response
Raises:
HTTPException: If rendering fails
"""
try:
css_bar = generate_css_bar(config.num_bars)
lastfm_client = LastFmClient(username=user)
result = lastfm_client.get_current_track()
if not result:
return JSONResponse(
content={
"success": False,
"message": "Failed to fetch song details",
},
status_code=404,
)
timestamp = t or datetime.now().strftime("%Y%m%d%H%M%S")
context = {
"title_text": "Now playing" if result["is_playing"] else "Last played",
"color": color,
"song_name": escape(result["song"]),
"artist_name": escape(result["artist"]),
"thumbnail": result["thumbnail"],
"url": escape(result["url"]) if result["url"] else "",
"css_bar": css_bar,
"timestamp": timestamp,
"cover_image": bool(result["thumbnail"]),
"content_bar": generate_bar_elements(config.num_bars),
}
svg_content = templates.get_template("default_theme.html").render(context)
headers = {
"Cache-Control": "private, no-cache, no-store, must-revalidate, max-age=0",
"Pragma": "no-cache",
"Expires": "-1",
"ETag": f'W/"{timestamp}"',
"Last-Modified": datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"),
}
return Response(
content=svg_content, media_type="image/svg+xml", headers=headers
)
except Exception as e:
logger.error(f"Error rendering banner: {e}")
raise HTTPException(
status_code=500, detail=f"Error rendering banner: {str(e)}"
)
@app.get("/health")
async def health_check() -> JSONResponse:
"""Check application health status."""
return JSONResponse(
content={"status": "healthy", "version": app.version}, status_code=200
)
return app
def start_server() -> None:
"""Start the uvicorn server for local development."""
uvicorn.run("pastfm.app:app", host="0.0.0.0", port=7860, reload=config.debug)
|