From 4dabaec3086bd938c83443e1729cda83e00096e1 Mon Sep 17 00:00:00 2001
From: RemixDev <RemixDev64@gmail.com>
Date: Fri, 12 Mar 2021 15:02:11 +0100
Subject: [PATCH] Some code rework

---
 deezer/__init__.py | 11 +++---
 deezer/api.py      | 23 ++++++------
 deezer/gw.py       | 89 ++++++++++++++++++++++------------------------
 deezer/utils.py    |  2 +-
 4 files changed, 59 insertions(+), 66 deletions(-)

diff --git a/deezer/__init__.py b/deezer/__init__.py
index 3044d74..18ab2c1 100644
--- a/deezer/__init__.py
+++ b/deezer/__init__.py
@@ -1,7 +1,6 @@
 import requests
 from deezer.gw import GW
 from deezer.api import API
-import json
 
 __version__ = "0.0.15"
 
@@ -124,10 +123,8 @@ class Deezer:
             })
 
     def change_account(self, child_n):
-        if len(self.childs)-1 >= child_n:
-            self.current_user =self.childs[child_n]
-            self.selected_account = child_n
-        else:
-            self.current_user = self.childs[0]
-            self.selected_account = 0
+        if len(self.childs)-1 < child_n: child_n = 0
+        self.current_user = self.childs[child_n]
+        self.selected_account = child_n
+
         return (self.current_user, self.selected_account)
diff --git a/deezer/api.py b/deezer/api.py
index ecfa6d6..7859efd 100644
--- a/deezer/api.py
+++ b/deezer/api.py
@@ -28,13 +28,12 @@ class API:
             args = {}
         if self.access_token: args['access_token'] = self.access_token
         try:
-            result = self.session.get(
+            result_json = self.session.get(
                 "https://api.deezer.com/" + method,
                 params=args,
                 headers=self.http_headers,
                 timeout=30
-            )
-            result_json = result.json()
+            ).json()
         except:
             sleep(2)
             return self.api_call(method, args)
@@ -43,14 +42,14 @@ class API:
                 if result_json['error']['code'] in [4, 700]:
                     sleep(5)
                     return self.api_call(method, args)
-                if result_json['error']['code'] == 100: raise ItemsLimitExceededException(f"ItemsLimitExceededException: {method}")
-                if result_json['error']['code'] == 200: raise PermissionException(f"PermissionException: {method}")
-                if result_json['error']['code'] == 300: raise InvalidTokenException(f"InvalidTokenException: {method}")
-                if result_json['error']['code'] == 500: raise WrongParameterException(f"ParameterException: {method}")
-                if result_json['error']['code'] == 501: raise MissingParameterException(f"MissingParameterException: {method}")
-                if result_json['error']['code'] == 600: raise InvalidQueryException(f"InvalidQueryException: {method}")
-                if result_json['error']['code'] == 800: raise DataException(f"DataException: {method}")
-                if result_json['error']['code'] == 901: raise IndividualAccountChangedNotAllowedException(f"IndividualAccountChangedNotAllowedException: {method}")
+                if result_json['error']['code'] == 100: raise ItemsLimitExceededException(f"ItemsLimitExceededException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 200: raise PermissionException(f"PermissionException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 300: raise InvalidTokenException(f"InvalidTokenException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 500: raise WrongParameterException(f"ParameterException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 501: raise MissingParameterException(f"MissingParameterException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 600: raise InvalidQueryException(f"InvalidQueryException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 800: raise DataException(f"DataException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
+                if result_json['error']['code'] == 901: raise IndividualAccountChangedNotAllowedException(f"IndividualAccountChangedNotAllowedException: {method} {result_json['error']['message'] if 'message' in result_json['error'] else ''}")
             raise APIError(json.dumps(result_json['error']))
         return result_json
 
@@ -292,7 +291,7 @@ class API:
         elif " - " in track:
             resp = self.advanced_search(artist=artist, track=track[:track.find(" - ")], limit=1)
             if len(resp['data']) > 0: return resp['data'][0]['id']
-        return 0
+        return "0"
 
 class APIError(Exception):
     """Base class for Deezer exceptions"""
diff --git a/deezer/gw.py b/deezer/gw.py
index f7f16a4..812683f 100644
--- a/deezer/gw.py
+++ b/deezer/gw.py
@@ -36,7 +36,7 @@ class PlaylistStatus():
     PRIVATE = 1
     COLLABORATIVE = 2
 
-EMPTY_TRACK_DICT = {
+EMPTY_TRACK_OBJ = {
     'SNG_ID': 0,
     'SNG_TITLE': '',
     'DURATION': 0,
@@ -63,20 +63,19 @@ class GW:
              'method': method}
         p.update(params)
         try:
-            result = self.session.post(
+            result_json = self.session.post(
                 "http://www.deezer.com/ajax/gw-light.php",
                 params=p,
                 timeout=30,
                 json=args,
                 headers=self.http_headers
-            )
-            result_json = result.json()
+            ).json()
         except:
             sleep(2)
             return self.api_call(method, args, params)
         if len(result_json['error']):
             raise APIError(json.dumps(result_json['error']))
-        return result.json()['results']
+        return result_json['results']
 
     def _get_token(self):
         token_data = self.get_user_data()
@@ -109,7 +108,7 @@ class GW:
                 tracks_array.append(body['data'][i - errors])
             else:
                 errors += 1
-                tracks_array.append(EMPTY_TRACK_DICT)
+                tracks_array.append(EMPTY_TRACK_OBJ)
         return tracks_array
 
     def get_album(self, alb_id):
@@ -117,18 +116,17 @@ class GW:
 
     def get_album_page(self, alb_id):
         return self.api_call('deezer.pageAlbum', {
-                                'alb_id': alb_id,
-                                'lang': 'en',
-                                'header': True,
-                                'tab': 0
-                            })
+            'alb_id': alb_id,
+            'lang': 'en',
+            'header': True,
+            'tab': 0
+        })
 
     def get_album_tracks(self, alb_id):
         tracks_array = []
         body = self.api_call('song.getListByAlbum', {'alb_id': alb_id, 'nb': -1})
         for track in body['data']:
-            _track = track
-            _track['POSITION'] = body['data'].index(track)
+            track['POSITION'] = body['data'].index(track)
             tracks_array.append(_track)
         return tracks_array
 
@@ -137,11 +135,11 @@ class GW:
 
     def get_artist_page(self, art_id):
         return self.api_call('deezer.pageArtist', {
-                                'alb_id': art_id,
-                                'lang': 'en',
-                                'header': True,
-                                'tab': 0
-                            })
+            'art_id': art_id,
+            'lang': 'en',
+            'header': True,
+            'tab': 0
+        })
 
     def get_artist_top_tracks(self, art_id, limit=100):
         tracks_array = []
@@ -153,23 +151,23 @@ class GW:
 
     def get_artist_discography(self, art_id, index=0, limit=25):
         return self.api_call('album.getDiscography', {
-                                'art_id': art_id,
-                                "discography_mode":"all",
-                                'nb': limit,
-                                'nb_songs': 0,
-                                'start': index
-                            })
+            'art_id': art_id,
+            "discography_mode":"all",
+            'nb': limit,
+            'nb_songs': 0,
+            'start': index
+        })
 
     def get_playlist(self, playlist_id):
         return self.api_call('playlist.getData', {'playlist_id': playlist_id})
 
     def get_playlist_page(self, playlist_id):
         return self.api_call('deezer.pagePlaylist', {
-                                'playlist_id': playlist_id,
-                                'lang': 'en',
-                                'header': True,
-                                'tab': 0
-                        })
+            'playlist_id': playlist_id,
+            'lang': 'en',
+            'header': True,
+            'tab': 0
+        })
 
     def get_playlist_tracks(self, playlist_id):
         tracks_array = []
