diff --git a/app/main.py b/app/main.py index 7f17d60..596bf2b 100644 --- a/app/main.py +++ b/app/main.py @@ -4,7 +4,7 @@ from fastapi.responses import HTMLResponse from app.plugins.ical import get_events from app.plugins.netatmo import get_data as get_data_netatmo -from app.plugins.sonos import get_data as get_data_sonos +from app.plugins.sonos import get_data as get_data_sonos, proxy from app.plugins.speedtest import get_data as get_data_speedtest from app.plugins.album import album_uploade_page, upload_image, delete_image, get_data from app.plugins.weather import get_data as get_data_weather @@ -104,3 +104,8 @@ async def get_departures(connections: str = '[["Hölstein, Süd", "Liestal, Bahn @cache(expire=21_600) async def eo_guide(): return get_data_eoguide() + + +@app.get("/sonos/image-proxy") +async def proxy_image(url: str = Query(..., description="The full URL of the image to proxy")): + return proxy(url) diff --git a/app/plugins/sonos.py b/app/plugins/sonos.py index ae96aa7..a3df6bd 100644 --- a/app/plugins/sonos.py +++ b/app/plugins/sonos.py @@ -1,3 +1,6 @@ +from urllib.parse import urlparse +from fastapi import HTTPException, Response +import httpx from soco.discovery import by_name import re from app import config @@ -25,12 +28,13 @@ def get_data(): image = f"https://cdn-profiles.tunein.com/{sid}/images/logoq.jpg" else: image = None - if device.is_playing_tv: + elif device.is_playing_tv: is_playing_tv = True else: artist = current_track["artist"] song = current_track["title"] - image = current_track["album_art"] + base_url = config.get_attribute(["sonos", "album_art_base_url"]) + image = f"{base_url}/sonos/image-proxy/?url={current_track['album_art']}" playing = { "artist": artist, @@ -41,3 +45,19 @@ def get_data(): } return playing + + +def proxy(url: str): + parsed_url = urlparse(url) + if parsed_url.scheme not in ["http", "https"]: + raise HTTPException(status_code=400, detail="Invalid URL scheme. Only 'http' and 'https' are supported.") + + try: + response = httpx.get(url) + except httpx.RequestError: + raise HTTPException(status_code=400, detail="Failed to fetch the URL.") + + if response.status_code == 200: + return Response(content=response.content, media_type=response.headers.get("content-type")) + else: + raise HTTPException(status_code=response.status_code, detail="Image not found or inaccessible.")