api/endpoints/lastfm.py

226 lines
7.1 KiB
Python
Raw Permalink Normal View History

2024-08-11 17:28:43 -04:00
import importlib
2025-01-15 20:17:49 -05:00
import traceback
2025-02-15 21:09:33 -05:00
from typing import Optional, Union
2024-08-11 17:28:43 -04:00
from fastapi import FastAPI
2025-02-15 21:09:33 -05:00
from fastapi.responses import JSONResponse
from .constructors import (
ValidArtistSearchRequest,
ValidAlbumDetailRequest,
ValidTrackInfoRequest,
LastFMException,
)
2024-08-11 17:28:43 -04:00
class LastFM(FastAPI):
"""Last.FM Endpoints"""
def __init__(self, app: FastAPI, util, constants) -> None:
2025-02-15 21:09:33 -05:00
self.app: FastAPI = app
2024-08-11 17:28:43 -04:00
self.util = util
self.constants = constants
2025-02-18 14:57:05 -05:00
self.lastfm = importlib.import_module("utils.lastfm_wrapper").LastFM()
2024-08-11 17:28:43 -04:00
2025-02-14 16:07:24 -05:00
self.endpoints: dict = {
2025-02-05 20:23:06 -05:00
"lastfm/get_artist_by_name": self.artist_by_name_handler,
"lastfm/get_artist_albums": self.artist_album_handler,
"lastfm/get_release": self.release_detail_handler,
"lastfm/get_release_tracklist": self.release_tracklist_handler,
"lastfm/get_track_info": self.track_info_handler,
# tbd
}
2024-08-11 17:28:43 -04:00
for endpoint, handler in self.endpoints.items():
app.add_api_route(
f"/{endpoint}", handler, methods=["POST"], include_in_schema=True
)
async def artist_by_name_handler(
self, data: ValidArtistSearchRequest
) -> JSONResponse:
2024-08-11 17:28:43 -04:00
"""
Get artist info
2025-02-05 20:23:06 -05:00
- **a**: Artist to search
2024-08-11 17:28:43 -04:00
"""
2025-02-11 20:01:07 -05:00
artist: Optional[str] = data.a.strip()
2024-08-11 17:28:43 -04:00
if not artist:
return JSONResponse(
content={
"err": True,
"errorText": "No artist specified",
}
)
2024-08-11 17:28:43 -04:00
artist_result = await self.lastfm.search_artist(artist=artist)
if (
not artist_result
or not artist_result.get("bio")
or "err" in artist_result.keys()
):
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "Search failed (no results?)",
},
)
return JSONResponse(
content={
"success": True,
"result": artist_result,
}
)
async def artist_album_handler(
self, data: ValidArtistSearchRequest
) -> JSONResponse:
2024-08-11 17:33:33 -04:00
"""
Get artist's albums/releases
2025-02-05 20:23:06 -05:00
- **a**: Artist to search
2024-08-11 17:33:33 -04:00
"""
2025-02-11 20:01:07 -05:00
artist: str = data.a.strip()
2024-08-11 17:33:33 -04:00
if not artist:
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "Invalid request: No artist specified",
},
)
album_result: Union[dict, list[dict]] = await self.lastfm.get_artist_albums(
artist=artist
)
2025-02-16 06:36:31 -05:00
if isinstance(album_result, dict):
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "General failure.",
},
)
2025-02-11 20:01:07 -05:00
album_result_out: list = []
seen_release_titles: list = []
2024-08-11 17:33:33 -04:00
for release in album_result:
release_title: str = release.get("title", "Unknown")
2024-08-11 17:33:33 -04:00
if release_title.lower() in seen_release_titles:
continue
seen_release_titles.append(release_title.lower())
album_result_out.append(release)
2024-08-11 17:40:10 -04:00
return JSONResponse(content={"success": True, "result": album_result_out})
2024-08-11 17:40:10 -04:00
async def release_detail_handler(
self, data: ValidAlbumDetailRequest
) -> JSONResponse:
2024-08-11 17:40:10 -04:00
"""
Get details of a particular release by an artist
2025-02-05 20:23:06 -05:00
- **a**: Artist to search
2025-02-11 20:01:07 -05:00
- **release**: Release title to search
2024-08-11 17:40:10 -04:00
"""
2025-02-11 20:01:07 -05:00
artist: str = data.a.strip()
release: str = data.release.strip()
2024-08-11 17:40:10 -04:00
if not artist or not release:
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "Invalid request",
},
)
2024-08-11 17:40:10 -04:00
release_result = await self.lastfm.get_release(artist=artist, album=release)
ret_obj = {
"id": release_result.get("id"),
"artists": release_result.get("artists"),
"title": release_result.get("title"),
"summary": release_result.get("summary"),
"tracks": release_result.get("tracks"),
}
return JSONResponse(
content={
"success": True,
"result": ret_obj,
}
)
async def release_tracklist_handler(
self, data: ValidAlbumDetailRequest
) -> JSONResponse:
2024-08-14 07:43:55 -04:00
"""
Get track list for a particular release by an artist
2025-02-05 20:23:06 -05:00
- **a**: Artist to search
- **release**: Release title to search
2024-08-14 07:43:55 -04:00
"""
2025-02-11 20:01:07 -05:00
artist: str = data.a.strip()
release: str = data.release.strip()
2024-08-14 07:43:55 -04:00
if not artist or not release:
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "Invalid request",
},
)
tracklist_result: dict = await self.lastfm.get_album_tracklist(
artist=artist, album=release
)
return JSONResponse(
content={
"success": True,
"id": tracklist_result.get("id"),
"artists": tracklist_result.get("artists"),
"title": tracklist_result.get("title"),
"summary": tracklist_result.get("summary"),
"tracks": tracklist_result.get("tracks"),
}
)
2024-08-14 08:06:02 -04:00
2025-02-15 21:09:33 -05:00
async def track_info_handler(self, data: ValidTrackInfoRequest) -> JSONResponse:
2024-08-14 08:06:02 -04:00
"""
Get track info from Last.FM given an artist/track
- **a**: Artist to search
- **t**: Track title to search
"""
2025-01-15 20:17:49 -05:00
try:
2025-02-11 20:01:07 -05:00
artist: str = data.a
track: str = data.t
2025-01-15 20:17:49 -05:00
if not artist or not track:
return JSONResponse(
status_code=500,
content={"err": True, "errorText": "Invalid request"},
)
track_info_result: Optional[dict] = await self.lastfm.get_track_info(
artist=artist, track=track
)
2025-02-18 06:55:47 -05:00
if not track_info_result:
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "Not found.",
},
)
2025-02-11 20:01:07 -05:00
if "err" in track_info_result:
raise LastFMException(
"Unknown error occurred: %s",
track_info_result.get("errorText", "??"),
)
return JSONResponse(content={"success": True, "result": track_info_result})
2025-01-15 20:17:49 -05:00
except:
traceback.print_exc()
return JSONResponse(
status_code=500,
content={
"err": True,
"errorText": "General error",
},
)