Print placeholders in twitch-dl info

This commit is contained in:
Ivan Habunek 2024-03-30 07:32:12 +01:00
parent 1c1e5955b8
commit 11fbfd35fc
No known key found for this signature in database
GPG Key ID: F5F0623FF5EBCB3D
4 changed files with 42 additions and 7 deletions

View File

@ -1,6 +1,5 @@
import asyncio import asyncio
import platform import platform
import click
import httpx import httpx
import m3u8 import m3u8
import os import os
@ -16,7 +15,7 @@ from urllib.parse import urlparse, urlencode
from twitchdl import twitch, utils from twitchdl import twitch, utils
from twitchdl.download import download_file from twitchdl.download import download_file
from twitchdl.entities import DownloadOptions from twitchdl.entities import Data, DownloadOptions
from twitchdl.exceptions import ConsoleError from twitchdl.exceptions import ConsoleError
from twitchdl.http import download_all from twitchdl.http import download_all
from twitchdl.output import print_out from twitchdl.output import print_out
@ -115,16 +114,16 @@ def _concat_vods(vod_paths: list[str], target: str):
raise ConsoleError(f"Joining files failed: {result.stderr}") raise ConsoleError(f"Joining files failed: {result.stderr}")
def _video_target_filename(video, args: DownloadOptions): def get_video_placeholders(video: Data, format: str) -> Data:
date, time = video['publishedAt'].split("T") date, time = video['publishedAt'].split("T")
game = video["game"]["name"] if video["game"] else "Unknown" game = video["game"]["name"] if video["game"] else "Unknown"
subs = { return {
"channel": video["creator"]["displayName"], "channel": video["creator"]["displayName"],
"channel_login": video["creator"]["login"], "channel_login": video["creator"]["login"],
"date": date, "date": date,
"datetime": video["publishedAt"], "datetime": video["publishedAt"],
"format": args.format, "format": format,
"game": game, "game": game,
"game_slug": utils.slugify(game), "game_slug": utils.slugify(game),
"id": video["id"], "id": video["id"],
@ -133,6 +132,10 @@ def _video_target_filename(video, args: DownloadOptions):
"title_slug": utils.slugify(video["title"]), "title_slug": utils.slugify(video["title"]),
} }
def _video_target_filename(video: Data, args: DownloadOptions):
subs = get_video_placeholders(video, args.format)
try: try:
return args.output.format(**subs) return args.output.format(**subs)
except KeyError as e: except KeyError as e:

View File

@ -1,8 +1,9 @@
import m3u8 import m3u8
from twitchdl import utils, twitch from twitchdl import utils, twitch
from twitchdl.commands.download import get_video_placeholders
from twitchdl.exceptions import ConsoleError from twitchdl.exceptions import ConsoleError
from twitchdl.output import print_video, print_clip, print_json, print_out, print_log from twitchdl.output import print_table, print_video, print_clip, print_json, print_out, print_log
def info(id: str, *, json: bool = False): def info(id: str, *, json: bool = False):
video_id = utils.parse_video_identifier(id) video_id = utils.parse_video_identifier(id)
@ -61,6 +62,11 @@ def video_info(video, playlists, chapters):
duration = utils.format_time(chapter["durationMilliseconds"] // 1000) duration = utils.format_time(chapter["durationMilliseconds"] // 1000)
print_out(f'{start} <b>{chapter["description"]}</b> ({duration})') print_out(f'{start} <b>{chapter["description"]}</b> ({duration})')
placeholders = get_video_placeholders(video, format = "mkv")
placeholders = [[f"{{{k}}}", v] for k, v in placeholders.items()]
print_out("")
print_table(["Placeholder", "Value"], placeholders)
def video_json(video, playlists, chapters): def video_json(video, playlists, chapters):
playlists = m3u8.loads(playlists).playlists playlists = m3u8.loads(playlists).playlists

View File

@ -1,4 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any
@dataclass @dataclass
@ -17,3 +18,8 @@ class DownloadOptions:
rate_limit: str | None rate_limit: str | None
start: int | None start: int | None
max_workers: int max_workers: int
# Type for annotating decoded JSON
# TODO: make data classes for common structs
Data = dict[str, Any]

View File

@ -1,6 +1,7 @@
import click
import json import json
import sys
import re import re
import sys
from itertools import islice from itertools import islice
from twitchdl import utils from twitchdl import utils
@ -75,6 +76,25 @@ def print_log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs) print(*args, file=sys.stderr, **kwargs)
def print_table(headers: list[str], data: list[list[str]]):
widths = [[len(cell) for cell in row] for row in data + [headers]]
widths = [max(width) for width in zip(*widths)]
underlines = ["-" * width for width in widths]
def print_row(row: list[str]):
for idx, cell in enumerate(row):
width = widths[idx]
click.echo(cell.ljust(width), nl=False)
click.echo(" ", nl=False)
click.echo()
print_row(headers)
print_row(underlines)
for row in data:
print_row(row)
def print_video(video): def print_video(video):
published_at = video["publishedAt"].replace("T", " @ ").replace("Z", "") published_at = video["publishedAt"].replace("T", " @ ").replace("Z", "")
length = utils.format_duration(video["lengthSeconds"]) length = utils.format_duration(video["lengthSeconds"])