Use default values on missing configs

This commit is contained in:
Mike Schwörer 2021-11-18 22:39:17 +01:00
parent 50187c5aeb
commit 9082938dfd
No known key found for this signature in database
GPG Key ID: D3C7172E0A70F8CF
4 changed files with 70 additions and 61 deletions

View File

@ -19,24 +19,24 @@ DOWNLOAD_REAL_TIME = 'DOWNLOAD_REAL_TIME'
LANGUAGE = 'LANGUAGE' LANGUAGE = 'LANGUAGE'
BITRATE = 'BITRATE' BITRATE = 'BITRATE'
CONFIG_DEFAULT_SETTINGS = { CONFIG_VALUES = {
'ROOT_PATH': '../ZSpotify Music/', ROOT_PATH: { 'default': '../ZSpotify Music/', 'type': 'str', 'arg': '--root-path' },
'ROOT_PODCAST_PATH': '../ZSpotify Podcasts/', ROOT_PODCAST_PATH: { 'default': '../ZSpotify Podcasts/', 'type': 'str', 'arg': '--root-podcast-path' },
'SKIP_EXISTING_FILES': True, SKIP_EXISTING_FILES: { 'default': True, 'type': 'bool', 'arg': '--skip-existing-files' },
'SKIP_PREVIOUSLY_DOWNLOADED': False, SKIP_PREVIOUSLY_DOWNLOADED: { 'default': False, 'type': 'bool', 'arg': '--skip-previously-downloaded' },
'DOWNLOAD_FORMAT': 'ogg', DOWNLOAD_FORMAT: { 'default': 'ogg', 'type': 'str', 'arg': '--download-format' },
'FORCE_PREMIUM': False, FORCE_PREMIUM: { 'default': False, 'type': 'bool', 'arg': '--force-premium' },
'ANTI_BAN_WAIT_TIME': 1, ANTI_BAN_WAIT_TIME: { 'default': 1, 'type': 'int', 'arg': '--anti-ban-wait-time' },
'OVERRIDE_AUTO_WAIT': False, OVERRIDE_AUTO_WAIT: { 'default': False, 'type': 'bool', 'arg': '--override-auto-wait' },
'CHUNK_SIZE': 50000, CHUNK_SIZE: { 'default': 50000, 'type': 'int', 'arg': '--chunk-size' },
'SPLIT_ALBUM_DISCS': False, SPLIT_ALBUM_DISCS: { 'default': False, 'type': 'bool', 'arg': '--split-album-discs' },
'DOWNLOAD_REAL_TIME': False, DOWNLOAD_REAL_TIME: { 'default': False, 'type': 'bool', 'arg': '--download-real-time' },
'LANGUAGE': 'en', LANGUAGE: { 'default': 'en', 'type': 'str', 'arg': '--language' },
'BITRATE': '', BITRATE: { 'default': '', 'type': 'str', 'arg': '--bitrate' },
} }
class Config:
class Config:
Values = {} Values = {}
@classmethod @classmethod
@ -51,65 +51,74 @@ class Config:
if not os.path.exists(true_config_file_path): if not os.path.exists(true_config_file_path):
with open(true_config_file_path, 'w', encoding='utf-8') as config_file: with open(true_config_file_path, 'w', encoding='utf-8') as config_file:
json.dump(CONFIG_DEFAULT_SETTINGS, config_file, indent=4) json.dump(cls.get_default_json(), config_file, indent=4)
cls.Values = CONFIG_DEFAULT_SETTINGS cls.Values = cls.get_default_json()
else: else:
with open(true_config_file_path, encoding='utf-8') as config_file: with open(true_config_file_path, encoding='utf-8') as config_file:
cls.Values = json.load(config_file) cls.Values = json.load(config_file)
for key in CONFIG_VALUES:
if key not in cls.Values:
cls.Values[key] = CONFIG_VALUES[key].default
@classmethod
def get_default_json(cls) -> Any:
r = {}
for key in CONFIG_VALUES:
r[key] = CONFIG_VALUES[key].default
return r
@classmethod @classmethod
def get(cls, key) -> Any: def get(cls, key) -> Any:
return cls.Values.get(key) return cls.Values.get(key)
@classmethod @classmethod
def getRootPath(cls) -> str: def get_root_path(cls) -> str:
return cls.get(ROOT_PATH) return cls.get(ROOT_PATH)
@classmethod @classmethod
def getRootPodcastPath(cls) -> str: def get_root_podcast_path(cls) -> str:
return cls.get(ROOT_PODCAST_PATH) return cls.get(ROOT_PODCAST_PATH)
@classmethod @classmethod
def getSkipExistingFiles(cls) -> bool: def get_skip_existing_files(cls) -> bool:
return cls.get(SKIP_EXISTING_FILES) return cls.get(SKIP_EXISTING_FILES)
@classmethod @classmethod
def getSkipPreviouslyDownloaded(cls) -> bool: def get_skip_previously_downloaded(cls) -> bool:
return cls.get(SKIP_PREVIOUSLY_DOWNLOADED) return cls.get(SKIP_PREVIOUSLY_DOWNLOADED)
@classmethod @classmethod
def getSplitAlbumDiscs(cls) -> bool: def get_split_album_discs(cls) -> bool:
return cls.get(SPLIT_ALBUM_DISCS) return cls.get(SPLIT_ALBUM_DISCS)
@classmethod @classmethod
def getChunkSize(cls) -> int(): def get_chunk_size(cls) -> int():
return cls.get(CHUNK_SIZE) return cls.get(CHUNK_SIZE)
@classmethod @classmethod
def getOverrideAutoWait(cls) -> bool: def get_override_auto_wait(cls) -> bool:
return cls.get(OVERRIDE_AUTO_WAIT) return cls.get(OVERRIDE_AUTO_WAIT)
@classmethod @classmethod
def getForcePremium(cls) -> bool: def get_force_premium(cls) -> bool:
return cls.get(FORCE_PREMIUM) return cls.get(FORCE_PREMIUM)
@classmethod @classmethod
def getDownloadFormat(cls) -> str: def get_download_format(cls) -> str:
return cls.get(DOWNLOAD_FORMAT) return cls.get(DOWNLOAD_FORMAT)
@classmethod @classmethod
def getAntiBanWaitTime(cls) -> int: def get_anti_ban_wait_time(cls) -> int:
return cls.get(ANTI_BAN_WAIT_TIME) return cls.get(ANTI_BAN_WAIT_TIME)
@classmethod @classmethod
def getLanguage(cls) -> str: def get_language(cls) -> str:
return cls.get(LANGUAGE) return cls.get(LANGUAGE)
@classmethod @classmethod
def getDownloadRealTime(cls) -> bool: def get_download_real_time(cls) -> bool:
return cls.get(DOWNLOAD_REAL_TIME) return cls.get(DOWNLOAD_REAL_TIME)
@classmethod @classmethod
def getBitrate(cls) -> str: def get_bitrate(cls) -> str:
return cls.get(BITRATE) return cls.get(BITRATE)

