Skip to content

Commit

Permalink
Config changes, dependency change
Browse files Browse the repository at this point in the history
Config file works properly this time, code is more concise.

Moved from `docopt` to `docopt-ng` as the former was no longer in development.
  • Loading branch information
Evolution0 committed Feb 19, 2023
1 parent 9f22fbe commit e21bb65
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 84 deletions.
4 changes: 2 additions & 2 deletions bandcamp_dl/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def main():
# TODO: Its possible to break bandcamp-dl temporarily by simply erasing a line in the config, catch this and warn.
config = init_config(arguments)

if config['debug']:
if config['--debug']:
logging.basicConfig(level=logging.DEBUG)

if arguments['--artist'] and arguments['--album']:
Expand All @@ -84,7 +84,7 @@ def main():
urls = Bandcamp.generate_album_url(arguments['--artist'], arguments['--track'], "track")
elif arguments['--artist']:
print(__doc__)
os.remove(f"{config['basedir']}/{__version__}.not.finished")
os.remove(f"{config['--base-dir']}/{__version__}.not.finished")
exit()
else:
urls = arguments['URL']
Expand Down
36 changes: 18 additions & 18 deletions bandcamp_dl/bandcampdownloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ def start(self, album: dict):
:param album: album dict
"""
if self.config['debug']:
if self.config['--debug']:
logging.basicConfig(level=logging.DEBUG)

if not album['full'] and not self.config['confirmation_skip']:
if not album['full'] and not self.config['--no-confirm']:
choice = input("Track list incomplete, some tracks may be private, download anyway? (yes/no): ").lower()
if choice == "yes" or choice == "y":
print("Starting download process.")
Expand All @@ -66,14 +66,14 @@ def template_to_path(self, track: dict, ascii_only, ok_chars, space_char, keep_s
:return: filepath
"""
logging.debug(" Generating filepath/trackname..")
path = self.config['template']
path = self.config['--template']

def slugify_preset(content):
slugged = slugify(content, ok=ok_chars, only_ascii=ascii_only, spaces=keep_space, lower=not keep_upper,
space_replacement=space_char)
return slugged

if self.config['no_slugify']:
if self.config['--no-slugify']:
path = path.replace("%{artist}", track['artist'])
path = path.replace("%{album}", track['album'])
path = path.replace("%{title}", track['title'])
Expand All @@ -91,7 +91,7 @@ def slugify_preset(content):
else:
path = path.replace("%{track}", str(track['track']).zfill(2))

path = f"{self.config['basedir']}/{path}.mp3"
path = f"{self.config['--base-dir']}/{path}.mp3"

logging.debug(" filepath/trackname generated..")
logging.debug(f"\n\tPath: {path}")
Expand Down Expand Up @@ -133,9 +133,9 @@ def download_album(self, album: dict) -> bool:
self.num_tracks = len(album['tracks'])
self.track_num = track_index + 1

filepath = self.template_to_path(track_meta, self.config['ascii_only'], self.config['allowed_chars'],
self.config['space_char'], self.config['keep_spaces'],
self.config['keep_upper']) + ".tmp"
filepath = self.template_to_path(track_meta, self.config['--ascii-only'], self.config['--ok-chars'],
self.config['--space-char'], self.config['--keep-spaces'],
self.config['--keep-upper']) + ".tmp"
filename = filepath.rsplit('/', 1)[1]
dirname = self.create_directory(filepath)

Expand Down Expand Up @@ -170,7 +170,7 @@ def download_album(self, album: dict) -> bool:
skip = True
# break out of the try/except and move on to the next file
break
elif os.path.exists(filepath[:-4]) and self.config['overwrite'] is not True:
elif os.path.exists(filepath[:-4]) and self.config['--overwrite'] is not True:
print(f"File: {filename[:-4]} already exists and is complete, skipping..")
skip = True
break
Expand All @@ -182,7 +182,7 @@ def download_album(self, album: dict) -> bool:
for data in r.iter_content(chunk_size=total):
dl += len(data)
f.write(data)
if not self.config['debug']:
if not self.config['--debug']:
done = int(50 * dl / file_length)
print_clean(
f'\r({self.track_num}/{self.num_tracks}) [{"=" * done}{" " * (50 - done)}] :: Downloading: {filename[:-8]}')
Expand All @@ -207,11 +207,11 @@ def download_album(self, album: dict) -> bool:
if skip is False:
self.write_id3_tags(filepath, track_meta)

if os.path.isfile(f"{self.config['basedir']}/{__version__}.not.finished"):
os.remove(f"{self.config['basedir']}/{__version__}.not.finished")
if os.path.isfile(f"{self.config['--base-dir']}/{__version__}.not.finished"):
os.remove(f"{self.config['--base-dir']}/{__version__}.not.finished")

# Remove album art image as it is embedded
if self.config['embed_art']:
if self.config['--embed-art']:
os.remove(self.album_art)

return True
Expand All @@ -226,7 +226,7 @@ def write_id3_tags(self, filepath: str, meta: dict):

filename = filepath.rsplit('/', 1)[1][:-8]

if not self.config['debug']:
if not self.config['--debug']:
print_clean(f'\r({self.track_num}/{self.num_tracks}) [{"=" * 50}] :: Encoding: {filename}')

