Skip to content

Commit f10e5ef

Browse files
committed
Merge remote-tracking branch 'upstream/main'
2 parents 06df84a + c11cfed commit f10e5ef

File tree

6 files changed

+43
-29
lines changed

6 files changed

+43
-29
lines changed

zspotify/app.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ def client(args) -> None:
1919
""" Connects to spotify to perform query's and get songs to download """
2020
ZSpotify(args)
2121

22-
if ZSpotify.CONFIG.get_print_splash():
23-
Printer.print(PrintChannel.SPLASH, splash())
22+
Printer.print(PrintChannel.SPLASH, splash())
2423

2524
if ZSpotify.check_premium():
2625
Printer.print(PrintChannel.SPLASH, '[ DETECTED PREMIUM ACCOUNT - USING VERY_HIGH QUALITY ]\n\n')

zspotify/config.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
OUTPUT_DEFAULT_SINGLE = '{artist} - {song_name}.{ext}'
7171
OUTPUT_DEFAULT_ALBUM = '{artist}/{album}/{album_num} - {artist} - {song_name}.{ext}'
7272

73+
7374
class Config:
7475
Values = {}
7576

@@ -206,15 +207,11 @@ def get_temp_download_dir(cls) -> str:
206207
return os.path.join(cls.get_root_path(), cls.get(TEMP_DOWNLOAD_DIR))
207208

208209
@classmethod
209-
def get_allGenres(cls) -> bool:
210+
def get_all_genres(cls) -> bool:
210211
return cls.get(MD_ALLGENRES)
211212

212213
@classmethod
213-
def get_print_splash(cls) -> bool:
214-
return cls.get(PRINT_SPLASH)
215-
216-
@classmethod
217-
def get_allGenresDelimiter(cls) -> bool:
214+
def get_all_genres_delimiter(cls) -> bool:
218215
return cls.get(MD_GENREDELIMITER)
219216

220217
@classmethod
@@ -248,3 +245,7 @@ def get_output(cls, mode: str) -> str:
248245
return os.path.join(split[0], 'Disc {disc_number}', split[0])
249246
return OUTPUT_DEFAULT_ALBUM
250247
raise ValueError()
248+
249+
@classmethod
250+
def get_retry_attempts(cls) -> int:
251+
return cls.get(RETRY_ATTEMPTS)

zspotify/const.py

+2
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434

3535
NAME = 'name'
3636

37+
HREF = 'href'
38+
3739
ID = 'id'
3840

3941
URL = 'url'

zspotify/track.py

+29-17
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from ffmpy import FFmpeg
1010

1111
from const import TRACKS, ALBUM, GENRES, NAME, ITEMS, DISC_NUMBER, TRACK_NUMBER, IS_PLAYABLE, ARTISTS, IMAGES, URL, \
12-
RELEASE_DATE, ID, TRACKS_URL, SAVED_TRACKS_URL, TRACK_STATS_URL, CODEC_MAP, EXT_MAP, DURATION_MS
12+
RELEASE_DATE, ID, TRACKS_URL, SAVED_TRACKS_URL, TRACK_STATS_URL, CODEC_MAP, EXT_MAP, DURATION_MS, HREF
1313
from termoutput import Printer, PrintChannel
1414
from utils import fix_filename, set_audio_tags, set_music_thumbnail, create_download_directory, \
1515
get_directory_song_ids, add_to_directory_song_ids, get_previously_downloaded, add_to_archive, fmt_seconds
@@ -35,7 +35,7 @@ def get_saved_tracks() -> list:
3535
return songs
3636

3737

