api/lastfm_wrapper.py

289 lines
11 KiB
Python
Raw Normal View History

2025-01-11 20:59:10 -05:00
#!/usr/bin/env python3.12
# pylint: disable=bare-except, broad-exception-caught, invalid-name
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-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"""
2025-02-12 19:33:51 -05:00
def __init__(self, noInit: Optional[bool] = False) -> None: # pylint: disable=unused-argument
2024-08-19 14:22:21 -04:00
self.creds = Constants().LFM_CREDS
2025-02-12 19:33:51 -05:00
self.api_base_url: str = "https://ws.audioscrobbler.com/2.0/?method="
2024-08-19 14:22:21 -04:00
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 {
2025-02-12 19:33:51 -05:00
'err': 'No artist specified.',
2024-08-19 14:22:21 -04:00
}
async with ClientSession() as session:
2025-02-05 20:23:06 -05:00
async with await session.get(f"{self.api_base_url}artist.getinfo&artist={artist}&api_key={self.creds.get('key')}&autocorrect=1&format=json",
2025-01-11 20:59:10 -05:00
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()
2025-02-14 16:07:24 -05:00
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'),
2025-02-14 16:07:24 -05:00
'bio': data.get('bio', None).get('summary').strip()\
2025-02-12 19:33:51 -05:00
.split("<a href")[0],
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 {
2025-02-12 19:33:51 -05:00
'err': 'Failed',
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
async def get_track_info(self, artist: Optional[str] = None,
track: Optional[str] = None) -> dict:
"""
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 {
2025-02-12 19:33:51 -05:00
'err': 'Invalid/No artist or track specified',
2024-08-19 14:22:21 -04:00
}
async with ClientSession() as session:
2025-02-05 20:23:06 -05:00
async with await session.get(f"{self.api_base_url}track.getInfo&api_key={self.creds.get('key')}&autocorrect=1&artist={artist}&track={track}&format=json",
2025-01-11 20:59:10 -05:00
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()
2025-02-14 16:07:24 -05:00
data = data.get('track', None)
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
2025-02-14 16:07:24 -05:00
'artist_mbid': data.get('artist', None).get('mbid'),
'album': data.get('album', None).get('title'),
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 {
2025-02-12 19:33:51 -05:00
'err': 'General Failure',
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
async def get_album_tracklist(self, artist: Optional[str] = None,
album: Optional[str] = None) -> dict:
"""
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 {
2025-02-12 19:33:51 -05:00
'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,
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 {
2025-02-12 19:33:51 -05:00
'err': 'General Failure',
2024-08-19 14:22:21 -04:00
}
2025-02-15 21:09:33 -05:00
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 {
2025-02-12 19:33:51 -05:00
'err': 'No artist specified.',
2024-08-19 14:22:21 -04:00
}
async with ClientSession() as session:
2025-02-05 20:23:06 -05:00
async with await session.get(f"{self.api_base_url}artist.gettopalbums&artist={artist}&api_key={self.creds.get('key')}&autocorrect=1&format=json",
2025-01-11 20:59:10 -05:00
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 = data.get('topalbums', None).get('album')
ret_obj: list = [
2024-08-19 14:22:21 -04:00
{
'title': item.get('name')
2025-01-11 20:59:10 -05:00
} 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
]
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 {
2025-02-12 19:33:51 -05:00
'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
2025-02-12 19:33:51 -05:00
artist_search: dict = await self.search_artist(artist=artist)
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
2025-02-12 19:33:51 -05:00
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
2024-08-19 14:22:21 -04:00
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 {
2025-02-12 19:33:51 -05:00
'err': 'Invalid/no artist_id specified.',
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
req_url: str = f"{self.api_base_url}artists/{artist_id}?key={self.creds.get('key')}\
&secret={self.creds.get('secret')}"
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
2025-02-12 19:33:51 -05:00
async with await session.get(req_url,
2025-01-11 20:59:10 -05:00
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()
2024-08-19 14:22:21 -04:00
2025-02-12 19:33:51 -05:00
ret_obj: dict = {
2024-08-19 14:22:21 -04:00
'id': data.get('id'),
'name': data.get('name'),
'profile': regex.sub(r"(\[(\/{0,})(u|b|i)])", "", data.get('profile')),
2025-02-12 19:33:51 -05:00
'members': data.get('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 {
2025-02-12 19:33:51 -05:00
'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 {
2025-02-12 19:33:51 -05:00
'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-02-14 16:07:24 -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 {
2025-01-11 20:59:10 -05:00
'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 {
2025-02-12 19:33:51 -05:00
'err': 'Failed',
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
async def get_release(self, artist: Optional[str] = None,
album: Optional[str] = None) -> dict:
"""
Get Release info from LastFM
Args:
artist (Optional[str])
album (Optioanl[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 album:
2024-08-19 14:22:21 -04:00
return {
2025-02-12 19:33:51 -05:00
'err': 'Invalid artist/album pair',
2024-08-19 14:22:21 -04:00
}
2025-02-12 19:33:51 -05:00
req_url: str = f"{self.api_base_url}album.getinfo&artist={artist}&album={album}\
&api_key={self.creds.get('key')}&autocorrect=1&format=json"
2024-08-19 14:22:21 -04:00
async with ClientSession() as session:
2025-02-12 19:33:51 -05:00
async with await session.get(req_url,
2025-01-11 20:59:10 -05:00
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 = {
2024-08-19 14:22:21 -04:00
'id': data.get('mbid'),
'artists': data.get('artist'),
'tags': data.get('tags'),
'title': data.get('name'),
2025-02-14 16:07:24 -05:00
'summary': data.get('wiki', None).get('summary').split("<a href")[0]\
2025-02-12 19:33:51 -05:00
if "wiki" in data.keys()\
else "No summary available for this release.",
2024-08-19 14:22:21 -04:00
}
try:
2025-02-14 16:07:24 -05:00
track_key: list = data.get('tracks', None).get('track')
2025-01-11 20:59:10 -05:00
except:
2025-02-14 16:07:24 -05:00
track_key = []
2025-01-11 20:59:10 -05:00
if isinstance(track_key, list):
2025-02-12 19:33:51 -05:00
ret_obj['tracks'] = [
2024-08-19 14:22:21 -04:00
{
'duration': item.get('duration', 'N/A'),
2025-02-12 19:33:51 -05:00
'title': item.get('name'),
2024-08-19 14:22:21 -04:00
} for item in track_key]
else:
2025-02-12 19:33:51 -05:00
ret_obj['tracks'] = [
2024-08-19 14:22:21 -04:00
{
2025-02-12 19:33:51 -05:00
'duration': data.get('tracks').get('track')\
.get('duration'),
'title': data.get('tracks').get('track')\
.get('name'),
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 {
2025-02-12 19:33:51 -05:00
'err': 'Failed',
}