Files
tidal-dl/tidal_dl_ng/cli.py
T

305 lines
9.3 KiB
Python
Raw Normal View History

2023-12-19 23:58:57 +01:00
#!/usr/bin/env python
2024-01-12 10:47:17 +01:00
from pathlib import Path
from typing import Annotated, Optional
2024-01-12 10:47:17 +01:00
2023-12-19 23:58:57 +01:00
import typer
from rich.live import Live
from rich.panel import Panel
from rich.progress import BarColumn, Console, Progress, SpinnerColumn, TextColumn
from rich.table import Table
2024-04-01 18:58:37 +02:00
from tidal_dl_ng import __version__
from tidal_dl_ng.config import Settings, Tidal
from tidal_dl_ng.constants import CTX_TIDAL, MediaType
from tidal_dl_ng.download import Download
2024-01-14 23:09:43 +01:00
from tidal_dl_ng.helper.path import get_format_template, path_file_settings
2024-05-22 06:33:40 +02:00
from tidal_dl_ng.helper.tidal import (
all_artist_album_ids,
get_tidal_media_id,
get_tidal_media_type,
instantiate_media,
)
2024-01-19 08:17:47 +01:00
from tidal_dl_ng.helper.wrapper import LoggerWrapped
from tidal_dl_ng.model.cfg import HelpSettings
2023-12-19 23:58:57 +01:00
2024-01-19 18:00:16 +01:00
app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}, add_completion=False)
2025-01-03 15:23:42 +00:00
dl_fav_group = typer.Typer(
context_settings={"help_option_names": ["-h", "--help"]},
add_completion=True,
help="Download from a favorites collection.",
)
app.add_typer(dl_fav_group, name="dl_fav")
2023-12-19 23:58:57 +01:00
def version_callback(value: bool):
if value:
2024-04-01 18:58:37 +02:00
print(f"{__version__}")
2023-12-19 23:58:57 +01:00
raise typer.Exit()
def _download(ctx: typer.Context, urls: list[str], try_login: bool = True):
"""
Shared logic for downloading a list of URLs.
:param ctx: The typer context
:type ctx: typer.Context
:param urls: The list of URLs to download.
:type urls: list[str]
:return: True if ran successfully.
"""
if try_login:
# Call login method to validate the token.
ctx.invoke(login, ctx)
# Create initial objects.
settings: Settings = Settings()
progress: Progress = Progress(
"{task.description}",
SpinnerColumn(),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
)
fn_logger = LoggerWrapped(progress.print)
dl = Download(
session=ctx.obj[CTX_TIDAL].session,
skip_existing=ctx.obj[CTX_TIDAL].settings.data.skip_existing,
path_base=settings.data.download_base_path,
fn_logger=fn_logger, # noqa: type
progress=progress,
)
progress_table = Table.grid()
# Style Progress display.
progress_table.add_row(Panel.fit(progress, title="Download Progress", border_style="green", padding=(2, 2)))
urls_pos_last = len(urls) - 1
for item in urls:
media_type: MediaType | bool = False
# Extract media name and id from link.
if "http" in item:
media_type = get_tidal_media_type(item)
item_id = get_tidal_media_id(item)
file_template = get_format_template(media_type, settings)
else:
print(f"It seems like that you have supplied an invalid URL: {item}")
continue
# Create Live display for Progress.
with Live(progress_table, refresh_per_second=10):
# Download media.
if media_type in [MediaType.TRACK, MediaType.VIDEO]:
download_delay: bool = bool(settings.data.download_delay and urls.index(item) < urls_pos_last)
dl.item(
media_id=item_id, media_type=media_type, file_template=file_template, download_delay=download_delay
)
elif media_type in [MediaType.ALBUM, MediaType.PLAYLIST, MediaType.MIX, MediaType.ARTIST]:
item_ids: [int] = []
if media_type == MediaType.ARTIST:
media = instantiate_media(ctx.obj[CTX_TIDAL].session, media_type, item_id)
media_type = MediaType.ALBUM
item_ids = item_ids + all_artist_album_ids(media)
else:
item_ids.append(item_id)
for item_id in item_ids:
dl.items(
media_id=item_id,
media_type=media_type,
file_template=file_template,
video_download=ctx.obj[CTX_TIDAL].settings.data.video_download,
download_delay=settings.data.download_delay,
)
# Stop Progress display.
progress.stop()
return True
2023-12-19 23:58:57 +01:00
@app.callback()
def callback_app(
ctx: typer.Context,
2024-01-12 10:51:30 +01:00
version: Annotated[
Optional[bool], typer.Option("--version", "-v", callback=version_callback, is_eager=True)
] = None,
2023-12-19 23:58:57 +01:00
):
ctx.obj = {"tidal": None}
@app.command(name="cfg")
def settings_management(
names: Annotated[Optional[list[str]], typer.Argument()] = None,
2023-12-19 23:58:57 +01:00
editor: Annotated[
bool, typer.Option("--editor", "-e", help="Open the settings file in your default editor.")
] = False,
):
"""
Print or set an option.
If no arguments are given, all options will be listed.
If only one argument is given, the value will be printed for this option.
To set a value for an option simply pass the value as the second argument
:param names: (Optional) None (list all options), one (list the value only for this option) or two arguments
(set the value for the option).
"""
if editor:
config_path: Path = Path(path_file_settings())
if not config_path.is_file():
config_path.write_text('{"version": "1.0.0"}')
config_file_str = str(config_path)
typer.launch(config_file_str)
else:
settings = Settings()
d_settings = settings.data.to_dict()
if names:
if names[0] not in d_settings:
print(f'Option "{names[0]}" is not valid!')
else:
if len(names) == 1:
print(f'{names[0]}: "{d_settings[names[0]]}"')
elif len(names) > 1:
settings.set_option(names[0], names[1])
settings.save()
else:
help_settings: dict = HelpSettings().to_dict()
table = Table(title=f"Config: {path_file_settings()}")
table.add_column("Key", style="cyan", no_wrap=True)
table.add_column("Value", style="magenta")
table.add_column("Description", style="green")
# Iterate over the attributes of the dataclass
for key, value in sorted(d_settings.items()):
table.add_row(key, str(value), help_settings[key])
console = Console()
console.print(table)
@app.command(name="login")
def login(ctx: typer.Context) -> bool:
print("Let us check, if you are already logged in... ", end="")
settings = Settings()
tidal = Tidal(settings)
result = tidal.login(fn_print=print)
2023-12-19 23:58:57 +01:00
ctx.obj[CTX_TIDAL] = tidal
return result
2024-05-03 20:38:29 +02:00
@app.command(name="logout")
def logout() -> bool:
settings = Settings()
tidal = Tidal(settings)
result = tidal.logout()
if result:
print("You have been successfully logged out.")
return result
2023-12-19 23:58:57 +01:00
@app.command(name="dl")
def download(
ctx: typer.Context,
2024-01-14 23:09:43 +01:00
urls: Annotated[Optional[list[str]], typer.Argument()] = None,
file_urls: Annotated[
2023-12-19 23:58:57 +01:00
Optional[Path],
typer.Option(
"--list",
"-l",
exists=True,
file_okay=True,
dir_okay=False,
writable=False,
readable=True,
resolve_path=True,
help="List with URLs to download. One per line",
),
] = None,
):
2024-01-14 23:09:43 +01:00
if not urls:
# Read the text file provided.
if file_urls:
text = file_urls.read_text()
2024-01-14 23:09:43 +01:00
urls = text.splitlines()
2023-12-19 23:58:57 +01:00
else:
print("Provide either URLs, IDs or a file containing URLs (one per line).")
raise typer.Abort()
return _download(ctx, urls)
2023-12-19 23:58:57 +01:00
@dl_fav_group.command(
name="tracks",
help="Download your saved, favorite tracks collection.",
)
def download_fav_tracks(ctx: typer.Context):
# Call login method to validate the token.
ctx.invoke(login, ctx)
# Get favorite tracks
track_urls = [track.share_url for track in ctx.obj[CTX_TIDAL].session.user.favorites.tracks()]
return _download(ctx, track_urls, try_login=False)
@dl_fav_group.command(
name="artists",
help="Download your saved, favorite artists collection.",
)
def download_fav_artists(ctx: typer.Context):
# Call login method to validate the token.
ctx.invoke(login, ctx)
# Get favorite artists
artist_urls = [artist.share_url for artist in ctx.obj[CTX_TIDAL].session.user.favorites.artists()]
return _download(ctx, artist_urls, try_login=False)
@dl_fav_group.command(
name="albums",
help="Download your saved, favorite albums collection.",
)
def download_fav_albums(ctx: typer.Context):
# Call login method to validate the token.
ctx.invoke(login, ctx)
# Get favorite artists
artist_urls = [artist.share_url for artist in ctx.obj[CTX_TIDAL].session.user.favorites.albums()]
return _download(ctx, artist_urls, try_login=False)
@dl_fav_group.command(
name="videos",
help="Download your saved, favorite videos collection.",
)
def download_fav_videos(ctx: typer.Context):
# Call login method to validate the token.
ctx.invoke(login, ctx)
# Get favorite artists
artist_urls = [artist.share_url for artist in ctx.obj[CTX_TIDAL].session.user.favorites.videos()]
return _download(ctx, artist_urls, try_login=False)
2023-12-19 23:58:57 +01:00
@app.command()
def gui(ctx: typer.Context):
from tidal_dl_ng.gui import gui_activate
ctx.invoke(login, ctx)
gui_activate(ctx.obj[CTX_TIDAL])
if __name__ == "__main__":
app()