"""Validation and safe CLI results around the unchanged streaming library.""" import argparse import json import os from pathlib import Path import re import sys from urllib.parse import urlsplit LANGUAGES = ("engsub", "engdub", "gersub", "gerdub") MAX_SAFE_INTEGER = 9007199254740991 MAX_TOKEN_BYTES = 8192 MAX_URL_LENGTH = 2048 MAX_SERIES_LIMIT = 10000 RESULT_PREFIX = "PROXER_RESULT " class ValidationError(ValueError): """An input error whose message is safe to display.""" class SafeArgumentParser(argparse.ArgumentParser): def error(self, message): # argparse's default error may echo an unrecognised credential argument. raise ValidationError("Invalid command-line arguments. Use --help for usage.") def positive_integer(value, label): text = str(value) if not re.fullmatch(r"[1-9][0-9]*", text): raise ValidationError(f"{label} must be a positive whole number.") if len(text) > len(str(MAX_SAFE_INTEGER)): raise ValidationError(f"{label} exceeds the supported integer range.") number = int(text) if number > MAX_SAFE_INTEGER: raise ValidationError(f"{label} exceeds the supported integer range.") return number def parse_token(token): if not isinstance(token, str): raise ValidationError("Token must be a cookie in name=value format.") try: if len(token.encode("utf-8")) > MAX_TOKEN_BYTES: raise ValidationError("Token exceeds the supported length.") except UnicodeEncodeError: raise ValidationError("Token contains invalid text.") from None name, separator, value = token.partition("=") if not separator or not re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", name): raise ValidationError("Token must be a cookie in name=value format.") if not value or any(character.isspace() or ord(character) < 32 or 127 <= ord(character) <= 159 or character == ";" for character in value): raise ValidationError("Token contains an empty or invalid cookie value.") return name, value def token_from_args(args, stream=None): if not args.token_stdin: return parse_token(args.token) stream = sys.stdin if stream is None else stream reader = getattr(stream, "buffer", stream) try: raw = reader.read(MAX_TOKEN_BYTES + 3) if isinstance(raw, str): raw = raw.encode("utf-8") if raw.endswith(b"\r\n"): raw = raw[:-2] elif raw.endswith(b"\n"): raw = raw[:-1] if len(raw) > MAX_TOKEN_BYTES: raise ValidationError("Token exceeds the supported length.") return parse_token(raw.decode("utf-8")) except (UnicodeError, OSError): raise ValidationError("Token input could not be read as UTF-8 text.") from None def validate_auth_cookie(auth_cookie): if not isinstance(auth_cookie, (tuple, list)) or len(auth_cookie) != 2: raise ValidationError("Token must contain exactly one cookie name and value.") name, value = auth_cookie if not isinstance(name, str) or not isinstance(value, str): raise ValidationError("Token must contain a cookie name and value.") parsed = parse_token(f"{name}={value}") if parsed[0] != name: raise ValidationError("Token contains an invalid cookie name.") return parsed def validate_watch_url(value): if (not isinstance(value, str) or len(value) > MAX_URL_LENGTH or "\\" in value or any(char.isspace() or ord(char) < 32 or 127 <= ord(char) <= 159 for char in value)): raise ValidationError("URL must be a valid HTTPS Proxer watch URL.") try: parsed = urlsplit(value) if (parsed.scheme != "https" or parsed.hostname not in {"proxer.me", "www.proxer.me"} or parsed.username is not None or parsed.password is not None or parsed.port not in (None, 443) or parsed.query): raise ValueError except ValueError: raise ValidationError("URL must be an HTTPS Proxer watch URL without credentials or query parameters.") from None match = re.fullmatch(r"/watch/([1-9][0-9]*)/([1-9][0-9]*)/(engsub|engdub|gersub|gerdub)/?", parsed.path) if not match: raise ValidationError("URL must identify a Proxer series, episode, and supported language.") series_id = positive_integer(match.group(1), "Series ID") episode = positive_integer(match.group(2), "Episode") return f"https://proxer.me/watch/{series_id}/{episode}/{match.group(3)}" def validate_filename(filename): if (not isinstance(filename, str) or not filename or filename != filename.strip() or filename in {".", ".."} or "/" in filename or "\\" in filename or any(ord(character) < 32 or 127 <= ord(character) <= 159 for character in filename)): raise ValidationError("Filename must be a nonempty single name without path separators or control characters.") try: encoded_length = len((filename + ".mp4").encode("utf-8")) except UnicodeEncodeError: raise ValidationError("Filename contains invalid text.") from None if encoded_length > 255: raise ValidationError("Filename is too long for the output filesystem.") return filename def output_path(output_dir, filename): validate_filename(filename) try: directory = Path(output_dir).resolve(strict=True) except (OSError, RuntimeError): raise OSError("The configured output directory is unavailable.") from None except (TypeError, ValueError): raise ValidationError("Output directory must be a valid filesystem path.") from None if not directory.is_dir(): raise OSError("The configured output directory is unavailable.") target = directory / (filename + ".mp4") if target.is_symlink(): raise ValidationError("Output file must not be a symbolic link.") if target.exists() and not target.is_file(): raise ValidationError("Output file must be a regular file.") if target.resolve(strict=False).parent != directory: raise ValidationError("Output file must remain inside the configured output directory.") return target def verify_output(target): if target.is_symlink() or not target.is_file() or target.stat().st_size == 0: raise OSError("The download did not produce a nonempty regular output file.") def episode_range(value): if not isinstance(value, str) or not re.fullmatch(r"[1-9][0-9]*-[1-9][0-9]*", value): raise ValidationError("Episodes must be an inclusive start-end range of positive whole numbers.") start_text, end_text = value.split("-", 1) start = positive_integer(start_text, "First episode") end = positive_integer(end_text, "Last episode") if end < start: raise ValidationError("Last episode must not be smaller than first episode.") configured_maximum = os.environ.get("MAX_SERIES_EPISODES") or "500" if not re.fullmatch(r"[0-9]+", configured_maximum): raise ValidationError("MAX_SERIES_EPISODES must be a positive whole number.") normalized_maximum = configured_maximum.lstrip("0") or "0" if len(normalized_maximum) > len(str(MAX_SERIES_LIMIT)): raise ValidationError("MAX_SERIES_EPISODES must be between 1 and 10000.") maximum = int(normalized_maximum) if maximum < 1 or maximum > MAX_SERIES_LIMIT: raise ValidationError("MAX_SERIES_EPISODES must be between 1 and 10000.") if end - start + 1 > maximum: raise ValidationError("Episode range exceeds MAX_SERIES_EPISODES.") return start, end def error_result(error): """Classify exception metadata, never broad keyword matches or raw messages.""" chain = [] current = error while current is not None and len(chain) < 20 and all(current is not item for item in chain): chain.append(current) current = current.__cause__ or current.__context__ if isinstance(error, ValidationError): category, message = "validation", str(error) elif any(isinstance(item, ImportError) for item in chain): category, message = "configuration", "The download dependencies could not be loaded. Check the Python environment." elif any(getattr(getattr(item, "response", None), "status_code", None) in (401, 403) for item in chain): category = "authentication" message = "The source rejected authentication or access. Refresh the token or complete any required verification before retrying." elif any(getattr(getattr(item, "response", None), "status_code", None) == 404 for item in chain): category, message = "source", "The requested video could not be resolved." elif any(type(item).__name__ == "NotFoundError" and type(item).__module__ == "lib.proxer_utils" for item in chain): # Missing page markers can mean a challenge or a changed/unavailable # source. Preserve that uncertainty and require human verification. category = "resolution" message = "The video link could not be resolved. Check the source page and complete any required verification before retrying." elif any(type(item).__module__.startswith(("requests.", "urllib3.")) or (type(item).__name__ == "NetworkError" and type(item).__module__ == "lib.proxer_utils") for item in chain): category, message = "network", "The source could not be reached or the transfer was interrupted." elif isinstance(error, OSError): category, message = "storage", "The output file could not be written or validated." else: category, message = "unknown", "The download could not be completed." return {"version": 1, "status": "failed", "errorCategory": category, "message": message} def emit_result(result): # A leading newline isolates the record from the library's terminal progress bar. print("\n" + RESULT_PREFIX + json.dumps(result, ensure_ascii=True), flush=True)