api/utils/lastfm_wrapper.py

366 lines
12 KiB
Python
Raw Normal View History

2024-08-19 14:22:21 -04:00
import traceback
2025-01-11 20:59:10 -05:00
import logging
2025-02-14 16:07:24 -05:00
from typing import Optional, Union
2025-01-11 20:59:10 -05:00
import regex
from aiohttp import ClientSession, ClientTimeout
2024-08-19 14:22:21 -04:00
from constants import Constants
2025-02-18 14:56:24 -05:00
from .constructors import InvalidLastFMResponseException
2025-01-11 20:59:10 -05:00
2024-08-19 14:22:21 -04:00
class LastFM:
2025-01-11 20:59:10 -05:00
"""LastFM Endpoints"""
def __init__(self, noInit: Optional[bool] = False) -> None:
2024-08-19 14:22:21 -04:00
self.creds = Constants().LFM_CREDS
2025-02-18 15:13:07 -05:00
self.api_base_url: str = "https://ws.audioscrobbler.com/2.0"
2025-02-12 19:33:51 -05:00
async def search_artist(self, artist: Optional[str] = None) -> dict:
2025-01-11 20:59:10 -05:00
"""Search LastFM for an artist"""
2024-08-19 14:22:21 -04:00
try:
2025-02-15 21:09:33 -05:00
if not artist:
2024-08-19 14:22:21 -04:00
return {
"err": "No artist specified.",
2024-08-19 14:22:21 -04:00
}
2025-02-18 15:13:07 -05:00
request_params: list[tuple] = [
("method", "artist.getInfo"),
("artist", artist),
("api_key", self.creds.get("key")),
2025-02-18 15:13:07 -05:00
("autocorrect", "1"),
("format", "json"),
]
async with ClientSession() as session:
async with await session.get(
self.api_base_url,
params=request_params,
timeout=ClientTimeout(connect=3, sock_read=8),
) as request:
2025-02-12 19:33:51 -05:00
request.raise_for_status()
data: dict = await request.json()
data = data.get("artist", "N/A")
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
"id": data.get("mbid"),
"touring": data.get("ontour"),
"name": data.get("name"),
"bio": data.get("bio", None)
.get("summary")
.strip()
.split("<a href")[0],
}
2025-02-12 19:33:51 -05:00
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
2024-08-19 14:22:21 -04:00
}
async def get_track_info(
self, artist: Optional[str] = None, track: Optional[str] = None
) -> Optional[dict]:
2025-02-12 19:33:51 -05:00
"""
Get Track Info from LastFM
Args:
artist (Optional[str])
track (Optional[str])
Returns:
dict
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-12 19:33:51 -05:00
if not artist or not track:
2025-01-11 20:59:10 -05:00
logging.info("inv request")
2024-08-19 14:22:21 -04:00
return {
"err": "Invalid/No artist or track specified",
2024-08-19 14:22:21 -04:00
}
2025-02-18 15:13:07 -05:00
request_params: list[tuple] = [
("method", "track.getInfo"),
("api_key", self.creds.get("key")),
2025-02-18 15:13:07 -05:00
("autocorrect", "1"),
("artist", artist),
("track", track),
("format", "json"),
]
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
async with await session.get(
self.api_base_url,
params=request_params,
timeout=ClientTimeout(connect=3, sock_read=8),
) as request:
2025-02-12 19:33:51 -05:00
request.raise_for_status()
data: dict = await request.json()
data = data.get("track", None)
if not isinstance(data.get("artist"), dict):
2025-02-18 06:55:47 -05:00
return None
artist_mbid: int = data.get("artist", None).get("mbid")
album: str = data.get("album", None).get("title")
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
"artist_mbid": artist_mbid,
"album": album,
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "General Failure",
2024-08-19 14:22:21 -04:00
}
async def get_album_tracklist(
self, artist: Optional[str] = None, album: Optional[str] = None
) -> dict:
2025-02-12 19:33:51 -05:00
"""
Get Album Tracklist
Args:
artist (str)
album (str)
Returns:
dict
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-15 21:09:33 -05:00
if not artist or not album:
2024-08-19 14:22:21 -04:00
return {
"err": "No artist or album specified",
2024-08-19 14:22:21 -04:00
}
2025-02-14 16:07:24 -05:00
tracks: dict = await self.get_release(artist=artist, album=album)
tracks = tracks.get("tracks", None)
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
"tracks": tracks,
}
2025-02-12 19:33:51 -05:00
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "General Failure",
}
async def get_artist_albums(
self, artist: Optional[str] = None
) -> Union[dict, list[dict]]:
2025-02-12 19:33:51 -05:00
"""
Get Artists Albums from LastFM
Args:
artist (Optional[str])
Returns:
2025-02-15 21:09:33 -05:00
Union[dict, list[dict]]
2025-02-12 19:33:51 -05:00
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-15 21:09:33 -05:00
if not artist:
2024-08-19 14:22:21 -04:00
return {
"err": "No artist specified.",
2024-08-19 14:22:21 -04:00
}
2025-02-18 15:13:07 -05:00
request_params: list[tuple] = [
("method", "artist.gettopalbums"),
("artist", artist),
("api_key", self.creds.get("key")),
2025-02-18 15:13:07 -05:00
("autocorrect", "1"),
("format", "json"),
]
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
async with await session.get(
self.api_base_url,
params=request_params,
timeout=ClientTimeout(connect=3, sock_read=8),
) as request:
2025-02-12 19:33:51 -05:00
request.raise_for_status()
2025-02-14 16:07:24 -05:00
json_data: dict = await request.json()
data: dict = json_data.get("topalbums", None).get("album")
2025-02-14 16:07:24 -05:00
ret_obj: list = [
{"title": item.get("name")}
for item in data
if not (item.get("name").lower() == "(null)")
and int(item.get("playcount")) >= 50
2024-08-19 14:22:21 -04:00
]
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
2024-08-19 14:22:21 -04:00
}
2025-02-14 16:07:24 -05:00
async def get_artist_id(self, artist: Optional[str] = None) -> int:
2025-02-12 19:33:51 -05:00
"""
Get Artist ID from LastFM
Args:
artist (Optional[str])
Returns:
2025-02-15 21:09:33 -05:00
int
2025-02-12 19:33:51 -05:00
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-15 21:09:33 -05:00
if not artist:
2025-02-14 16:07:24 -05:00
return -1
artist_search: dict = await self.search_artist(artist=artist)
2025-02-12 19:33:51 -05:00
if not artist_search:
2025-01-11 20:59:10 -05:00
logging.debug("[get_artist_id] Throwing no result error")
2025-02-14 16:07:24 -05:00
return -1
artist_id: int = int(artist_search[0].get("id", 0))
2024-08-19 14:22:21 -04:00
return artist_id
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2025-02-14 16:07:24 -05:00
return -1
2025-02-12 19:33:51 -05:00
async def get_artist_info_by_id(self, artist_id: Optional[int] = None) -> dict:
"""
Get Artist info by ID from LastFM
Args:
artist_id (Optional[int])
Returns:
dict
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-12 19:33:51 -05:00
if not artist_id or not str(artist_id).isnumeric():
2024-08-19 14:22:21 -04:00
return {
"err": "Invalid/no artist_id specified.",
2024-08-19 14:22:21 -04:00
}
2025-02-18 15:14:15 -05:00
req_url: str = f"{self.api_base_url}/artists/{artist_id}"
2025-02-18 15:13:07 -05:00
request_params: list[tuple] = [
("key", self.creds.get("key")),
("secret", self.creds.get("secret")),
2025-02-18 15:13:07 -05:00
]
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
async with await session.get(
req_url,
params=request_params,
timeout=ClientTimeout(connect=3, sock_read=8),
) as request:
2025-02-12 19:33:51 -05:00
request.raise_for_status()
data: dict = await request.json()
if not data.get("profile"):
raise InvalidLastFMResponseException(
"Data did not contain 'profile' key."
)
_id: int = data.get("id", None)
name: str = data.get("name", None)
profile: str = data.get("profile", "")
2025-02-18 14:56:24 -05:00
profile = regex.sub(r"(\[(\/{0,})(u|b|i)])", "", profile)
members: list = data.get("members", None)
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
"id": _id,
"name": name,
"profile": profile,
"members": members,
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
async def get_artist_info(self, artist: Optional[str] = None) -> dict:
"""
Get Artist Info from LastFM
Args:
artist (Optional[str])
Returns:
dict
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-12 19:33:51 -05:00
if not artist:
2024-08-19 14:22:21 -04:00
return {
"err": "No artist specified.",
2024-08-19 14:22:21 -04:00
}
2025-02-14 16:07:24 -05:00
artist_id: Optional[int] = await self.get_artist_id(artist=artist)
2025-02-12 19:33:51 -05:00
if not artist_id:
2025-01-11 20:59:10 -05:00
return {
"err": "Failed",
2025-01-11 20:59:10 -05:00
}
artist_info: Optional[dict] = await self.get_artist_info_by_id(
artist_id=artist_id
)
2025-02-12 19:33:51 -05:00
if not artist_info:
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
2024-08-19 14:22:21 -04:00
}
return artist_info
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
2024-08-19 14:22:21 -04:00
}
async def get_release(
self, artist: Optional[str] = None, album: Optional[str] = None
) -> dict:
2025-02-12 19:33:51 -05:00
"""
Get Release info from LastFM
Args:
artist (Optional[str])
2025-02-18 15:17:35 -05:00
album (Optional[str])
2025-02-12 19:33:51 -05:00
Returns:
dict
"""
2024-08-19 14:22:21 -04:00
try:
2025-02-12 19:33:51 -05:00
if not artist or not album:
2024-08-19 14:22:21 -04:00
return {
"err": "Invalid artist/album pair",
2024-08-19 14:22:21 -04:00
}
2025-02-18 15:13:07 -05:00
request_params: list[tuple] = [
("method", "album.getinfo"),
("artist", artist),
("album", album),
("api_key", self.creds.get("key")),
2025-02-18 15:13:07 -05:00
("autocorrect", "1"),
("format", "json"),
]
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
async with await session.get(
self.api_base_url,
params=request_params,
timeout=ClientTimeout(connect=3, sock_read=8),
) as request:
2025-02-12 19:33:51 -05:00
request.raise_for_status()
2025-02-14 16:07:24 -05:00
json_data: dict = await request.json()
data: dict = json_data.get("album", None)
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
"id": data.get("mbid"),
"artists": data.get("artist"),
"tags": data.get("tags"),
"title": data.get("name"),
"summary": (
data.get("wiki", None).get("summary").split("<a href")[0]
if "wiki" in data.keys()
else "No summary available for this release."
),
2024-08-19 14:22:21 -04:00
}
try:
track_key: list = data.get("tracks", None).get("track")
except:
2025-02-14 16:07:24 -05:00
track_key = []
2025-01-11 20:59:10 -05:00
if isinstance(track_key, list):
ret_obj["tracks"] = [
2024-08-19 14:22:21 -04:00
{
"duration": item.get("duration", "N/A"),
"title": item.get("name"),
}
for item in track_key
]
2024-08-19 14:22:21 -04:00
else:
ret_obj["tracks"] = [
{
"duration": data.get("tracks")
.get("track")
.get("duration"),
"title": data.get("tracks").get("track").get("name"),
}
]
2025-02-12 19:33:51 -05:00
return ret_obj
2024-08-19 14:22:21 -04:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
"err": "Failed",
}