api/lastfm_wrapper.py

249 lines
9.6 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
from typing import Union
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"""
def __init__(self, noInit: Union[None, bool] = False): # pylint: disable=unused-argument
2024-08-19 14:22:21 -04:00
self.creds = Constants().LFM_CREDS
self.api_base_url = "https://ws.audioscrobbler.com/2.0/?method="
async def search_artist(self, artist=None):
2025-01-11 20:59:10 -05:00
"""Search LastFM for an artist"""
2024-08-19 14:22:21 -04:00
try:
if artist is None:
return {
'err': 'No artist specified.'
}
async with ClientSession() as session:
2025-01-11 20:59:10 -05:00
async with session.get(f"{self.api_base_url}artist.getinfo&artist={artist}&api_key={self.creds.get('key')}&autocorrect=1&format=json",
timeout=ClientTimeout(connect=3, sock_read=8)) as request:
2024-08-19 14:22:21 -04:00
assert request.status in [200, 204]
data = await request.json()
data = data.get('artist')
2025-01-11 20:59:10 -05:00
logging.debug("Using data:\n%s", data)
2024-08-19 14:22:21 -04:00
# return data.get('results')
retObj = {
'id': data.get('mbid'),
'touring': data.get('ontour'),
'name': data.get('name'),
'bio': data.get('bio').get('summary').strip().split("<a href")[0]
}
return retObj
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
'err': 'Failed'
}
async def get_track_info(self, artist=None, track=None):
2025-01-11 20:59:10 -05:00
"""Get Track Info from LastFM"""
2024-08-19 14:22:21 -04:00
try:
if artist is None or track is None:
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'
}
async with ClientSession() as session:
2025-01-11 20:59:10 -05:00
async with session.get(f"{self.api_base_url}track.getInfo&api_key={self.creds.get('key')}&autocorrect=1&artist={artist}&track={track}&format=json",
timeout=ClientTimeout(connect=3, sock_read=8)) as request:
2024-08-19 14:22:21 -04:00
assert request.status in [200, 204]
data = await request.json()
data = data.get('track')
retObj = {
'artist_mbid': data.get('artist').get('mbid'),
'album': data.get('album').get('title')
}
2025-01-11 20:59:10 -05:00
logging.debug("Returning:\n%s", retObj)
2024-08-19 14:22:21 -04:00
return retObj
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_album_tracklist(self, artist=None, album=None):
2025-01-11 20:59:10 -05:00
"""Get Album Tracklist"""
2024-08-19 14:22:21 -04:00
try:
if artist is None or album is None:
2025-01-11 20:59:10 -05:00
logging.info("inv request")
2024-08-19 14:22:21 -04:00
return {
'err': 'No artist or album specified'
}
tracks = await self.get_release(artist=artist, album=album)
tracks = tracks.get('tracks')
retObj = {
'tracks': tracks
}
2025-01-11 20:59:10 -05:00
logging.debug("Returning:\n%s", retObj)
2024-08-19 14:22:21 -04:00
return retObj
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=None):
2025-01-11 20:59:10 -05:00
"""Get Artists Albums from LastFM"""
2024-08-19 14:22:21 -04:00
try:
if artist is None:
return {
'err': 'No artist specified.'
}
async with ClientSession() as session:
2025-01-11 20:59:10 -05:00
async with session.get(f"{self.api_base_url}artist.gettopalbums&artist={artist}&api_key={self.creds.get('key')}&autocorrect=1&format=json",
timeout=ClientTimeout(connect=3, sock_read=8)) as request:
2024-08-19 14:22:21 -04:00
assert request.status in [200, 204]
data = await request.json()
data = data.get('topalbums').get('album')
retObj = [
{
'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
]
return retObj
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
'err': 'Failed'
}
async def get_artist_id(self, artist=None):
2025-01-11 20:59:10 -05:00
"""Get Artist ID from LastFM"""
2024-08-19 14:22:21 -04:00
try:
if artist is None:
return {
'err': 'No artist specified.'
}
artist_search = await self.search_artist(artist=artist)
if artist_search is None or len(artist_search) < 1:
2025-01-11 20:59:10 -05:00
logging.debug("[get_artist_id] Throwing no result error")
2024-08-19 14:22:21 -04:00
return {
'err': 'No results.'
}
artist_id = artist_search[0].get('id')
return artist_id
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
'err': 'Failed'
}
async def get_artist_info_by_id(self, artist_id=None):
2025-01-11 20:59:10 -05:00
"""Get Artist info by ID from LastFM"""
2024-08-19 14:22:21 -04:00
try:
2025-01-11 20:59:10 -05:00
if artist_id is None or not str(artist_id).isnumeric():
2024-08-19 14:22:21 -04:00
return {
'err': 'Invalid/no artist_id specified.'
}
async with ClientSession() as session:
2025-01-11 20:59:10 -05:00
async with session.get(f"{self.api_base_url}artists/{artist_id}?key={self.creds.get('key')}&secret={self.creds.get('secret')}",
timeout=ClientTimeout(connect=3, sock_read=8)) as request:
2024-08-19 14:22:21 -04:00
assert request.status in [200, 204]
data = await request.json()
retObj = {
'id': data.get('id'),
'name': data.get('name'),
'profile': regex.sub(r"(\[(\/{0,})(u|b|i)])", "", data.get('profile')),
'members': data.get('members')
}
return retObj
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
'err': 'Failed'
}
async def get_artist_info(self, artist=None):
2025-01-11 20:59:10 -05:00
"""Get Artist Info from LastFM"""
2024-08-19 14:22:21 -04:00
try:
if artist is None:
return {
'err': 'No artist specified.'
}
2025-01-11 20:59:10 -05:00
artist_id = await self.get_artist_id(artist=artist)
if artist_id is None:
return {
'err': 'Failed',
}
2024-08-27 20:47:29 -04:00
artist_info = await self.get_artist_info_by_id(artist_id=artist_id)
2024-08-19 14:22:21 -04:00
if artist_info is None:
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 {
'err': 'Failed'
}
async def get_release(self, artist=None, album=None):
2025-01-11 20:59:10 -05:00
"""Get Release info from LastFM"""
2024-08-19 14:22:21 -04:00
try:
if artist is None or album is None:
return {
'err': 'Invalid artist/album pair'
}
async with ClientSession() as session:
2025-01-11 20:59:10 -05:00
async with session.get(f"{self.api_base_url}album.getinfo&artist={artist}&album={album}&api_key={self.creds.get('key')}&autocorrect=1&format=json",
timeout=ClientTimeout(connect=3, sock_read=8)) as request:
2024-08-19 14:22:21 -04:00
assert request.status in [200, 204]
data = await request.json()
data = data.get('album')
retObj = {
'id': data.get('mbid'),
'artists': data.get('artist'),
'tags': data.get('tags'),
'title': data.get('name'),
'summary': data.get('wiki').get('summary').split("<a href")[0] if "wiki" in data.keys() else "No summary available for this release.",
}
try:
track_key = data.get('tracks').get('track')
2025-01-11 20:59:10 -05:00
except:
track_key = []
if isinstance(track_key, list):
logging.debug("Track key: %s", track_key)
2024-08-19 14:22:21 -04:00
retObj['tracks'] = [
{
'duration': item.get('duration', 'N/A'),
'title': item.get('name')
} for item in track_key]
else:
retObj['tracks'] = [
{
'duration': data.get('tracks').get('track').get('duration'),
'title': data.get('tracks').get('track').get('name')
}
]
return retObj
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-08-19 14:22:21 -04:00
return {
'err': 'Failed'
}