audio = MP3(filepath)
Expand All @@ -235,13 +235,13 @@ def write_id3_tags(self, filepath: str, meta: dict):
audio.save(filename=None, v1=2)

audio = MP3(filepath)
if self.config['group'] and 'label' in meta:
if self.config['--group'] and 'label' in meta:
audio["TIT1"] = TIT1(encoding=3, text=meta["label"])

if self.config['embed_lyrics']:
if self.config['--embed-lyrics']:
audio["USLT"] = USLT(encoding=3, lang='eng', desc='', text=meta['lyrics'])

if self.config['embed_art']:
if self.config['--embed-art']:
with open(self.album_art, 'rb') as cover_img:
cover_bytes = cover_img.read()
audio["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=cover_bytes)
Expand All @@ -264,5 +264,5 @@ def write_id3_tags(self, filepath: str, meta: dict):
os.remove(filepath[:-4])
os.rename(filepath, filepath[:-4])

if not self.config['debug']:
if not self.config['--debug']:
print_clean(f'\r({self.track_num}/{self.num_tracks}) [{"=" * 50}] :: Finished: {filename}')
2 changes: 1 addition & 1 deletion bandcamp_dl/deps.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
beautifulsoup4==4.10.0
demjson3==3.0.5
docopt==0.6.2
docopt-ng==0.8.1
mutagen==1.45.1
requests==2.26.0
unicode-slugify==0.1.5
Expand Down
79 changes: 18 additions & 61 deletions bandcamp_dl/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,29 @@ def init_config(arguments) -> json or dict:
with open(config_path, "w") as config_file:
# Where config defaults are set/added
config = {
"basedir": user_home,
"template": "%{artist}/%{album}/%{track} - %{title}",
"overwrite": False,
"no_art": False,
"embed_art": False,
"embed_lyrics": False,
"group": False,
"no_slugify": False,
"allowed_chars": "-_~",
"space_char": "-",
"ascii_only": False,
"keep_spaces": False,
"keep_upper": False,
"confirmation_skip": False,
"debug": False
"--base-dir": user_home,
"--template": "%{artist}/%{album}/%{track} - %{title}",
"--overwrite": False,
"--no-art": False,
"--embed-art": False,
"--embed-lyrics": False,
"--group": False,
"--no-slugify": False,
"--ok-chars": "-_~",
"--space-char": "-",
"--ascii-only": False,
"--keep-spaces": False,
"--keep-upper": False,
"--no-confirm": False,
"--debug": False
}
config_json = json.dumps(config, indent=4)
logging.debug("Creating config file...")
config_file.write(config_json)

# TODO: Replace all this shuffling around values with a dict comprehension if possible !!!!
# TODO: Session file should override config, as its essentially replaying manually set args
session_file = f"{config['basedir']}/{__version__}.not.finished"
session_file = f"{config['--base-dir']}/{__version__}.not.finished"

if os.path.isfile(session_file) and arguments['URL'] is None:
with open(session_file, "r") as f:
Expand All @@ -61,49 +62,5 @@ def init_config(arguments) -> json or dict:
with open(session_file, "w") as f:
f.write("".join(str(arguments).split('\n')))

if arguments['--base-dir'] is not None:
config['basedir'] = arguments['--base-dir']

if arguments['--template'] != config['template']:
config['template'] = arguments['--template']

if arguments['--overwrite'] != config['overwrite']:
config['overwrite'] = arguments['--overwrite']

if arguments['--no-art'] != config['no_art']:
config['no_art'] = arguments['--no-art']

if arguments['--embed-art'] != config['embed_art']:
config['embed_art'] = arguments['--embed-art']

if arguments['--embed-lyrics'] != config['embed_lyrics']:
config['embed_lyrics'] = arguments['--embed-lyrics']

if arguments['--group'] != config['group']:
config['group'] = arguments['--group']

if arguments['--no-slugify'] != config['no_slugify']:
config['no_slugify'] = arguments['--no-slugify']

if arguments['--ok-chars'] != config['allowed_chars']:
config['allowed_chars'] = arguments['--ok-chars']

if arguments['--space-char'] != config['space_char']:
config['space_char'] = arguments['--space-char']

if arguments['--ascii-only'] != config['ascii_only']:
config['ascii_only'] = arguments['--ascii-only']

if arguments['--keep-spaces'] != config['keep_spaces']:
config['keep_spaces'] = arguments['--keep-spaces']

if arguments['--keep-upper'] != config['keep_upper']:
config['keep_upper'] = arguments['--keep-upper']

if arguments['--no-confirm'] != config['confirmation_skip']:
config['confirmation_skip'] = arguments['--no-confirm']

if arguments['--debug'] != config['debug']:
config['debug'] = arguments['--debug']

config = {key: arguments.get(key, config[key]) for key in config}
return config
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

beautifulsoup4==4.11.1
demjson3==3.0.5
docopt==0.6.2
docopt-ng==0.8.1
mutagen==1.45.1
requests==2.27.1
unicode-slugify==0.1.5
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from setuptools import setup, find_packages
import pathlib

appversion = "0.0.14"
appversion = "0.0.15"

here = pathlib.Path(__file__).parent.resolve()

Expand Down

0 comments on commit e21bb65

Please sign in to comment.