View File

@ -79,7 +79,7 @@ def download_episode(episode_id) -> None:
download_directory = os.path.join( download_directory = os.path.join(
os.path.dirname(__file__), os.path.dirname(__file__),
ZSpotify.CONFIG.getRootPodcastPath(), ZSpotify.CONFIG.get_root_podcast_path(),
extra_paths, extra_paths,
) )
download_directory = os.path.realpath(download_directory) download_directory = os.path.realpath(download_directory)
@ -96,7 +96,7 @@ def download_episode(episode_id) -> None:
if ( if (
os.path.isfile(filepath) os.path.isfile(filepath)
and os.path.getsize(filepath) == total_size and os.path.getsize(filepath) == total_size
and ZSpotify.CONFIG.getSkipExistingFiles() and ZSpotify.CONFIG.get_skip_existing_files()
): ):
print( print(
"\n### SKIPPING:", "\n### SKIPPING:",
@ -114,9 +114,9 @@ def download_episode(episode_id) -> None:
unit_scale=True, unit_scale=True,
unit_divisor=1024 unit_divisor=1024
) as bar: ) as bar:
for _ in range(int(total_size / ZSpotify.CONFIG.getChunkSize()) + 1): for _ in range(int(total_size / ZSpotify.CONFIG.get_chunk_size()) + 1):
bar.update(file.write( bar.update(file.write(
stream.input_stream.stream().read(ZSpotify.CONFIG.getChunkSize()))) stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size())))
else: else:
filepath = os.path.join(download_directory, f"{filename}.mp3") filepath = os.path.join(download_directory, f"{filename}.mp3")
download_podcast_directly(direct_download_url, filepath) download_podcast_directly(direct_download_url, filepath)

View File

