webhook / album art changes

This commit is contained in:
codey 2025-02-11 15:21:01 -05:00
parent 7145e86ded
commit 55bd485af4
2 changed files with 49 additions and 41 deletions

View File

@ -69,6 +69,7 @@ class Radio(FastAPI):
app.add_api_route("/radio/album_art", self.album_art_handler, methods=["GET"], app.add_api_route("/radio/album_art", self.album_art_handler, methods=["GET"],
include_in_schema=True) include_in_schema=True)
asyncio.get_event_loop().run_until_complete(self.load_playlist()) asyncio.get_event_loop().run_until_complete(self.load_playlist())
asyncio.get_event_loop().run_until_complete(self._ls_skip())
def get_queue_item_by_uuid(self, uuid: str) -> tuple[int, dict] | None: def get_queue_item_by_uuid(self, uuid: str) -> tuple[int, dict] | None:
@ -269,7 +270,8 @@ class Radio(FastAPI):
query = "SELECT album_art FROM tracks WHERE id = ?" query = "SELECT album_art FROM tracks WHERE id = ?"
query_params = (track_id,) query_params = (track_id,)
if file_path: if file_path and not track_id:
logging.info("Searchijng w filePath %s", file_path)
query = "SELECT album_art FROM tracks WHERE file_path = ?" query = "SELECT album_art FROM tracks WHERE file_path = ?"
query_params = (file_path,) query_params = (file_path,)
@ -295,7 +297,8 @@ class Radio(FastAPI):
file_path = file_path.replace("/paul/toons/", file_path = file_path.replace("/paul/toons/",
"/singer/gogs_toons/") "/singer/gogs_toons/")
logging.info("Seeking %s", original_file_path) logging.info("Seeking %s", original_file_path)
cached_album_art = await self.get_album_art(file_path=original_file_path) cached_album_art = await self.get_album_art(file_path=original_file_path,
track_id=track_id)
if cached_album_art: if cached_album_art:
logging.info("Returning from cache!") logging.info("Returning from cache!")
return cached_album_art return cached_album_art
@ -308,9 +311,10 @@ class Radio(FastAPI):
traceback.print_exc() traceback.print_exc()
# TODO: Optimize/cache # TODO: Optimize/cache
async def album_art_handler(self, request: Request) -> bytes: async def album_art_handler(self, request: Request, track_id: Optional[int] = None) -> bytes:
try: try:
album_art = await self._get_album_art() logging.info("Seeking album art with trackId: %s", track_id)
album_art = await self._get_album_art(track_id=track_id)
if not album_art: if not album_art:
return RedirectResponse(url="https://codey.lol/images/radio_art_default.jpg", return RedirectResponse(url="https://codey.lol/images/radio_art_default.jpg",
status_code=302) status_code=302)
@ -337,7 +341,7 @@ class Radio(FastAPI):
async def radio_get_next(self, data: ValidRadioNextRequest, request: Request, async def radio_get_next(self, data: ValidRadioNextRequest, request: Request,
background_tasks: BackgroundTasks) -> dict: background_tasks: BackgroundTasks) -> Optional[dict]:
""" """
Get next track Get next track
Args: Args:
@ -349,42 +353,43 @@ class Radio(FastAPI):
""" """
if not self.util.check_key(path=request.url.path, req_type=4, key=data.key): if not self.util.check_key(path=request.url.path, req_type=4, key=data.key):
raise HTTPException(status_code=403, detail="Unauthorized") raise HTTPException(status_code=403, detail="Unauthorized")
if not isinstance(self.active_playlist, list) or not self.active_playlist:
if isinstance(self.active_playlist, list) and self.active_playlist: await self.load_playlist()
next = self.active_playlist.pop(0) await self._ls_skip()
if not isinstance(next, dict): return
logging.info("next is of type: %s, reloading playlist...", type(next)) next = self.active_playlist.pop(0)
await self.load_playlist() if not isinstance(next, dict):
return await self.radio_pop_track(request, recursion_type="not dict: next") logging.info("next is of type: %s, reloading playlist...", type(next))
await self.load_playlist()
duration = next['duration'] await self._ls_skip()
time_started = int(time.time()) return
time_ends = int(time_started + duration)
duration = next['duration']
if len(self.active_playlist) > 1: time_started = int(time.time())
self.active_playlist.append(next) # Push to end of playlist time_ends = int(time_started + duration)
else:
await self.load_playlist() if len(self.active_playlist) > 1:
self.active_playlist.append(next) # Push to end of playlist
logging.info("Returning %s", next['artistsong'])
# logging.info("Top 5 songs in playlist: %s, bottom: %s",
# self.active_playlist[0:6], self.active_playlist[-6:])
self.now_playing = next
next['start'] = time_started
next['end'] = time_ends
try:
background_tasks.add_task(self.radio_util.webhook_song_change, next)
except Exception as e:
traceback.print_exc()
try:
if not await self.get_album_art(file_path=next['file_path']):
album_art = await self._get_album_art(next['file_path'])
await self.cache_album_art(next['id'], album_art)
except:
traceback.print_exc()
return next
else: else:
return await self.radio_pop_track(request, recursion_type="not list: self.active_playlist") await self.load_playlist()
logging.info("Returning %s", next['artistsong'])
# logging.info("Top 5 songs in playlist: %s, bottom: %s",
# self.active_playlist[0:6], self.active_playlist[-6:])
self.now_playing = next
next['start'] = time_started
next['end'] = time_ends
try:
background_tasks.add_task(self.radio_util.webhook_song_change, next)
except Exception as e:
traceback.print_exc()
try:
if not await self.get_album_art(file_path=next['file_path']):
album_art = await self._get_album_art(next['file_path'])
await self.cache_album_art(next['id'], album_art)
except:
traceback.print_exc()
return next
async def radio_request(self, data: ValidRadioSongRequest, request: Request) -> Response: async def radio_request(self, data: ValidRadioSongRequest, request: Request) -> Response:

View File

@ -65,8 +65,11 @@ class RadioUtil:
'username': 'serious.FM', 'username': 'serious.FM',
"embeds": [{ "embeds": [{
"title": "Now Playing", "title": "Now Playing",
"description": f'# {track['song']}\nby **{track['artist']}**', "description": f'## {track['song']}\nby\n## {track['artist']}',
"color": 0x30c56f, "color": 0x30c56f,
"thumbnail": {
"url": f"https://api.codey.lol/radio/album_art?track_id={track['id']}&{time.time()}",
},
"fields": [ "fields": [
{ {
"name": "Duration", "name": "Duration",