From 0bd2b6b4f306582a8042a5a4c9443df442664576 Mon Sep 17 00:00:00 2001 From: codey Date: Sat, 27 Sep 2025 09:28:47 -0400 Subject: [PATCH] Refactor LRC fetching logic to use BackgroundTasks directly and encapsulate in a new async method --- endpoints/radio.py | 39 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/endpoints/radio.py b/endpoints/radio.py index 85c3209..2fe91d1 100644 --- a/endpoints/radio.py +++ b/endpoints/radio.py @@ -433,28 +433,8 @@ class Radio(FastAPI): next["start"] = time_started next["end"] = time_ends - # Use BackgroundTasks with a sync wrapper for LRC fetch/cache - def lrc_fetch_sync(station, track_json): - import asyncio - try: - async def lrc_fetch(): - async with self.lrc_cache_locks[station]: - self.lrc_cache.pop(station, None) - lrc, source = await self._fetch_and_cache_lrc(station, track_json) - if lrc: - self.lrc_cache[station] = lrc - else: - self.lrc_cache[station] = None - if lrc: - await self.broadcast_lrc(station, lrc, source) - asyncio.run(lrc_fetch()) - except Exception as e: - logging.error(f"[LRC] Error during LRC fetch/cache: {e}") - try: - # Pass a copy of the track dict to avoid mutation issues - background_tasks.add_task(lrc_fetch_sync, data.station, next.copy()) - except Exception as e: - logging.error(f"[LRC] Could not schedule LRC fetch task: {e}") + # Use BackgroundTasks for LRC fetch/cache + background_tasks.add_task(self._do_lrc_fetch, data.station, next.copy()) try: background_tasks.add_task(self.radio_util.webhook_song_change, next, data.station) @@ -818,3 +798,18 @@ class Radio(FastAPI): except Exception as e: logging.error(f"[LRC] Error fetching lyrics: {e}") return None, "None" + + async def _do_lrc_fetch(self, station: str, track_json: dict): + """Fetch and cache LRC for a station's track.""" + try: + async with self.lrc_cache_locks[station]: + self.lrc_cache.pop(station, None) + lrc, source = await self._fetch_and_cache_lrc(station, track_json) + if lrc: + self.lrc_cache[station] = lrc + else: + self.lrc_cache[station] = None + if lrc: + await self.broadcast_lrc(station, lrc, source) + except Exception as e: + logging.error(f"[LRC] Error during LRC fetch/cache: {e}")