From b9254f5b9baf35107cae0c91cf9d979fbbfa14aa Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Thu, 19 May 2022 17:33:42 -0500 Subject: Añadida descarga, búsqueda de álbum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ampache/ampache.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 5 deletions(-) (limited to 'src/ampache/ampache.py') diff --git a/src/ampache/ampache.py b/src/ampache/ampache.py index 12ccbd7..64939d9 100644 --- a/src/ampache/ampache.py +++ b/src/ampache/ampache.py @@ -1,4 +1,9 @@ +""" +The main file. The AmpacheClient class allows us to make requests to the +API. +""" from datetime import datetime +from sys import version from ampache import models, exceptions import requests @@ -63,13 +68,14 @@ class AmpacheClient: if not response.ok: response.raise_for_status() - data = response.json() + if headers['Content-type'] == 'application/json': + response = response.json() - if 'error' in data: - self.raise_by_status(models.Error(int(data['error']['errorCode']), - data['error']['errorMessage'])) + if 'error' in response: + self.raise_by_status(models.Error(int(response['error']['errorCode']), + response['error']['errorMessage'])) - return data + return response def authenticate(self): """ @@ -109,6 +115,54 @@ class AmpacheClient: return song + def get_album(self, album_id): + params = { + 'action': 'album_songs', + 'auth': self._auth.auth, + 'filter': album_id, + 'version': self._version + } + headers = { + 'Content-type': 'application/json' + } + data = self.request(params, headers) + album = self.process_album(data) + + return album + + def process_album(self, album_data): + album_id = album_data['song'][0]['album']['id'] + album_title = album_data['song'][0]['album']['name'] + album_artist = album_data['song'][0]['artist']['name'] + songs = [] + + for song in album_data['song']: + new_song = models.Song(song['id'], song['title'], album_title, + album_artist) + songs.append(new_song) + + return models.Album(album_id, album_title, album_artist, songs) + + def download(self, song_id, destination): + """ + Download a song to destination. + """ + params = { + 'action': 'download', + 'auth': self._auth.auth, + 'type': 'song', + 'id': song_id, + 'version': self._version, + 'format': 'mp3' + } + headers = { + 'Content-type': 'audio/mpeg' + } + data = self.request(params, headers) + + with open(destination, 'wb') as song: + song.write(data.content) + def renew_token(self): if datetime.now(self._auth.expires.tzinfo) > self._auth.expires: self.authenticate() -- cgit v1.2.3