@ -76,12 +76,12 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
(artists, album_name, name, image_url, release_year, disc_number, (artists, album_name, name, image_url, release_year, disc_number,
track_number, scraped_song_id, is_playable, duration_ms) = get_song_info(track_id) track_number, scraped_song_id, is_playable, duration_ms) = get_song_info(track_id)
if ZSpotify.CONFIG.getSplitAlbumDiscs(): if ZSpotify.CONFIG.get_split_album_discs():
download_directory = os.path.join(os.path.dirname( download_directory = os.path.join(os.path.dirname(
__file__), ZSpotify.CONFIG.getRootPath(), extra_paths, f'Disc {disc_number}') __file__), ZSpotify.CONFIG.get_root_path(), extra_paths, f'Disc {disc_number}')
else: else:
download_directory = os.path.join(os.path.dirname( download_directory = os.path.join(os.path.dirname(
__file__), ZSpotify.CONFIG.getRootPath(), extra_paths) __file__), ZSpotify.CONFIG.get_root_path(), extra_paths)
song_name = fix_filename(artists[0]) + ' - ' + fix_filename(name) song_name = fix_filename(artists[0]) + ' - ' + fix_filename(name)
if prefix: if prefix:
@ -89,9 +89,9 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
) else f'{prefix_value} - {song_name}' ) else f'{prefix_value} - {song_name}'
filename = os.path.join( filename = os.path.join(
download_directory, f'{song_name}.{EXT_MAP.get(ZSpotify.CONFIG.getDownloadFormat().lower())}') download_directory, f'{song_name}.{EXT_MAP.get(ZSpotify.CONFIG.get_download_format().lower())}')
archive_directory = os.path.join(os.path.dirname(__file__), ZSpotify.CONFIG.getRootPath()) archive_directory = os.path.join(os.path.dirname(__file__), ZSpotify.CONFIG.get_root_path())
check_name = os.path.isfile(filename) and os.path.getsize(filename) check_name = os.path.isfile(filename) and os.path.getsize(filename)
check_id = scraped_song_id in get_directory_song_ids(download_directory) check_id = scraped_song_id in get_directory_song_ids(download_directory)
check_all_time = scraped_song_id in get_previously_downloaded(scraped_song_id, archive_directory) check_all_time = scraped_song_id in get_previously_downloaded(scraped_song_id, archive_directory)
@ -102,7 +102,7 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
if re.search(f'^{song_name}_', file)]) + 1 if re.search(f'^{song_name}_', file)]) + 1
filename = os.path.join( filename = os.path.join(
download_directory, f'{song_name}_{c}.{EXT_MAP.get(ZSpotify.CONFIG.getDownloadFormat())}') download_directory, f'{song_name}_{c}.{EXT_MAP.get(ZSpotify.CONFIG.get_download_format())}')
except Exception as e: except Exception as e:
@ -114,11 +114,11 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
print('\n### SKIPPING:', song_name, print('\n### SKIPPING:', song_name,
'(SONG IS UNAVAILABLE) ###') '(SONG IS UNAVAILABLE) ###')
else: else:
if check_id and check_name and ZSpotify.CONFIG.getSkipExistingFiles(): if check_id and check_name and ZSpotify.CONFIG.get_skip_existing_files():
print('\n### SKIPPING:', song_name, print('\n### SKIPPING:', song_name,
'(SONG ALREADY EXISTS) ###') '(SONG ALREADY EXISTS) ###')
elif check_all_time and ZSpotify.CONFIG.getSkipPreviouslyDownloaded(): elif check_all_time and ZSpotify.CONFIG.get_skip_previously_downloaded():
print('\n### SKIPPING:', song_name, print('\n### SKIPPING:', song_name,
'(SONG ALREADY DOWNLOADED ONCE) ###') '(SONG ALREADY DOWNLOADED ONCE) ###')
@ -139,11 +139,11 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
unit_divisor=1024, unit_divisor=1024,
disable=disable_progressbar disable=disable_progressbar
) as p_bar: ) as p_bar:
pause = duration_ms / ZSpotify.CONFIG.getChunkSize() pause = duration_ms / ZSpotify.CONFIG.get_chunk_size()
for chunk in range(int(total_size / ZSpotify.CONFIG.getChunkSize()) + 1): for chunk in range(int(total_size / ZSpotify.CONFIG.get_chunk_size()) + 1):
data = stream.input_stream.stream().read(ZSpotify.CONFIG.getChunkSize()) data = stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size())
p_bar.update(file.write(data)) p_bar.update(file.write(data))
if ZSpotify.CONFIG.getDownloadRealTime(): if ZSpotify.CONFIG.get_download_real_time():
time.sleep(pause) time.sleep(pause)
convert_audio_format(filename) convert_audio_format(filename)
@ -152,14 +152,14 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
set_music_thumbnail(filename, image_url) set_music_thumbnail(filename, image_url)
# add song id to archive file # add song id to archive file
if ZSpotify.CONFIG.getSkipPreviouslyDownloaded(): if ZSpotify.CONFIG.get_skip_previously_downloaded():
add_to_archive(scraped_song_id, archive_directory) add_to_archive(scraped_song_id, archive_directory)
# add song id to download directory's .song_ids file # add song id to download directory's .song_ids file
if not check_id: if not check_id:
add_to_directory_song_ids(download_directory, scraped_song_id) add_to_directory_song_ids(download_directory, scraped_song_id)
if not ZSpotify.CONFIG.getAntiBanWaitTime(): if not ZSpotify.CONFIG.get_anti_ban_wait_time():
time.sleep(ZSpotify.CONFIG.getAntiBanWaitTime()) time.sleep(ZSpotify.CONFIG.get_anti_ban_wait_time())
except Exception as e: except Exception as e:
print('### SKIPPING:', song_name, print('### SKIPPING:', song_name,
'(GENERAL DOWNLOAD ERROR) ###') '(GENERAL DOWNLOAD ERROR) ###')
@ -173,10 +173,10 @@ def convert_audio_format(filename) -> None:
temp_filename = f'{os.path.splitext(filename)[0]}.tmp' temp_filename = f'{os.path.splitext(filename)[0]}.tmp'
os.replace(filename, temp_filename) os.replace(filename, temp_filename)
download_format = ZSpotify.CONFIG.getDownloadFormat().lower() download_format = ZSpotify.CONFIG.get_download_format().lower()
file_codec = CODEC_MAP.get(download_format, 'copy') file_codec = CODEC_MAP.get(download_format, 'copy')
if file_codec != 'copy': if file_codec != 'copy':
bitrate = ZSpotify.CONFIG.getBitrate() bitrate = ZSpotify.CONFIG.get_bitrate()
if not bitrate: if not bitrate:
if ZSpotify.DOWNLOAD_QUALITY == AudioQuality.VERY_HIGH: if ZSpotify.DOWNLOAD_QUALITY == AudioQuality.VERY_HIGH:
bitrate = '320k' bitrate = '320k'

