Refactor LRC fetching logic to use BackgroundTasks directly and encapsulate in a new async method

This commit is contained in:
2025-09-27 09:28:47 -04:00
parent 566f1f6692
commit 0bd2b6b4f3

View File

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