Files
Downloader-Bot/services/download/worker_cli.py
Mak5erandClaude Fable 5 caffc343af refactor: apply full-project audit — bug fixes, performance, deduplication
Full-codebase audit (149 raw findings, 57 verified and applied).

Fixes:
- download resume: recompute Range header per retry attempt; never resume
  preallocated multipart .part files (silent media corruption)
- inline sends: canonical error tail (rate-limit/queue-busy/timeout/failure)
  for all platforms; YouTube inline no longer strands tokens in
  'processing' for 6h
- admin mailing: exclude banned users; fix Telegram error-text matching
- middlewares: instantiate once and share across message/callback/inline
  so antiflood/ban state no longer fragments
- event loop: move ZIP compression, JSON state persistence, admin FS
  walks, PIL/ffmpeg/ffprobe work off the loop
- download queue: prune idle per-user scopes; cancelled leader releases
  joined duplicate requests
- worker subprocess: disable log sinks (stderr error protocol and log
  rotation no longer race the parent)
- third-party loggers route through app handlers instead of lastResort
- tiktok: fix mojibake reaction emoji; per-user settings in doc callback;
  per-URL locks for short-URL expansion; parallel photo-set downloads
- ci: fix broken yt-dlp auto-bump workflow baseline
- db: drop redundant analytics_events indexes (migration 000010)

Refactoring:
- services/inline/send_flow.py: shared inline delivery flow for all five
  platforms (~640 duplicated lines removed)
- services/media/audio_flow.py: shared MP3 pipeline (was duplicated 6x
  across youtube/youtube_inline/soundcloud/spotify)
- CobaltMediaService base + shared Cobalt response parsing
- services/platforms/ytdlp_helpers.py: shared yt-dlp scaffolding
- register_inline_send_handlers: one chosen_inline_result/callback
  registration factory for 8 handlers
- merge pinterest/threads single-media and media-group flows
- logging decorator factory; remove ~11 dead repository methods

Tests: 470 -> 518 passing, coverage 77.3% -> 80.9% (CI gate 74%).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 16:25:59 +03:00

59 lines
1.8 KiB
Python

from __future__ import annotations
import json
import sys
from dataclasses import asdict
from services.logger import disable_log_sinks
from utils.download_manager import DownloadConfig, ResilientDownloader
def _read_payload() -> dict:
raw = sys.stdin.buffer.read()
if not raw:
raise ValueError("No payload provided to download worker.")
return json.loads(raw.decode("utf-8"))
def _build_config(raw: dict) -> DownloadConfig:
config_data = dict(raw or {})
stream_timeout = config_data.get("stream_timeout")
if isinstance(stream_timeout, list):
config_data["stream_timeout"] = tuple(stream_timeout)
return DownloadConfig(**config_data)
def main() -> int:
# The parent process raises this worker's entire stderr as the download
# error message and shares its log files, so drop every log sink first:
# stderr must carry only the final exception text, and a second process
# must not write/rotate the parent's rotating log files.
disable_log_sinks()
try:
payload = _read_payload()
config = _build_config(payload.get("config") or {})
downloader = ResilientDownloader(
output_dir=payload["output_dir"],
config=config,
source=payload.get("source", "worker"),
)
metrics = downloader._download_sync(
payload["url"],
payload["filename"],
payload.get("headers") or {},
bool(payload.get("skip_if_exists", False)),
None,
int(payload.get("max_size_bytes") or 0) or None,
)
sys.stdout.write(json.dumps(asdict(metrics)))
sys.stdout.flush()
return 0
except Exception as exc:
sys.stderr.write(str(exc))
sys.stderr.flush()
return 1
if __name__ == "__main__":
raise SystemExit(main())