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

View File

@ -79,7 +79,7 @@ def download_episode(episode_id) -> None:
download_directory = os.path.join(
os.path.dirname(__file__),
ZSpotify.CONFIG.getRootPodcastPath(),
ZSpotify.CONFIG.get_root_podcast_path(),
extra_paths,
)
download_directory = os.path.realpath(download_directory)
@ -96,7 +96,7 @@ def download_episode(episode_id) -> None:
if (
os.path.isfile(filepath)
and os.path.getsize(filepath) == total_size
and ZSpotify.CONFIG.getSkipExistingFiles()
and ZSpotify.CONFIG.get_skip_existing_files()
):
print(
"\n### SKIPPING:",
@ -114,9 +114,9 @@ def download_episode(episode_id) -> None:
unit_scale=True,
unit_divisor=1024
) 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(
stream.input_stream.stream().read(ZSpotify.CONFIG.getChunkSize())))
stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size())))
else:
filepath = os.path.join(download_directory, f"{filename}.mp3")
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,
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(
__file__), ZSpotify.CONFIG.getRootPath(), extra_paths, f'Disc {disc_number}')
__file__), ZSpotify.CONFIG.get_root_path(), extra_paths, f'Disc {disc_number}')
else:
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)
if prefix:
@ -89,9 +89,9 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
) else f'{prefix_value} - {song_name}'
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_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)
@ -102,7 +102,7 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
if re.search(f'^{song_name}_', file)]) + 1
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:
@ -114,11 +114,11 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
print('\n### SKIPPING:', song_name,
'(SONG IS UNAVAILABLE) ###')
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,
'(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,
'(SONG ALREADY DOWNLOADED ONCE) ###')
@ -139,11 +139,11 @@ def download_track(track_id: str, extra_paths='', prefix=False, prefix_value='',
unit_divisor=1024,
disable=disable_progressbar
) as p_bar:
pause = duration_ms / ZSpotify.CONFIG.getChunkSize()
for chunk in range(int(total_size / ZSpotify.CONFIG.getChunkSize()) + 1):
data = stream.input_stream.stream().read(ZSpotify.CONFIG.getChunkSize())
pause = duration_ms / ZSpotify.CONFIG.get_chunk_size()
for chunk in range(int(total_size / ZSpotify.CONFIG.get_chunk_size()) + 1):
data = stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size())
p_bar.update(file.write(data))
if ZSpotify.CONFIG.getDownloadRealTime():
if ZSpotify.CONFIG.get_download_real_time():
time.sleep(pause)
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)
# 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 song id to download directory's .song_ids file
if not check_id:
add_to_directory_song_ids(download_directory, scraped_song_id)
if not ZSpotify.CONFIG.getAntiBanWaitTime():
time.sleep(ZSpotify.CONFIG.getAntiBanWaitTime())
if not ZSpotify.CONFIG.get_anti_ban_wait_time():
time.sleep(ZSpotify.CONFIG.get_anti_ban_wait_time())
except Exception as e:
print('### SKIPPING:', song_name,
'(GENERAL DOWNLOAD ERROR) ###')
@ -173,10 +173,10 @@ def convert_audio_format(filename) -> None:
temp_filename = f'{os.path.splitext(filename)[0]}.tmp'
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')
if file_codec != 'copy':
bitrate = ZSpotify.CONFIG.getBitrate()
bitrate = ZSpotify.CONFIG.get_bitrate()
if not bitrate:
if ZSpotify.DOWNLOAD_QUALITY == AudioQuality.VERY_HIGH:
bitrate = '320k'

View File

@ -26,7 +26,7 @@ from config import Config
class ZSpotify:
SESSION: Session = None
DOWNLOAD_QUALITY = None
CONFIG = Config()
CONFIG: Config = Config()
def __init__(self, args):
ZSpotify.CONFIG.load(args)
@ -65,14 +65,14 @@ class ZSpotify:
def get_auth_header(cls):
return {
'Authorization': f'Bearer {cls.__get_auth_token()}',
'Accept-Language': f'{cls.CONFIG.getLanguage()}'
'Accept-Language': f'{cls.CONFIG.get_language()}'
}
@classmethod
def get_auth_header_and_params(cls, limit, offset):
return {
'Authorization': f'Bearer {cls.__get_auth_token()}',
'Accept-Language': f'{cls.CONFIG.getLanguage()}'
'Accept-Language': f'{cls.CONFIG.get_language()}'
}, {LIMIT: limit, OFFSET: offset}
@classmethod
@ -89,4 +89,4 @@ class ZSpotify:
@classmethod
def check_premium(cls) -> bool:
""" 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()