Restructure cli

This commit is contained in:
nathom 2021-03-22 14:53:28 -07:00
parent 72a79d0c32
commit b7ace1d8d0
2 changed files with 54 additions and 41 deletions

View file

@ -1,69 +1,63 @@
# For tests # For tests
import logging import logging
from getpass import getpass
import os import os
import click import click
from qobuz_dl_rewrite.config import Config from .config import Config
from qobuz_dl_rewrite.constants import CACHE_DIR, CONFIG_DIR, CONFIG_PATH from .constants import CACHE_DIR, CONFIG_DIR, CONFIG_PATH
from qobuz_dl_rewrite.core import MusicDL from .core import MusicDL
from qobuz_dl_rewrite.utils import init_log
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
config = Config(CONFIG_PATH)
def _get_config(ctx): def _get_config(ctx):
print(f"{ctx.obj=}")
if not os.path.isdir(CONFIG_DIR): if not os.path.isdir(CONFIG_DIR):
os.makedirs(CONFIG_DIR) os.makedirs(CONFIG_DIR)
if not os.path.isdir(CACHE_DIR): if not os.path.isdir(CACHE_DIR):
os.makedirs(CONFIG_DIR) os.makedirs(CONFIG_DIR)
config = Config(ctx.obj.get("config")) config = Config(CONFIG_PATH)
config.update_from_cli(**ctx.obj) config.update_from_cli(**ctx.obj)
return config return config
# fmt: off
@click.group() @click.group()
@click.option("--debug", default=False, is_flag=True, help="Enable debug logging") @click.option("--debug", default=False, is_flag=True, help="Enable debug logging")
@click.option("--flush-cache", metavar="PATH", help="Flush the cache before running (only for extreme cases)") @click.option("--flush-cache", metavar="PATH", help="Flush the cache before running (only for extreme cases)")
@click.option("-c", '--convert', metavar='CODEC')
@click.pass_context @click.pass_context
# fmt: on
def cli(ctx, **kwargs): def cli(ctx, **kwargs):
"""cli. """cli.
$ rip www.qobuz.com/album/id1089374 convert -c ALAC -sr 48000 $ rip www.qobuz.com/album/id1089374 convert -c ALAC -sr 48000
> download and convert to alac, downsample to 48kHz > download and convert to alac, downsample to 48kHz
$ rip config --read $ rip config --read
> Config(...) > Config(...)
$ rip config --qobuzpwd MyQobuzPwd123 --qobuzemail person@email.com
$ rip config --tidalpwd MyTidalPwd123 --tidalemail person@email.com
> sets the credentials
$ rip www.qobuz.com/artist/id223049 filter --studio-albums --no-repeats $ rip www.qobuz.com/artist/id223049 filter --studio-albums --no-repeats
> download discography with given filters > download discography with given filters
:param ctx:
:param kwargs:
""" """
ctx.ensure_object(dict) print(f"{ctx=}")
print(f"{kwargs=}")
for key in kwargs.keys():
ctx.obj[key] = kwargs.get(key)
if ctx.obj["debug"]:
init_log(path=ctx.obj.get("log_file"))
else:
click.secho("Debug is not enabled", fg="yellow")
@click.command(name="dl") @click.command(name="dl")
@click.option("-q", "--quality", metavar="INT", help="Quality integer ID (5, 6, 7, 27)") @click.option("-q", "--quality", metavar="INT", help="Quality integer ID (5, 6, 7, 27)")
@click.option("--large-cover", is_flag=True, help="Download large covers (it might fail with embed)")
@click.option("-f", "--folder", metavar="PATH", help="Custom download folder") @click.option("-f", "--folder", metavar="PATH", help="Custom download folder")
@click.option("-s", "--search", metavar='QUERY')
@click.option("-nd", "--no-db", is_flag=True)
@click.argument("items", nargs=-1) @click.argument("items", nargs=-1)
@click.pass_context @click.pass_context
def download(ctx, items): def download(ctx, quality, folder, search, items):
""" """
Download an URL, space separated URLs or a text file with URLs. Download an URL, space separated URLs or a text file with URLs.
Mixed arguments are also supported. Mixed arguments are also supported.
@ -84,6 +78,7 @@ def download(ctx, items):
* Tidal (album, artist, track, playlist) * Tidal (album, artist, track, playlist)
""" """
ctx.ensure_object(dict)
config = _get_config(ctx) config = _get_config(ctx)
core = MusicDL(config) core = MusicDL(config)
for item in items: for item in items:
@ -100,14 +95,27 @@ def download(ctx, items):
) )
@click.command() @click.command(name='config')
@click.argument("--path") @click.option('-o', "--open", is_flag=True)
@click.argument("--read") @click.option("-q", '--qobuz', is_flag=True)
def config(path, read): @click.option("-t", '--tidal', is_flag=True)
if path: def edit_config(open, qobuz, tidal):
click.echo(CONFIG_PATH) if open:
if read: # open in text editor
click.echo(repr(config)) click.launch(CONFIG_PATH)
return
if qobuz:
config['qobuz']['email'] = input("Qobuz email: ")
config['qobuz']['password'] = getpass("Qobuz password: ")
config.save()
click.secho(f"Config saved at {CONFIG_PATH}", fg='green')
if tidal:
config['tidal']['email'] = input("Tidal email: ")
config['tidal']['password'] = getpass("Tidal password: ")
config.save()
click.secho(f"Config saved at {CONFIG_PATH}", fg='green')
@click.command() @click.command()
@ -115,15 +123,15 @@ def config(path, read):
help='Type to search for. Can be album, artist, playlist, track') help='Type to search for. Can be album, artist, playlist, track')
@click.argument("QUERY") @click.argument("QUERY")
def search(media_type, query): def search(media_type, query):
pass print(f"searching for {media_type} with {query=}")
@click.command() @click.command()
@click.option("-c", "--codec", default='ALAC')
@click.option("-sr", '--sampling-rate') @click.option("-sr", '--sampling-rate')
@click.option("-bd", "--bit-depth") @click.option("-bd", "--bit-depth")
def convert(codec, sampling_rate, bit_depth): @click.argument("codec")
pass def convert(sampling_rate, bit_depth, codec):
print(codec, sampling_rate, bit_depth)
@click.command() @click.command()
@ -137,18 +145,23 @@ def interactive():
@click.option("--studio-albums", is_flag=True, help="Ignore non-studio albums") @click.option("--studio-albums", is_flag=True, help="Ignore non-studio albums")
@click.option("--remaster-only", is_flag=True, help="Ignore non-remastered albums") @click.option("--remaster-only", is_flag=True, help="Ignore non-remastered albums")
@click.option("--albums-only", is_flag=True, help="Ignore non-album downloads") @click.option("--albums-only", is_flag=True, help="Ignore non-album downloads")
def filter(): def filter(*args):
pass print(f"filter {args=}")
@click.command() @click.command()
@click.option("--default-comment", metavar="COMMENT", help="Custom comment tag for audio files") @click.option("--default-comment", metavar="COMMENT", help="Custom comment tag for audio files")
def tags(): @click.option("--no-cover", help='Do not embed cover into audio file.')
pass def tags(default_comment, no_cover):
print(f"{default_comment=}, {no_cover=}")
def main(): def main():
cli.add_command(download) cli.add_command(download)
cli.add_command(filter)
cli.add_command(tags)
cli.add_command(edit_config)
cli.add_command(convert)
cli(obj={}) cli(obj={})

View file

@ -98,7 +98,7 @@ class Config:
def update_from_cli(self, **kwargs): def update_from_cli(self, **kwargs):
for category in (self.downloads, self.metadata, self.filters): for category in (self.downloads, self.metadata, self.filters):
for key in category.keys(): for key in category.keys():
if kwargs[key] is None: if kwargs.get(key) is None:
continue continue
# For debugging's sake # For debugging's sake