41 lines
1.6 KiB
Python
41 lines
1.6 KiB
Python
from datetime import datetime, timedelta, UTC
|
|
from typing import Dict, List
|
|
from requests import get
|
|
from musicbrainz_entities import MbRecording, MbArtist
|
|
from time import sleep
|
|
|
|
class MusicBrainz:
|
|
def __init__(self, application_name: str, version: str, contact: str, root_url: str = "https://musicbrainz.org/ws/2/"):
|
|
self._user_agent_string = f"{application_name}/{version} ( {contact} )"
|
|
self._last_request_time = datetime.now(UTC) + timedelta(seconds=-1)
|
|
self._root_url = root_url
|
|
|
|
def _request(self, method, endpoint:str, params: Dict[str, object] = dict()):
|
|
url = f"{self._root_url.rstrip('/')}/{endpoint.lstrip('/')}"
|
|
params['fmt'] = 'json'
|
|
# TODO: retries
|
|
|
|
if datetime.now(UTC) - self._last_request_time < timedelta(seconds=1):
|
|
sleep(1 - (datetime.now(UTC) - self._last_request_time).total_seconds())
|
|
|
|
response = method(url, params=params)
|
|
self._last_request_time = datetime.now(UTC)
|
|
return response
|
|
|
|
def isrc_lookup(self, isrc: str) -> List[MbRecording]:
|
|
result = self._request(get, f"/isrc/{isrc}", { 'inc': 'artists+isrcs+releases+url-rels' })
|
|
return [MbRecording(recording) for recording in result.json()['recordings']]
|
|
|
|
def get_artist_by_id(self, id: str) -> MbArtist:
|
|
result = self._request(get, f'/artist/{id}', { 'inc': 'genres' })
|
|
return MbArtist(result.json())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
mb = MusicBrainz("pob_tag_test", "0.1", "musicbrainz@pobnellion.com")
|
|
|
|
res = mb.isrc_lookup('JPPC09428330')
|
|
print(res[0].title)
|
|
artist = mb.get_artist_by_id(res[0].artist_credit[0].id)
|
|
print(artist.name)
|