38-
def get_song_info(song_id) -> Tuple[List[str], List[str], str, str, Any, Any, Any, Any, Any, Any, int]:
38+
def get_song_info(song_id) -> Tuple[List[str], List[Any], str, str, Any, Any, Any, Any, Any, Any, int]:
3939
""" Retrieves metadata for downloaded songs """
4040
with Loader(PrintChannel.PROGRESS_INFO, "Fetching track information..."):
4141
(raw, info) = ZSpotify.invoke_url(f'{TRACKS_URL}?ids={song_id}&market=from_token')
@@ -45,21 +45,8 @@ def get_song_info(song_id) -> Tuple[List[str], List[str], str, str, Any, Any, An
4545

4646
try:
4747
artists = []
48-
genres = []
4948
for data in info[TRACKS][0][ARTISTS]:
5049
artists.append(data[NAME])
51-
# query artist genres via href, which will be the api url
52-
with Loader(PrintChannel.PROGRESS_INFO, "Fetching artist information..."):
53-
(raw, artistInfo) = ZSpotify.invoke_url(f'{data["href"]}')
54-
if ZSpotify.CONFIG.get_allGenres() and len(artistInfo[GENRES]) > 0:
55-
for genre in artistInfo[GENRES]:
56-
genres.append(genre)
57-
elif len(artistInfo[GENRES]) > 0:
58-
genres.append(artistInfo[GENRES][0])
59-
60-
if len(genres) == 0:
61-
Printer.print(PrintChannel.WARNINGS, '### No Genres found for song ' + info[TRACKS][0][NAME])
62-
genres.append('')
6350

6451
album_name = info[TRACKS][0][ALBUM][NAME]
6552
name = info[TRACKS][0][NAME]
@@ -71,11 +58,34 @@ def get_song_info(song_id) -> Tuple[List[str], List[str], str, str, Any, Any, An
7158
is_playable = info[TRACKS][0][IS_PLAYABLE]
7259
duration_ms = info[TRACKS][0][DURATION_MS]
7360

74-
return artists, genres, album_name, name, image_url, release_year, disc_number, track_number, scraped_song_id, is_playable, duration_ms
61+
return artists, info[TRACKS][0][ARTISTS], album_name, name, image_url, release_year, disc_number, track_number, scraped_song_id, is_playable, duration_ms
7562
except Exception as e:
7663
raise ValueError(f'Failed to parse TRACKS_URL response: {str(e)}\n{raw}')
7764

7865

66+
def get_song_genres(rawartists: List[str], track_name: str) -> List[str]:
67+
68+
try:
69+
genres = []
70+
for data in rawartists:
71+
# query artist genres via href, which will be the api url
72+
with Loader(PrintChannel.PROGRESS_INFO, "Fetching artist information..."):
73+
(raw, artistInfo) = ZSpotify.invoke_url(f'{data[HREF]}')
74+
if ZSpotify.CONFIG.get_all_genres() and len(artistInfo[GENRES]) > 0:
75+
for genre in artistInfo[GENRES]:
76+
genres.append(genre)
77+
elif len(artistInfo[GENRES]) > 0:
78+
genres.append(artistInfo[GENRES][0])
79+
80+
if len(genres) == 0:
81+
Printer.print(PrintChannel.WARNINGS, '### No Genres found for song ' + track_name)
82+
genres.append('')
83+
84+
return genres
85+
except Exception as e:
86+
raise ValueError(f'Failed to parse GENRES response: {str(e)}\n{raw}')
87+
88+
7989
def get_song_duration(song_id: str) -> float:
8090
""" Retrieves duration of song in second as is on spotify """
8191

@@ -106,7 +116,7 @@ def download_track(mode: str, track_id: str, extra_keys=None, disable_progressba
106116
try:
107117
output_template = ZSpotify.CONFIG.get_output(mode)
108118

109-
(artists, genres, album_name, name, image_url, release_year, disc_number,
119+
(artists, raw_artists, album_name, name, image_url, release_year, disc_number,
110120
track_number, scraped_song_id, is_playable, duration_ms) = get_song_info(track_id)
111121

112122
song_name = fix_filename(artists[0]) + ' - ' + fix_filename(name)
@@ -201,6 +211,8 @@ def download_track(mode: str, track_id: str, extra_keys=None, disable_progressba
201211

202212
time_downloaded = time.time()
203213

214+
genres = get_song_genres(raw_artists, name)
215+
204216
convert_audio_format(filename_temp)
205217
set_audio_tags(filename_temp, artists, genres, name, album_name, release_year, disc_number, track_number)
206218
set_music_thumbnail(filename_temp, image_url)

zspotify/utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def set_audio_tags(filename, artists, genres, name, album_name, release_year, di
129129
tags = music_tag.load_file(filename)
130130
tags[ALBUMARTIST] = artists[0]
131131
tags[ARTIST] = conv_artist_format(artists)
132-
tags[GENRE] = genres[0] if not ZSpotify.CONFIG.get_allGenres() else ZSpotify.CONFIG.get_allGenresDelimiter().join(genres)
132+
tags[GENRE] = genres[0] if not ZSpotify.CONFIG.get_all_genres() else ZSpotify.CONFIG.get_all_genres_delimiter().join(genres)
133133
tags[TRACKTITLE] = name
134134
tags[ALBUM] = album_name
135135
tags[YEAR] = release_year
@@ -273,9 +273,9 @@ def fmt_seconds(secs: float) -> str:
273273
h = math.floor(val)
274274

275275
if h == 0 and m == 0 and s == 0:
276-
return "0"
276+
return "0s"
277277
elif h == 0 and m == 0:
278-
return f'{s}'.zfill(2)
278+
return f'{s}s'.zfill(2)
279279
elif h == 0:
280280
return f'{m}'.zfill(2) + ':' + f'{s}'.zfill(2)
281281
else:

zspotify/zspotify.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def invoke_url(cls, url, tryCount=0):
8282
responsejson = response.json()
8383

8484
if 'error' in responsejson:
85-
if tryCount < (cls.CONFIG.retry_attemps - 1):
85+
if tryCount < (cls.CONFIG.get_retry_attempts() - 1):
8686
Printer.print(PrintChannel.WARNINGS, f"Spotify API Error (try {tryCount + 1}) ({responsejson['error']['status']}): {responsejson['error']['message']}")
8787
time.sleep(5)
8888
return cls.invoke_url(url, tryCount + 1)

0 commit comments

Comments
 (0)