View File

@ -26,7 +26,7 @@ from config import Config
class ZSpotify: class ZSpotify:
SESSION: Session = None SESSION: Session = None
DOWNLOAD_QUALITY = None DOWNLOAD_QUALITY = None
CONFIG = Config() CONFIG: Config = Config()
def __init__(self, args): def __init__(self, args):
ZSpotify.CONFIG.load(args) ZSpotify.CONFIG.load(args)
@ -65,14 +65,14 @@ class ZSpotify:
def get_auth_header(cls): def get_auth_header(cls):
return { return {
'Authorization': f'Bearer {cls.__get_auth_token()}', 'Authorization': f'Bearer {cls.__get_auth_token()}',
'Accept-Language': f'{cls.CONFIG.getLanguage()}' 'Accept-Language': f'{cls.CONFIG.get_language()}'
} }
@classmethod @classmethod
def get_auth_header_and_params(cls, limit, offset): def get_auth_header_and_params(cls, limit, offset):
return { return {
'Authorization': f'Bearer {cls.__get_auth_token()}', 'Authorization': f'Bearer {cls.__get_auth_token()}',
'Accept-Language': f'{cls.CONFIG.getLanguage()}' 'Accept-Language': f'{cls.CONFIG.get_language()}'
}, {LIMIT: limit, OFFSET: offset} }, {LIMIT: limit, OFFSET: offset}
@classmethod @classmethod
@ -89,4 +89,4 @@ class ZSpotify:
@classmethod @classmethod
def check_premium(cls) -> bool: def check_premium(cls) -> bool:
""" If user has spotify premium return true """ """ If user has spotify premium return true """
return (cls.SESSION.get_user_attribute(TYPE) == PREMIUM) or cls.CONFIG.getForcePremium() return (cls.SESSION.get_user_attribute(TYPE) == PREMIUM) or cls.CONFIG.get_force_premium()