55 lines
No EOL
2.3 KiB
Python
55 lines
No EOL
2.3 KiB
Python
from enum import Enum
|
|
from typing import Literal
|
|
import requests
|
|
import urllib.parse
|
|
|
|
API_BASE = 'https://api.jamendo.com/v3.0/'
|
|
ImageSize = Literal[25, 35, 50, 55, 60, 65, 70, 75, 85, 100, 130, 150, 200, 300, 400, 500, 600]
|
|
AudioFormat = Literal['mp31', 'mp32', 'ogg', 'flac']
|
|
VocalInstrumental = Literal['vocal', 'instrumental']
|
|
AcousticElectric = Literal['acoustic', 'electric']
|
|
Order = Literal['relevance', 'buzzrate', 'downloads_week', 'downloads_month', 'downloads_total', 'listens_week', 'listens_month', 'listens_total', 'popularity_week', 'popularity_month', 'popularity_total', 'name', 'album_name', 'artist_name', 'releasedate', 'duration', 'id']
|
|
Speed = Literal['verylow', 'low', 'medium', 'high', 'veryhigh']
|
|
|
|
class JamendoClient:
|
|
def __init__(self, client_id: str):
|
|
self._client_id = client_id
|
|
self._session = requests.session()
|
|
|
|
def tracks(self, tags: str, offset: int = 0, order: Order = 'relevance',
|
|
audioformat: AudioFormat = 'ogg', imagesize: ImageSize = 600,
|
|
vocalinstrumental: VocalInstrumental = None,
|
|
acousticelectric: AcousticElectric = None,
|
|
speed: Speed = None, ccsa: bool = False,
|
|
ccnd: bool = False, ccnc: bool = False,
|
|
):
|
|
params = {
|
|
'client_id': self._client_id,
|
|
'offset': offset,
|
|
'format': 'json',
|
|
'tags': urllib.parse.quote(tags),
|
|
'audioformat': audioformat,
|
|
'imagesize': imagesize,
|
|
'ccsa': ccsa,
|
|
'ccnd': ccnd,
|
|
'ccnc': ccnc,
|
|
'limit': 5
|
|
}
|
|
if vocalinstrumental: params['vocalinstrumental'] = urllib.parse.quote(vocalinstrumental)
|
|
if acousticelectric: params['acousticelectric'] = urllib.parse.quote(acousticelectric)
|
|
if speed: params['speed'] = urllib.parse.quote(speed)
|
|
|
|
url = urllib.parse.urljoin(API_BASE, f'tracks/?{urllib.parse.urlencode(params)}')
|
|
|
|
with self._session.get(url) as r:
|
|
r.raise_for_status()
|
|
result = r.json()
|
|
|
|
if 'results' in result:
|
|
return result['results']
|
|
|
|
def download(self, url: str, fp):
|
|
with self._session.get(url, stream=True) as r:
|
|
r.raise_for_status()
|
|
for chunk in r.iter_content(chunk_size=1024):
|
|
fp.write(chunk) |