phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
+82
-45
@@ -1,62 +1,99 @@
|
||||
import sys
|
||||
import argparse
|
||||
from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4
|
||||
|
||||
# Protect scripts/lib/__pycache__ even when this CLI is invoked without python -B.
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
from time import sleep
|
||||
|
||||
def download_series_series(serie_id, pretty_name, episode_range, language, auth_token, output_dir):
|
||||
"""
|
||||
Downloads all episodes in a specified range of a series.
|
||||
from request_validation import (
|
||||
LANGUAGES,
|
||||
SafeArgumentParser,
|
||||
ValidationError,
|
||||
emit_result,
|
||||
episode_range as validate_episode_range,
|
||||
error_result,
|
||||
output_path,
|
||||
token_from_args,
|
||||
positive_integer,
|
||||
validate_auth_cookie,
|
||||
validate_filename,
|
||||
verify_output,
|
||||
)
|
||||
|
||||
:param serie_id: The ID of the series (Proxer)
|
||||
:param pretty_name: Pretty name for the series used in file names
|
||||
:param episode_range: A string in the format of "start-end" (inclusive range of episodes)
|
||||
:param language: The preferred language (e.g., 'engsub', 'gerdub')
|
||||
:param auth_token: A tuple containing (cookie_name, cookie_value)
|
||||
:param output_dir: Directory to store downloaded videos
|
||||
"""
|
||||
start, end = map(int, episode_range.split("-"))
|
||||
for episode_number in range(start, end + 1):
|
||||
|
||||
def download_series_series(serie_id, pretty_name, episode_range, language, auth_token, output_dir):
|
||||
"""Preserve sequential CLI naming and report every failed episode."""
|
||||
serie_id = positive_integer(serie_id, "Series ID")
|
||||
validate_filename(pretty_name)
|
||||
start, end = validate_episode_range(episode_range)
|
||||
if language not in LANGUAGES:
|
||||
raise ValidationError("Language is not supported.")
|
||||
auth_token = validate_auth_cookie(auth_token)
|
||||
|
||||
# Validate every output before beginning a series, including long generated names.
|
||||
targets = [(episode, output_path(output_dir, f"{pretty_name}_Episode_{episode}_{language}"))
|
||||
for episode in range(start, end + 1)]
|
||||
|
||||
from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4
|
||||
|
||||
completed = 0
|
||||
failures = []
|
||||
for episode_number, target in targets:
|
||||
episode_url = f"https://proxer.me/watch/{serie_id}/{episode_number}/{language}"
|
||||
try:
|
||||
print(f"Fetching embed URL for episode {episode_number} for {episode_url}...")
|
||||
print(f"Resolving episode {episode_number}...", flush=True)
|
||||
embed_url = get_embed_url(episode_url, auth_token)
|
||||
print(f"Embed URL fetched for episode {episode_number}: {embed_url}")
|
||||
|
||||
print(f"Fetching MP4 URL for episode {episode_number}...")
|
||||
mp4_url = get_mp4_url(embed_url)
|
||||
print(f"MP4 URL fetched for episode {episode_number}: {mp4_url}")
|
||||
print(f"Downloading episode {episode_number}...", flush=True)
|
||||
download_mp4(mp4_url, str(target), label=f"Episode {episode_number} ({language})")
|
||||
verify_output(target)
|
||||
completed += 1
|
||||
except Exception as error:
|
||||
result = error_result(error)
|
||||
failures.append({"episode": episode_number, "errorCategory": result["errorCategory"]})
|
||||
print(f"Episode {episode_number} failed: {result['message']}", flush=True)
|
||||
if result["errorCategory"] in {"authentication", "resolution", "storage", "configuration"}:
|
||||
# Access, unresolved links, and host failures need intervention.
|
||||
break
|
||||
if episode_number < end:
|
||||
sleep(1)
|
||||
|
||||
# Prepare the output file path
|
||||
output_file = f"{output_dir}/{pretty_name}_Episode_{episode_number}_{language}.mp4"
|
||||
return {"completed": completed, "failed": len(failures),
|
||||
"notAttempted": len(targets) - completed - len(failures), "failures": failures}
|
||||
|
||||
# Download the episode
|
||||
print(f"Downloading episode {episode_number}...")
|
||||
download_mp4(mp4_url, output_file, label=f"Episode {episode_number} ({language})")
|
||||
print(f"Episode {episode_number} downloaded successfully!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error downloading episode {episode_number}: {e}")
|
||||
# Optional: Sleep between downloads to avoid being rate-limited
|
||||
sleep(1)
|
||||
|
||||
def parse_args():
|
||||
"""Parse command-line arguments"""
|
||||
parser = argparse.ArgumentParser(description="Download a series from Proxer.me")
|
||||
def parse_args(argv=None):
|
||||
parser = SafeArgumentParser(description="Download a series from Proxer.me")
|
||||
parser.add_argument('-i', '--id', required=True, type=str, help="The series ID on Proxer.me")
|
||||
parser.add_argument('-n', '--name', required=True, type=str, help="The pretty name of the series")
|
||||
parser.add_argument('-e', '--episodes', required=True, type=str, help="Episode range (start-end), e.g. 1-10")
|
||||
parser.add_argument('-l', '--language', required=True, choices=['engsub', 'engdub', 'gersub', 'gerdub'], help="Language of the subtitles/audio")
|
||||
parser.add_argument('-t', '--token', required=True, type=str, help="Proxer authentication token")
|
||||
parser.add_argument('-o', '--output', required=True, type=str, help="Directory to store downloaded videos")
|
||||
parser.add_argument('-l', '--language', required=True, choices=LANGUAGES, help="Language of the subtitles/audio")
|
||||
token = parser.add_mutually_exclusive_group(required=True)
|
||||
token.add_argument('-t', '--token', type=str, help="Proxer authentication token")
|
||||
token.add_argument('--token-stdin', action='store_true', help="Read the cookie from standard input instead of process arguments")
|
||||
parser.add_argument('-o', '--output', required=True, type=str, help="Existing directory to store downloaded videos")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
try:
|
||||
args = parse_args(argv)
|
||||
summary = download_series_series(args.id, args.name, args.episodes, args.language, token_from_args(args), args.output)
|
||||
except Exception as error:
|
||||
result = error_result(error)
|
||||
emit_result(result)
|
||||
return 2 if result["errorCategory"] == "validation" else 1
|
||||
status = "completed" if summary["failed"] == 0 and summary["notAttempted"] == 0 else "failed"
|
||||
result = {"version": 1, "status": status, **summary}
|
||||
if status == "failed":
|
||||
categories = [failure["errorCategory"] for failure in summary["failures"]]
|
||||
blocking = next((category for category in reversed(categories)
|
||||
if category in {"authentication", "resolution", "storage", "configuration"}), None)
|
||||
result["errorCategory"] = blocking or (categories[0] if categories else "unknown")
|
||||
result["message"] = "The series did not complete; see the episode summary."
|
||||
emit_result(result)
|
||||
return 0 if status == "completed" else 1
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Parse command-line arguments
|
||||
args = parse_args()
|
||||
|
||||
# Assuming the Proxer authentication token comes as a cookie string (name=value)
|
||||
auth_token = tuple(args.token.split("="))
|
||||
|
||||
# Call the function to download the series
|
||||
download_series_series(args.id, args.name, args.episodes, args.language, auth_token, args.output)
|
||||
sys.exit(main())
|
||||
+49
-40
@@ -1,52 +1,61 @@
|
||||
import sys
|
||||
import argparse
|
||||
from lib.proxer_utils import get_mp4_url, download_mp4, get_embed_url
|
||||
|
||||
# Protect scripts/lib/__pycache__ even when this CLI is invoked without python -B.
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
from request_validation import (
|
||||
SafeArgumentParser,
|
||||
emit_result,
|
||||
error_result,
|
||||
output_path,
|
||||
token_from_args,
|
||||
validate_auth_cookie,
|
||||
validate_watch_url,
|
||||
verify_output,
|
||||
)
|
||||
|
||||
|
||||
def download_video(url, filename, auth_token, output_dir):
|
||||
"""
|
||||
Downloads a video from Proxer and saves it to the specified directory.
|
||||
"""Run the existing stream pipeline; errors propagate to the CLI result."""
|
||||
url = validate_watch_url(url)
|
||||
auth_token = validate_auth_cookie(auth_token)
|
||||
target = output_path(output_dir, filename)
|
||||
|
||||
:param url: The URL of the Proxer video page
|
||||
:param filename: The desired filename for the downloaded video
|
||||
:param auth_token: A tuple containing (cookie_name, cookie_value) for Proxer authentication
|
||||
:param output_dir: Directory to save the downloaded video
|
||||
"""
|
||||
try:
|
||||
print(f"Fetching embed URL for video: {url}...")
|
||||
embed_url = get_embed_url(url, auth_token)
|
||||
print(f"Embed URL fetched: {embed_url}")
|
||||
# Import only after validation, leaving all protected source and bytecode intact.
|
||||
from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4
|
||||
|
||||
print(f"Fetching MP4 URL for video: {url}...")
|
||||
mp4_url = get_mp4_url(embed_url)
|
||||
print(f"MP4 URL fetched: {mp4_url}")
|
||||
print("Resolving episode...", flush=True)
|
||||
embed_url = get_embed_url(url, auth_token)
|
||||
print("Resolving media...", flush=True)
|
||||
mp4_url = get_mp4_url(embed_url)
|
||||
print("Downloading video...", flush=True)
|
||||
download_mp4(mp4_url, str(target), label=f"Downloading {filename}")
|
||||
verify_output(target)
|
||||
return target
|
||||
|
||||
# Prepare the output file path
|
||||
output_file = f"{output_dir}/{filename}.mp4"
|
||||
|
||||
# Download the video
|
||||
print(f"Downloading video {filename}...")
|
||||
download_mp4(mp4_url, output_file, label=f"Downloading {filename}")
|
||||
print(f"Video {filename} downloaded successfully!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error downloading video: {e}")
|
||||
|
||||
def parse_args():
|
||||
"""Parse command-line arguments"""
|
||||
parser = argparse.ArgumentParser(description="Download a video from Proxer.me")
|
||||
def parse_args(argv=None):
|
||||
parser = SafeArgumentParser(description="Download a video from Proxer.me")
|
||||
parser.add_argument('-u', '--url', required=True, type=str, help="URL of the Proxer video page")
|
||||
parser.add_argument('-f', '--filename', required=True, type=str, help="Filename for the downloaded video (without extension)")
|
||||
parser.add_argument('-t', '--token', required=True, type=str, help="Proxer authentication token (cookie)")
|
||||
parser.add_argument('-o', '--output', required=True, type=str, help="Directory to save the downloaded video")
|
||||
token = parser.add_mutually_exclusive_group(required=True)
|
||||
token.add_argument('-t', '--token', type=str, help="Proxer authentication token (cookie)")
|
||||
token.add_argument('--token-stdin', action='store_true', help="Read the cookie from standard input instead of process arguments")
|
||||
parser.add_argument('-o', '--output', required=True, type=str, help="Existing directory to save the downloaded video")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
try:
|
||||
args = parse_args(argv)
|
||||
download_video(args.url, args.filename, token_from_args(args), args.output)
|
||||
except Exception as error:
|
||||
result = error_result(error)
|
||||
emit_result(result)
|
||||
return 2 if result["errorCategory"] == "validation" else 1
|
||||
emit_result({"version": 1, "status": "completed"})
|
||||
return 0
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Parse command-line arguments
|
||||
args = parse_args()
|
||||
|
||||
# Assuming the Proxer authentication token comes as a cookie string (name=value)
|
||||
auth_token = tuple(args.token.split("="))
|
||||
|
||||
# Call the function to download the video
|
||||
download_video(args.url, args.filename, auth_token, args.output)
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,204 @@
|
||||
"""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)
|
||||
Reference in new issue
Block a user