@@ -190,7 +188,7 @@ class GW:
             'songs': newSongs
         })
 
-    def edit_playlist(self, playlist_id, title, status=None, description=None, songs=None):
+    def edit_playlist(self, playlist_id, title, status=None, description=None, songs=[]):
         newSongs = []
         for song in songs:
             newSongs.append([song, 0])
@@ -275,23 +273,22 @@ class GW:
 
     def search(self, query, index=0, limit=10, suggest=True, artist_suggest=True, top_tracks=True):
         return self.api_call('deezer.pageSearch', {
-                    "query": query,
-                    "start": index,
-                    "nb": limit,
-                    "suggest": suggest,
-                    "artist_suggest": artist_suggest,
-                    "top_tracks": top_tracks
-                })
+            "query": query,
+            "start": index,
+            "nb": limit,
+            "suggest": suggest,
+            "artist_suggest": artist_suggest,
+            "top_tracks": top_tracks
+        })
 
     def search_music(self, query, type, index=0, limit=10):
-        return self.api_call('search.music',
-                             {
-                                 "query": query,
-                                 "filter": "ALL",
-                                 "output": type,
-                                 "start": index,
-                                 "nb": limit
-                             })
+        return self.api_call('search.music', {
+            "query": query,
+            "filter": "ALL",
+            "output": type,
+            "start": index,
+            "nb": limit
+        })
 
     # Extra calls
 
@@ -350,7 +347,7 @@ class GW:
 
     def get_user_playlists(self, user_id, limit=25):
         user_profile_page = self.get_user_profile_page(user_id, 'playlists', limit=limit)
-        blog_name = user_profile_page['DATA']['USER'].get('BLOG_NAME', "Unkown")
+        blog_name = user_profile_page['DATA']['USER'].get('BLOG_NAME', "Unknown")
         data = user_profile_page['TAB']['playlists']['data']
         result = []
         for playlist in data:
diff --git a/deezer/utils.py b/deezer/utils.py
index b346f6a..e11b7cb 100644
--- a/deezer/utils.py
+++ b/deezer/utils.py
@@ -45,7 +45,7 @@ def map_user_artist(artist):
         'id': artist['ART_ID'],
         'name': artist['ART_NAME'],
         'link': 'https://www.deezer.com/artist/'+str(artist['ART_ID']),
-        'picture': 'https://api.deezer.com/artist/'+str(artist['ART_PICTURE'])+'/image',
+        'picture': 'https://api.deezer.com/artist/'+str(artist['ART_ID'])+'/image',
         'picture_small': 'https://e-cdns-images.dzcdn.net/images/artist/'+str(artist['ART_PICTURE'])+'/56x56-000000-80-0-0.jpg',
         'picture_medium': 'https://e-cdns-images.dzcdn.net/images/artist/'+str(artist['ART_PICTURE'])+'/250x250-000000-80-0-0.jpg',
         'picture_big': 'https://e-cdns-images.dzcdn.net/images/artist/'+str(artist['ART_PICTURE'])+'/500x500-000000-80-0-0.jpg',