forked from kenzuya/unshackle
fix(cli): make the click param types the one source of codec spellings
--acodec now lists its codecs in --help, --vcodec drops the duplicate entries, and the REST API derives its allowlists from the same types, so AC-4, DDP, VORB and sub_format "original" stop being rejected and H264 stops being silently dropped. Adds shell completion for --acodec and repairs MultipleChoice completion. Raises the click floor to 8.2.
This commit is contained in:
@@ -18,6 +18,7 @@ from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from unshackle.core.api.events import bus, publish_service_event
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.utils.click_types import VIDEO_CODEC_LIST
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_path, redact_text
|
||||
|
||||
log = logging.getLogger("download_manager")
|
||||
@@ -387,10 +388,7 @@ def perform_download(
|
||||
|
||||
vcodec_raw = params.get("vcodec")
|
||||
if vcodec_raw:
|
||||
if isinstance(vcodec_raw, str):
|
||||
vcodec_raw = [vcodec_raw]
|
||||
if isinstance(vcodec_raw, list) and vcodec_raw and not isinstance(vcodec_raw[0], Video.Codec):
|
||||
params["vcodec"] = to_enum(vcodec_raw, Video.Codec)
|
||||
params["vcodec"] = VIDEO_CODEC_LIST.convert(vcodec_raw)
|
||||
else:
|
||||
params["vcodec"] = []
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from http.cookiejar import CookieJar, MozillaCookieJar
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Iterable, List, Optional
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
|
||||
from unshackle.core.api.compression import safe_inflate
|
||||
@@ -33,6 +34,7 @@ from unshackle.core.services import Services
|
||||
from unshackle.core.titles import Episode, Movie, Song, Title_T
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST, SUBTITLE_CODEC, VIDEO_CODEC_LIST
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
||||
|
||||
@@ -1513,24 +1515,23 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
)
|
||||
|
||||
|
||||
VALID_VCODECS = ["H264", "H265", "H.264", "H.265", "AVC", "HEVC", "VC1", "VC-1", "VP8", "VP9", "AV1"]
|
||||
VALID_ACODECS = [
|
||||
"AAC",
|
||||
"AC3",
|
||||
"EC3",
|
||||
"EAC3",
|
||||
"DD",
|
||||
"DD+",
|
||||
"AC4",
|
||||
"OPUS",
|
||||
"FLAC",
|
||||
"ALAC",
|
||||
"VORBIS",
|
||||
"OGG",
|
||||
"DTS",
|
||||
"DTSX",
|
||||
"DTS-X",
|
||||
]
|
||||
VALID_VCODECS = [choice.upper() for choice in VIDEO_CODEC_LIST.choices]
|
||||
VALID_ACODECS = [choice.upper() for choice in AUDIO_CODEC_LIST.choices]
|
||||
VALID_SUB_FORMATS = [choice.upper() for choice in SUBTITLE_CODEC.choices]
|
||||
|
||||
|
||||
def resolve_vcodec(value: Any) -> Optional[list]:
|
||||
"""Map a client's vcodec field to codec enums.
|
||||
|
||||
Session routes do not run validate_download_parameters, so this must answer junk with a 400
|
||||
instead of letting click's UsageError surface as a 500.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return VIDEO_CODEC_LIST.convert(value) or None
|
||||
except click.UsageError as e:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}")
|
||||
|
||||
|
||||
def check_codec(value: Any, allowed: List[str], name: str) -> Optional[str]:
|
||||
@@ -1590,9 +1591,8 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
return err
|
||||
|
||||
if "sub_format" in data and data["sub_format"]:
|
||||
valid_sub_formats = ["SRT", "VTT", "ASS", "SSA", "TTML", "STPP", "WVTT", "SMI", "SUB", "MPL2", "TMP"]
|
||||
if data["sub_format"].upper() not in valid_sub_formats:
|
||||
return f"Invalid sub_format: {data['sub_format']}. Must be one of: {', '.join(valid_sub_formats)}"
|
||||
if str(data["sub_format"]).upper() not in VALID_SUB_FORMATS:
|
||||
return f"Invalid sub_format: {data['sub_format']}. Must be one of: {', '.join(VALID_SUB_FORMATS)}"
|
||||
|
||||
if "vbitrate" in data and data["vbitrate"] is not None:
|
||||
if not isinstance(data["vbitrate"], int) or data["vbitrate"] <= 0:
|
||||
@@ -2884,16 +2884,7 @@ def create_service_instance(
|
||||
pass
|
||||
range_values = range_values or None
|
||||
|
||||
vcodec_names = data.get("vcodec")
|
||||
vcodec_values: Optional[list] = None
|
||||
if vcodec_names:
|
||||
vcodec_values = []
|
||||
for name in vcodec_names:
|
||||
try:
|
||||
vcodec_values.append(Video.Codec[name])
|
||||
except KeyError:
|
||||
pass
|
||||
vcodec_values = vcodec_values or None
|
||||
vcodec_values = resolve_vcodec(data.get("vcodec"))
|
||||
|
||||
extra_params = {
|
||||
"range_": range_values,
|
||||
|
||||
@@ -675,14 +675,14 @@ async def download(request: web.Request) -> web.Response:
|
||||
- type: array
|
||||
items:
|
||||
type: string
|
||||
description: Video codec(s) to download (e.g., "H265" or ["H264", "H265"]) - accepts H264, H265, AVC, HEVC, VP8, VP9, AV1, VC1 (default - None)
|
||||
description: Video codec(s) to download (e.g., "HEVC" or ["AVC", "HEVC"]) - accepts AVC, H.264, H264, HEVC, H.265, H265, VC1, VC-1, VP8, VP9, AV1 (default - None)
|
||||
acodec:
|
||||
oneOf:
|
||||
- type: string
|
||||
- type: array
|
||||
items:
|
||||
type: string
|
||||
description: Audio codec(s) to download (e.g., "AAC" or ["AAC", "EC3"]) - accepts AAC, AC3, EC3, AC4, OPUS, FLAC, ALAC, DTS, DTSX, DTS-X, OGG (default - None)
|
||||
description: Audio codec(s) to download (e.g., "AAC" or ["AAC", "EC3"]) - accepts AAC, AC3, DD, EC3, DD+, EAC3, DDP, AC4, AC-4, OPUS, OGG, VORB, VORBIS, DTS, DTSX, DTS-X, ALAC, FLAC (default - None)
|
||||
vbitrate:
|
||||
type: integer
|
||||
description: Video bitrate in kbps (default - None)
|
||||
@@ -756,7 +756,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Use exact language matching (no variants) (default - false)
|
||||
sub_format:
|
||||
type: string
|
||||
description: Output subtitle format such as SRT or VTT (default - None)
|
||||
description: Output subtitle format such as SRT or VTT, or "original" to keep the source format (default - None)
|
||||
video_only:
|
||||
type: boolean
|
||||
description: Only download video tracks (default - false)
|
||||
|
||||
@@ -7,6 +7,8 @@ from click.shell_completion import CompletionItem
|
||||
from pywidevine.cdm import Cdm as WidevineCdm
|
||||
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
|
||||
|
||||
class VideoCodecChoice(click.Choice):
|
||||
@@ -18,27 +20,31 @@ class VideoCodecChoice(click.Choice):
|
||||
- Enum values: H.264, H.265, VC-1, VP8, VP9, AV1
|
||||
"""
|
||||
|
||||
def __init__(self, codec_enum):
|
||||
def __init__(self, codec_enum: type[Video.Codec]) -> None:
|
||||
self.codec_enum = codec_enum
|
||||
choices = []
|
||||
self._name_to_codec: dict[str, Video.Codec] = {}
|
||||
for codec in codec_enum:
|
||||
choices.append(codec.name.lower()) # e.g., "avc", "hevc"
|
||||
choices.append(codec.value) # e.g., "H.264", "H.265"
|
||||
super().__init__(choices, case_sensitive=False)
|
||||
for choice in (codec.name.lower(), codec.value.lower()):
|
||||
self._name_to_codec[choice] = codec
|
||||
|
||||
def convert(self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None):
|
||||
aliases = {"h264": "AVC", "h265": "HEVC"}
|
||||
for alias, target in aliases.items():
|
||||
if target in codec_enum.__members__:
|
||||
self._name_to_codec[alias] = codec_enum[target]
|
||||
|
||||
super().__init__(list(self._name_to_codec), case_sensitive=False)
|
||||
|
||||
def convert(self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None) -> Any:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, self.codec_enum):
|
||||
return value
|
||||
|
||||
converted_value = super().convert(value, param, ctx)
|
||||
|
||||
for codec in self.codec_enum:
|
||||
if converted_value.lower() == codec.name.lower():
|
||||
return codec
|
||||
if converted_value == codec.value:
|
||||
return codec
|
||||
|
||||
self.fail(f"'{value}' is not a valid video codec", param, ctx)
|
||||
codec = self._name_to_codec.get(str(converted_value).lower())
|
||||
if codec is None:
|
||||
self.fail(f"'{value}' is not a valid video codec", param, ctx)
|
||||
return codec
|
||||
|
||||
|
||||
class MultipleVideoCodecChoice(VideoCodecChoice):
|
||||
@@ -64,7 +70,10 @@ class MultipleVideoCodecChoice(VideoCodecChoice):
|
||||
|
||||
chosen_values: list[Any] = []
|
||||
for v in values:
|
||||
chosen_values.append(super().convert(v.strip(), param, ctx))
|
||||
token = v.strip() if isinstance(v, str) else str(v).strip()
|
||||
if not token:
|
||||
continue
|
||||
chosen_values.append(super().convert(token, param, ctx))
|
||||
return chosen_values
|
||||
|
||||
|
||||
@@ -351,12 +360,12 @@ class AudioCodecList(click.ParamType):
|
||||
|
||||
name = "audio_codec_list"
|
||||
|
||||
def __init__(self, codec_enum):
|
||||
def __init__(self, codec_enum: type[Audio.Codec]) -> None:
|
||||
self.codec_enum = codec_enum
|
||||
self._name_to_codec: dict[str, Audio.Codec] = {}
|
||||
for codec in codec_enum:
|
||||
self._name_to_codec[codec.name.lower()] = codec
|
||||
self._name_to_codec[codec.value.lower()] = codec
|
||||
for choice in (codec.name.lower(), codec.value.lower()):
|
||||
self._name_to_codec[choice] = codec
|
||||
|
||||
aliases = {
|
||||
"eac3": "EC3",
|
||||
@@ -367,6 +376,14 @@ class AudioCodecList(click.ParamType):
|
||||
if target in codec_enum.__members__:
|
||||
self._name_to_codec[alias] = codec_enum[target]
|
||||
|
||||
@property
|
||||
def choices(self) -> list[str]:
|
||||
"""Every spelling convert() accepts, in declaration order. Mirrors click.Choice.choices."""
|
||||
return list(self._name_to_codec)
|
||||
|
||||
def get_metavar(self, *args: Any, **kwargs: Any) -> str:
|
||||
return f"[{'|'.join(self.choices)}]"
|
||||
|
||||
def convert(self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None) -> list:
|
||||
if not value:
|
||||
return []
|
||||
@@ -387,10 +404,21 @@ class AudioCodecList(click.ParamType):
|
||||
if key in self._name_to_codec:
|
||||
codecs.append(self._name_to_codec[key])
|
||||
else:
|
||||
valid = sorted(set(self._name_to_codec.keys()))
|
||||
self.fail(f"'{val}' is not valid. Choices: {', '.join(valid)}", param, ctx)
|
||||
self.fail(f"'{val}' is not valid. Choices: {', '.join(sorted(self.choices))}", param, ctx)
|
||||
return list(dict.fromkeys(codecs)) # Remove duplicates, preserve order
|
||||
|
||||
def shell_complete(self, ctx: click.Context, param: click.Parameter, incomplete: str) -> list[CompletionItem]:
|
||||
"""
|
||||
Complete the codec after the last comma.
|
||||
|
||||
Parameters:
|
||||
ctx: Invocation context for this command.
|
||||
param: The parameter that requests completion.
|
||||
incomplete: The value to complete. Can be empty.
|
||||
"""
|
||||
prefix, sep, last = incomplete.rpartition(",")
|
||||
return [CompletionItem(f"{prefix}{sep}{choice}") for choice in self.choices if choice.startswith(last.lower())]
|
||||
|
||||
|
||||
class MultipleChoice(click.Choice):
|
||||
"""
|
||||
@@ -425,15 +453,21 @@ class MultipleChoice(click.Choice):
|
||||
|
||||
def shell_complete(self, ctx: click.Context, param: click.Parameter, incomplete: str) -> list[CompletionItem]:
|
||||
"""
|
||||
Complete choices that start with the incomplete value.
|
||||
Complete the choice after the last comma.
|
||||
|
||||
Parameters:
|
||||
ctx: Invocation context for this command.
|
||||
param: The parameter that requests completion.
|
||||
incomplete: The value to complete. Can be empty.
|
||||
"""
|
||||
incomplete = incomplete.rsplit(",")[-1]
|
||||
return super(self).shell_complete(ctx, param, incomplete)
|
||||
prefix, sep, last = incomplete.rpartition(",")
|
||||
if not self.case_sensitive:
|
||||
last = last.casefold()
|
||||
return [
|
||||
CompletionItem(f"{prefix}{sep}{choice}")
|
||||
for choice in (self.normalize_choice(c, ctx) for c in self.choices)
|
||||
if choice.startswith(last)
|
||||
]
|
||||
|
||||
|
||||
class SlowDelayRange(click.ParamType):
|
||||
@@ -466,4 +500,6 @@ SEASON_RANGE = SeasonRange()
|
||||
LANGUAGE_RANGE = LanguageRange()
|
||||
QUALITY_LIST = QualityList()
|
||||
AUDIO_CODEC_LIST = AudioCodecList(Audio.Codec)
|
||||
VIDEO_CODEC_LIST = MultipleVideoCodecChoice(Video.Codec)
|
||||
SUBTITLE_CODEC = SubtitleCodecChoice(Subtitle.Codec)
|
||||
SLOW_DELAY_RANGE = SlowDelayRange()
|
||||
|
||||
Reference in New Issue
Block a user