-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathuniversal_downloader.py
More file actions
2342 lines (2142 loc) · 104 KB
/
Copy pathuniversal_downloader.py
File metadata and controls
2342 lines (2142 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Universal Video Downloader — yt-dlp powered
============================================
Given a performer/streamer username, probe all configured video sites to find
their profile/channel pages, enumerate videos, and download them.
Architecture
------------
[username] -> [parallel probe sites] -> [rank hits by video count]
-> [enumerate video URLs per site] -> [filter via history]
-> [download via yt-dlp + aria2c external downloader]
-> [persist history atomically]
Design principles
-----------------
- Leverage yt-dlp's 1800+ built-in extractors. No per-site anti-bot code here.
- Thread-safe, atomic JSON state (history, failed, combo counts).
- Rolling-window: re-runs pick up the next batch of new videos per performer.
- aria2c multi-segment downloads where the site supports Range requests.
- Graceful degradation: per-site failure doesn't block other sites.
- Fully configurable: enabled sites, per-site URL patterns, rate limits.
Usage
-----
python universal_downloader.py <username> # specific performer
python universal_downloader.py --all # every performer in config
python universal_downloader.py <username> --sites pornhub,xvideos
python universal_downloader.py --list-sites # show supported sites
python universal_downloader.py --save-config # write template config
python universal_downloader.py --dry-run <username> # probe only, no downloads
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import queue
import re
import shutil
import string
import subprocess
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, asdict, field
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
from typing import Optional, List, Dict, Any, Iterable
if sys.platform == "win32":
import io
if not isinstance(sys.stdout, io.TextIOWrapper) or sys.stdout.encoding != "utf-8":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
if not isinstance(sys.stderr, io.TextIOWrapper) or sys.stderr.encoding != "utf-8":
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
try:
import yt_dlp
except ImportError:
print("ERROR: yt-dlp is not installed. Run: pip install -U \"yt-dlp[default,curl-cffi]\"")
sys.exit(1)
def _is_404_playlist(title: str, url: str) -> bool:
"""Heuristic: did our probe/enumerate land on a site-wide 404 page?
Motherless (notably) returns a 404 HTML page for nonexistent uploader
URLs, BUT yt-dlp's MotherlessUploader extractor still parses it and
extracts "popular / related" thumbnails displayed on that page. The
extractor reports the playlist title as "404 | MOTHERLESS.COM ™" (or
similar) while yielding videos that aren't associated with the
requested user. Downloading these pollutes the performer folder
with unrelated content.
We detect this by checking whether the page title starts with "404"
or contains obvious error-page markers. Returns True if this looks
like a 404 page we should skip.
"""
if not title:
return False
t_lower = title.strip().lower()
# Title starts with "404" (most common)
if t_lower.startswith("404"):
return True
# Title is exactly "Not Found" or "Page Not Found" / similar
for marker in ("page not found", "not found - ", "404 not found",
"error 404", " - 404"):
if marker in t_lower:
return True
# Very short title in a context where the URL is a user-page pattern
# could also indicate empty/error state; keep conservative and require
# explicit 404 markers so legit pages aren't rejected.
return False
def _is_cross_host_redirect(probed_url: str, info: dict) -> tuple[bool, str]:
"""Detect when yt-dlp's generic extractor "fell back" from a 404 onto
a completely different site's homepage.
Real-world case: `camwhores.tv/models/{u}/` returns HTTP 404. The generic
extractor's fallback parses the 404 HTML, finds youporn.com links
(ads on the page), follows the redirect, lands on `https://www.youporn.com/`
homepage, and YouPornVideos extractor dutifully enumerates the ENTIRE
trending videos catalog — hundreds of pages of off-topic content.
We detect this by comparing hostnames:
- probed_url: e.g. `https://camwhores.tv/models/alice/`
- info.webpage_url: e.g. `https://www.youporn.com/`
If the eTLD+1 of the final page differs from the probed URL, reject.
Returns (is_cross_host, reason).
"""
if not info:
return False, ""
final_url = str(info.get("webpage_url") or info.get("url") or "")
if not final_url:
return False, ""
try:
from urllib.parse import urlparse
probed_host = (urlparse(probed_url).hostname or "").lower()
final_host = (urlparse(final_url).hostname or "").lower()
except Exception:
return False, ""
if not probed_host or not final_host:
return False, ""
# Strip www./m. prefixes
def _base(h: str) -> str:
for pfx in ("www.", "m.", "en.", "beta."):
if h.startswith(pfx):
h = h[len(pfx):]
# Strip leading subdomain like "a.", "b1." — compare eTLD+1ish
parts = h.split(".")
return ".".join(parts[-2:]) if len(parts) >= 2 else h
if _base(probed_host) != _base(final_host):
return True, f"probed {probed_host!r} → final {final_host!r}"
return False, ""
# Custom scrapers for cam archive sites not supported by yt-dlp
import custom_scrapers
from custom_scrapers import (
load_scrapers as _load_custom_scrapers,
username_variants as _username_variants,
SiteScraper as _CustomSiteScraper,
)
# Shared live-progress tracker (writes downloads/_progress.json for the UI).
from progress_tracker import ProgressTracker, make_yt_dlp_hook
from site_health import SiteHealth, record_run_outcomes
try:
from rich.console import Console
from rich.progress import (
Progress, SpinnerColumn, TextColumn, BarColumn,
TimeElapsedColumn, TaskProgressColumn,
)
from rich.table import Table
from rich.panel import Panel
from rich.logging import RichHandler
HAVE_RICH = True
except ImportError:
HAVE_RICH = False
SCRIPT_DIR = Path(__file__).resolve().parent
console = Console() if HAVE_RICH else None
# ── aria2c auto-detection ─────────────────────────────────────────────────────
ARIA2C_PATH = ""
for _candidate in [
r"C:\Users\Street Coder\AppData\Local\Microsoft\WinGet\Packages\aria2.aria2_Microsoft.Winget.Source_8wekyb3d8bbwe\aria2-1.37.0-win-64bit-build1\aria2c.exe",
r"C:\ProgramData\chocolatey\bin\aria2c.exe",
shutil.which("aria2c") or "aria2c",
]:
try:
result = subprocess.run([_candidate, "--version"], capture_output=True, timeout=5)
if result.returncode == 0:
ARIA2C_PATH = _candidate
break
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
continue
# ── ffmpeg auto-detection ─────────────────────────────────────────────────────
FFMPEG_PATH = ""
for _candidate in [
r"C:\ffmpeg\bin\ffmpeg.exe",
shutil.which("ffmpeg") or "ffmpeg",
]:
try:
result = subprocess.run([_candidate, "-version"], capture_output=True, timeout=5)
if result.returncode == 0:
FFMPEG_PATH = _candidate
break
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
continue
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/131.0.0.0 Safari/537.36"
)
# ── Logging ───────────────────────────────────────────────────────────────────
def setup_logging(log_dir: Path, verbose: bool = False) -> logging.Logger:
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / "universal.log"
root = logging.getLogger()
root.setLevel(logging.DEBUG)
if HAVE_RICH:
console_handler = RichHandler(rich_tracebacks=True, show_path=False, console=console)
console_handler.setFormatter(logging.Formatter("%(message)s"))
else:
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
console_handler.setLevel(logging.DEBUG if verbose else logging.INFO)
file_handler = logging.FileHandler(str(log_file), encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
"%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
))
root.handlers.clear()
root.addHandler(console_handler)
root.addHandler(file_handler)
# Persistent ERROR log that survives downloads/ being cleared: a stable
# project-level logs/archive-errors.log, daily-rotated and kept ~14 days, so
# past errors stay readable even after the run's universal.log is gone.
try:
from logging.handlers import TimedRotatingFileHandler
_err_dir = SCRIPT_DIR / "logs"
_err_dir.mkdir(parents=True, exist_ok=True)
_err_h = TimedRotatingFileHandler(
str(_err_dir / "archive-errors.log"),
when="midnight", backupCount=14, encoding="utf-8", delay=True,
)
_err_h.setLevel(logging.ERROR)
_err_h.setFormatter(logging.Formatter(
"%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
))
root.addHandler(_err_h)
except Exception:
pass
# Silence noisy third-party loggers
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("yt_dlp").setLevel(logging.WARNING)
return logging.getLogger("universal")
# ── Data Models ───────────────────────────────────────────────────────────────
@dataclass
class SiteConfig:
name: str
category: str = "misc"
patterns: List[str] = field(default_factory=list)
yt_dlp_extractor: str = ""
supports_flat: bool = True
notes: str = ""
@dataclass
class ProbeHit:
"""A successful probe: this site has videos for this username at this URL."""
site: str
url: str
entry_count: int = 0 # from flat extraction
uploader_id: str = ""
@dataclass
class VideoRef:
"""Reference to a single video discovered on a site."""
site: str
video_id: str # site-native id (yt-dlp's `id` field)
video_url: str # canonical URL for yt-dlp to download
title: str = ""
uploader: str = ""
uploader_id: str = ""
duration: float = 0.0
performer: str = "" # the query username we used to find this
# Populated by custom scrapers (yt-dlp fills these at download time instead)
stream_url: str = ""
stream_kind: str = "" # "mp4" | "hls" | ""
stream_headers: Dict[str, str] = field(default_factory=dict)
is_custom: bool = False # True if this came from a custom scraper (not yt-dlp)
@property
def global_id(self) -> str:
"""Globally unique ID for dedup: site|video_id."""
return f"{self.site}|{self.video_id}"
@dataclass
class UniversalConfig:
output_dir: str = str(SCRIPT_DIR / "downloads")
performers: List[str] = field(default_factory=list)
enabled_sites: List[str] = field(default_factory=list) # empty = all sites from sites.json
max_videos_per_site: int = 10
min_probe_entries: int = 2 # reject probe hits with fewer than N videos (1-video hits are usually placeholders)
max_parallel_probes: int = 8
max_parallel_downloads: int = 3
min_disk_gb: float = 5.0
use_aria2c: bool = True
aria2c_connections: int = 16
rate_limit: str = "" # e.g. "500K" for 500KB/s per download
cookies_from_browser: str = "" # e.g. "chrome", "firefox"
cookies_file: str = "" # Netscape cookies.txt path
impersonate_target: str = "chrome" # curl_cffi impersonation
min_duration_seconds: float = 30.0 # skip very short clips
retries: int = 5
probe_timeout: int = 30
verbose: bool = False
# Site-specific credentials (login for camsmut etc.)
camsmut_username: str = ""
camsmut_password: str = ""
# HTTP(S)/SOCKS proxy — applied to aria2c + curl download phase when set.
# Useful when the CDN hosts used by Coomer / Kemono mirrors are IP-blocked
# by your ISP; route through a VPN or proxy. Format:
# http://user:pass@host:port
# socks5://127.0.0.1:9150 (Tor)
# http://127.0.0.1:8080 (local Squid / HTTP proxy)
download_proxy: str = ""
# Retention rules (auto-applied between runs by the webui / downloader):
# max_per_performer_gb = 0 no per-performer cap
# auto_prune_days = 0 never auto-delete by age
# These are advisory — the downloader logs warnings but never deletes
# unless the user explicitly runs the corresponding /api/disk endpoint.
max_per_performer_gb: float = 0.0
auto_prune_days: int = 0
@classmethod
def load(cls, path: Path) -> "UniversalConfig":
if not path.exists():
return cls()
with open(path, encoding="utf-8") as f:
data = json.load(f)
valid = {k: v for k, v in data.items() if k in cls.__dataclass_fields__}
return cls(**valid)
def save(self, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(asdict(self), f, indent=2, ensure_ascii=False)
# ── Atomic JSON store (reusable for history, failed, etc.) ────────────────────
class AtomicJsonStore:
"""Thread-safe JSON store with atomic writes. Handles Windows file-lock
races by retrying os.replace() and using per-thread temp file names."""
def __init__(self, path: Path):
self.path = path
self.data: dict = {}
self._lock = threading.Lock()
self._load()
def _load(self) -> None:
if self.path.exists():
try:
with open(self.path, encoding="utf-8") as f:
self.data = json.load(f)
except (json.JSONDecodeError, OSError):
self.data = {}
def save(self) -> None:
with self._lock:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp")
try:
# Merge with any concurrent disk changes to avoid overwriting them
if self.path.exists():
try:
with open(self.path, encoding="utf-8") as f:
disk = json.load(f)
self._merge_disk(disk)
except (json.JSONDecodeError, OSError):
pass
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=2, ensure_ascii=False, sort_keys=True)
for attempt in range(6):
try:
os.replace(tmp, self.path)
break
except PermissionError:
if attempt == 5:
raise
time.sleep(0.1 * (attempt + 1))
except Exception:
try:
tmp.unlink(missing_ok=True)
except Exception:
pass
raise
def _merge_disk(self, disk: dict) -> None:
"""Merge disk state into self.data. Override for domain-specific merge."""
for k, v in disk.items():
if k not in self.data:
self.data[k] = v
class DownloadHistory(AtomicJsonStore):
"""Tracks downloaded videos, keyed by (performer, global_id).
Schema:
{
"performer_lower": {
"site|video_id": {
"title": "...", "url": "...", "output": "...",
"date": "...", "filesize": N, "duration": N, ...
}
}
}
"""
def _merge_disk(self, disk: dict) -> None:
# Nested merge: performer -> global_id
for perf, entries in disk.items():
if perf not in self.data:
self.data[perf] = entries
else:
for gid, info in entries.items():
if gid not in self.data[perf]:
self.data[perf][gid] = info
def is_downloaded(self, performer: str, global_id: str) -> bool:
return global_id in self.data.get(performer.lower(), {})
def mark_downloaded(self, video: VideoRef, output_path: str = "", filesize: int = 0) -> None:
with self._lock:
key = video.performer.lower()
if key not in self.data:
self.data[key] = {}
self.data[key][video.global_id] = {
"site": video.site,
"video_id": video.video_id,
"url": video.video_url,
"title": video.title,
"output": output_path,
"filesize": filesize,
"duration": video.duration,
"date": datetime.now().isoformat(timespec="seconds"),
}
self.save()
def count(self, performer: str = "") -> int:
if performer:
return len(self.data.get(performer.lower(), {}))
return sum(len(v) for v in self.data.values())
class FailedHistory(AtomicJsonStore):
"""Tracks failed downloads. Permanent flag only for confirmed dead links."""
MAX_FAILURES = 3
def _merge_disk(self, disk: dict) -> None:
for k, v in disk.items():
if k not in self.data:
self.data[k] = v
def is_permanently_failed(self, global_id: str) -> bool:
e = self.data.get(global_id)
return e is not None and e.get("permanent", False)
def record_failure(self, video: VideoRef, reason: str, file_size: int = 0) -> bool:
with self._lock:
entry = self.data.get(video.global_id, {"fail_count": 0, "sizes": []})
entry["fail_count"] = entry.get("fail_count", 0) + 1
entry["reason"] = reason
entry["date"] = datetime.now().isoformat(timespec="seconds")
entry["site"] = video.site
entry["url"] = video.video_url
sizes = entry.get("sizes", [])
if file_size > 0:
sizes.append(file_size)
entry["sizes"] = sizes[-5:]
if entry["fail_count"] >= self.MAX_FAILURES:
rlow = reason.lower()
if ("404" in rlow or "dead" in rlow or "not found" in rlow
or "deleted" in rlow or "private" in rlow
or "members-only" in rlow):
entry["permanent"] = True
elif file_size > 0 and len(sizes) >= 2 and all(abs(s - sizes[0]) < 100_000 for s in sizes):
entry["permanent"] = True
self.data[video.global_id] = entry
self.save()
return entry.get("permanent", False)
# ── Site registry ─────────────────────────────────────────────────────────────
class SiteRegistry:
"""Loads the list of supported sites and their URL patterns from sites.json."""
def __init__(self, sites_path: Path, log: logging.Logger):
self.log = log
self.sites: Dict[str, SiteConfig] = {}
self._load(sites_path)
def _load(self, path: Path) -> None:
if not path.exists():
self.log.error(f"sites.json not found at {path}")
return
with open(path, encoding="utf-8") as f:
data = json.load(f)
skipped = []
for name, info in data.get("sites", {}).items():
# Names starting with underscore are disabled
if name.startswith("_"):
skipped.append(name)
continue
self.sites[name] = SiteConfig(
name=name,
category=info.get("category", "misc"),
patterns=info.get("patterns", []),
yt_dlp_extractor=info.get("yt_dlp_extractor", ""),
supports_flat=info.get("supports_flat", True),
notes=info.get("notes", ""),
)
msg = f"Loaded {len(self.sites)} site definitions"
if skipped:
msg += f" ({len(skipped)} disabled: {', '.join(s.lstrip('_') for s in skipped)})"
self.log.info(msg)
def enabled(self, names: List[str]) -> List[SiteConfig]:
if not names:
return list(self.sites.values())
return [self.sites[n] for n in names if n in self.sites]
def by_category(self, category: str) -> List[SiteConfig]:
return [s for s in self.sites.values() if s.category == category]
# ── yt-dlp wrapper ────────────────────────────────────────────────────────────
class _QuietYtdlpLogger:
"""yt-dlp logger adapter. Routes yt-dlp's own messages to our file log
only (suppressed on console) so per-extractor 404s and 'Unsupported URL'
don't flood the terminal while we're probing dozens of sites."""
def __init__(self, target: logging.Logger):
self._log = target
def debug(self, msg):
# yt-dlp uses debug() for both real debug and verbose stdout; filter noise
if msg.startswith("[debug] "):
self._log.debug(msg)
else:
self._log.debug(msg)
def info(self, msg):
self._log.debug(msg) # demote info to debug
def warning(self, msg):
self._log.debug(msg) # also demote: most yt-dlp warnings are per-URL noise
def error(self, msg):
self._log.debug(msg) # extractor errors on bad URLs; keep in file only
class YtdlpEngine:
"""Thin wrapper around yt-dlp's Python API. Builds YoutubeDL instances with
consistent options for probing, enumeration, and downloading."""
def __init__(self, config: UniversalConfig, log: logging.Logger):
self.config = config
self.log = log
self._ytdlp_logger = _QuietYtdlpLogger(logging.getLogger("yt_dlp_silent"))
def _common_opts(self) -> dict:
opts = {
"quiet": True,
"no_warnings": True,
"verbose": False,
"ignoreerrors": True,
"noplaylist": False,
"retries": self.config.retries,
"fragment_retries": self.config.retries,
"file_access_retries": 3,
"extractor_retries": self.config.retries,
"socket_timeout": self.config.probe_timeout,
"http_headers": {"User-Agent": USER_AGENT},
"sleep_interval_requests": 1,
"sleep_interval": 1,
"max_sleep_interval": 3,
"logger": self._ytdlp_logger,
"consoletitle": False,
}
if self.config.cookies_from_browser:
opts["cookiesfrombrowser"] = (self.config.cookies_from_browser,)
if self.config.cookies_file:
opts["cookiefile"] = self.config.cookies_file
# curl_cffi impersonation if available (helps with Cloudflare)
if self.config.impersonate_target:
try:
from yt_dlp.networking.impersonate import ImpersonateTarget
opts["impersonate"] = ImpersonateTarget(self.config.impersonate_target)
except (ImportError, AttributeError):
pass
return opts
def probe(self, url: str) -> Optional[dict]:
"""Fast probe: returns playlist metadata with flat entries, or None.
Uses aggressively-tight retry/timeout settings — probes should fail fast
on non-existent users. Many probes fail with 404 / Unsupported URL;
these are expected and routed to the debug log, not console."""
opts = self._common_opts()
opts.update({
"extract_flat": "in_playlist",
"skip_download": True,
# Low cap — we just need existence, not an accurate count.
# Some extractors (e.g. YouPorn) enumerate the whole site when the
# user doesn't exist. Keep this tight.
"playlistend": 25,
"lazy_playlist": True,
# Probe-specific: fail fast. Each URL should take <= 5s on 404.
"retries": 0,
"extractor_retries": 0,
"fragment_retries": 0,
"socket_timeout": 10,
"sleep_interval_requests": 0,
"sleep_interval": 0,
"max_sleep_interval": 0,
})
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
if not info:
return None
info = ydl.sanitize_info(info)
# Reject probes that landed on site-wide 404 pages: some
# extractors (notably Motherless) will dutifully scrape
# "popular/related" thumbnails off a 404 error page and
# report them as if they were the user's uploads.
title = str(info.get("title", ""))
if _is_404_playlist(title, url):
self.log.debug(f"Probe rejected: landed on 404 page — {url} "
f"(title: {title!r})")
return None
# Reject probes that redirected across hosts. e.g. camwhores.tv
# 404 → generic fallback finds youporn.com link in the page →
# follows to https://www.youporn.com/ → YouPornVideos
# extractor enumerates the whole site.
cross, why = _is_cross_host_redirect(url, info)
if cross:
self.log.debug(f"Probe rejected: cross-host redirect ({why})")
return None
return info
except yt_dlp.utils.DownloadError as e:
self.log.debug(f"Probe failed for {url}: {e}")
return None
except Exception as e:
self.log.debug(f"Probe error for {url}: {type(e).__name__}: {e}")
return None
def enumerate_videos(self, url: str, limit: int = 0, site_hint: str = "") -> List[VideoRef]:
"""Return flat list of VideoRef from a user/channel/playlist URL.
site_hint: the site name from sites.json, used when extractor_key is empty."""
opts = self._common_opts()
opts.update({
"extract_flat": "in_playlist",
"skip_download": True,
"lazy_playlist": True,
})
if limit:
opts["playlistend"] = limit
videos: List[VideoRef] = []
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
if not info:
return []
info = ydl.sanitize_info(info)
# Same guard as in probe(): if the site returned a 404 page
# and the extractor happily scraped "related/popular" videos
# off it, those videos don't belong to the requested user.
title = str(info.get("title", ""))
if _is_404_playlist(title, url):
self.log.warning(
f"Enumerate rejected: landed on 404 page — {url} "
f"(title: {title!r}). Would have yielded unrelated content."
)
return []
# Cross-host redirect guard: e.g. camwhores.tv → youporn.com
# (see _is_cross_host_redirect for context).
cross, why = _is_cross_host_redirect(url, info)
if cross:
self.log.warning(
f"Enumerate rejected: cross-host redirect ({why}). "
f"Would have yielded unrelated content."
)
return []
entries = info.get("entries") or [info]
default_site = site_hint or info.get("extractor_key", "").lower() or "unknown"
for e in entries:
if not e:
continue
vid = e.get("id") or ""
vurl = e.get("url") or e.get("webpage_url") or ""
if not vid:
continue
# If URL is missing, reconstruct from ie_key + id
if not vurl:
vurl = e.get("original_url") or ""
if not vurl:
continue
# Prefer ie_key (yt-dlp's extractor identifier) over our hint
site = (e.get("ie_key") or e.get("extractor_key") or "").lower()
if not site or site == "generic":
site = default_site
videos.append(VideoRef(
site=site,
video_id=vid,
video_url=vurl,
title=e.get("title") or vid,
uploader=e.get("uploader", "") or "",
uploader_id=e.get("uploader_id", "") or "",
duration=e.get("duration") or 0.0,
))
except Exception as e:
self.log.warning(f"Enumeration failed for {url}: {e}")
return videos
def _download_opts(self, performer: str, output_dir: Path) -> dict:
"""Build opts for the actual download phase."""
opts = self._common_opts()
opts.update({
"skip_download": False,
"outtmpl": str(output_dir / performer / "%(extractor)s-%(id)s-%(title).100B.%(ext)s"),
"writeinfojson": False,
"writethumbnail": False,
"continuedl": True,
"overwrites": False,
"nopart": False,
"concurrent_fragment_downloads": 8, # HLS/DASH fragments
})
if self.config.rate_limit:
opts["ratelimit"] = self._parse_rate(self.config.rate_limit)
if self.config.min_duration_seconds:
from yt_dlp.utils import match_filter_func
# "?" marks field as optional — videos with unknown duration pass
opts["match_filter"] = match_filter_func(
f"duration >=? {self.config.min_duration_seconds}"
)
# aria2c external downloader — best for direct HTTP (mp4).
# Let yt-dlp handle HLS/DASH natively with concurrent fragments.
if self.config.use_aria2c and ARIA2C_PATH:
opts["external_downloader"] = {"default": ARIA2C_PATH}
opts["external_downloader_args"] = {
"default": [
"-x", str(self.config.aria2c_connections),
"-s", str(self.config.aria2c_connections),
"-k", "1M",
"--max-tries=3",
"--retry-wait=3",
"--connect-timeout=30",
"--timeout=60",
"--file-allocation=none",
"--allow-overwrite=true",
"--auto-file-renaming=false",
"--console-log-level=error",
"--summary-interval=0",
],
}
# ffmpeg path for HLS/DASH merging + post-processing
if FFMPEG_PATH:
opts["ffmpeg_location"] = str(Path(FFMPEG_PATH).parent)
return opts
def download(self, video: VideoRef, output_dir: Path,
progress_hook=None, extra_opts: Optional[dict] = None) -> Optional[dict]:
"""Download one video. Returns info_dict on success, None on failure.
Optional `progress_hook` is passed through to yt-dlp's `progress_hooks`
so the caller can surface byte/speed/ETA updates (UI progress bar).
`extra_opts` merges in per-URL options such as a host-specific
cookiefile."""
opts = self._download_opts(video.performer, output_dir)
if extra_opts:
opts.update(extra_opts)
if progress_hook is not None:
opts["progress_hooks"] = [progress_hook]
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(video.video_url, download=True)
if not info:
return None
return ydl.sanitize_info(info)
except yt_dlp.utils.DownloadError as e:
self.log.warning(f" {video.site}/{video.video_id}: download failed: {e}")
return None
except Exception as e:
self.log.warning(f" {video.site}/{video.video_id}: unexpected error: {e}")
return None
@staticmethod
def _parse_rate(rate: str) -> int:
"""Parse '500K' / '2M' -> bytes/sec."""
rate = rate.strip().upper()
if not rate:
return 0
multipliers = {"K": 1024, "M": 1024 * 1024, "G": 1024 * 1024 * 1024}
if rate[-1] in multipliers:
return int(float(rate[:-1]) * multipliers[rate[-1]])
return int(rate)
# ── Universal Downloader ──────────────────────────────────────────────────────
class UniversalDownloader:
def __init__(self, config: UniversalConfig, registry: SiteRegistry, log: logging.Logger):
self.config = config
self.registry = registry
self.log = log
self.output_dir = Path(config.output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.history = DownloadHistory(self.output_dir / "history.json")
self.failed = FailedHistory(self.output_dir / "failed.json")
self.engine = YtdlpEngine(config, log)
# Live progress tracker — the web UI tails downloads/_progress.json
self.progress = ProgressTracker(self.output_dir)
# Expose the progress path to the SIGTERM/SIGBREAK handler so a
# clean kill from the webui flips running:false on disk before
# the daemon threads get torn down.
try:
_progress_path_holder["path"] = str(self.progress.path)
except Exception:
pass
# Site-drift tracker — persistent per-site success/fail ledger
# so the UI can surface sites that used to work but now fail.
self.health = SiteHealth(self.output_dir)
# Custom scrapers for cam-archive sites not supported by yt-dlp.
# Pass cookies_file so sites requiring auth (Recu.me, camwhores.tv
# private videos) can access protected content.
site_credentials = {}
if config.camsmut_username and config.camsmut_password:
site_credentials["camsmut"] = {
"username": config.camsmut_username,
"password": config.camsmut_password,
}
# Respect enabled_sites for custom scrapers too. If enabled_sites is
# empty (== "all"), pass None to load every registered scraper;
# otherwise filter to the intersection.
enabled = config.enabled_sites or None
self.custom_scrapers: List[_CustomSiteScraper] = _load_custom_scrapers(
log, enabled_names=enabled, cookies_file=config.cookies_file,
site_credentials=site_credentials,
)
def check_disk_space(self) -> bool:
try:
free_gb = shutil.disk_usage(self.output_dir.resolve().anchor).free / (1024 ** 3)
except Exception:
return True
if free_gb < self.config.min_disk_gb:
self.log.error(f"DISK LOW: {free_gb:.1f} GB free (need {self.config.min_disk_gb})")
return False
return True
# ── Probe phase: find which sites have the performer ─────────────────────
def probe_all_sites(self, performer: str) -> List[ProbeHit]:
"""Probe every enabled site for this performer in parallel. For each site,
we collect ALL successful probes, then pick the best URL (highest video
count). This handles sites with multiple URL patterns like YouTube
(/videos vs /streams vs /shorts) correctly."""
sites = self.registry.enabled(self.config.enabled_sites)
jobs: List[tuple] = [] # (site_config, url, pattern_index)
for site in sites:
for idx, pattern in enumerate(site.patterns):
jobs.append((site, pattern.format(u=performer), idx))
self.log.info(f"Probing {len(jobs)} URL patterns across {len(sites)} sites for '{performer}'")
# Surface probe progress to the UI.
self.progress.set_phase("probing", f"Probing {len(sites)} sites...")
probe_counter = [0] # mutable box for inner closure
probe_lock = threading.Lock()
min_entries = max(1, self.config.min_probe_entries)
def probe_one(job):
site, url, idx = job
try:
info = self.engine.probe(url)
finally:
with probe_lock:
probe_counter[0] += 1
self.progress.note_probe(site.name, probe_counter[0], len(jobs))
if not info:
return None
entries = info.get("entries") or []
entries_list = list(entries) if entries else []
# Reject hits with fewer entries than threshold — most tube sites
# return a 1-video "placeholder" for non-existent users (usually a
# search-first-result or the site's promo video).
if len(entries_list) < min_entries:
return None
return (site.name, idx, ProbeHit(
site=site.name,
url=url,
entry_count=len(entries_list),
uploader_id=info.get("uploader_id", "") or info.get("id", ""),
))
# Collect ALL successful hits per site, then pick best one per site.
# Hard wall-clock cap on the whole probe phase so we never hang.
# Use explicit non-waiting shutdown: already-running probe threads
# that are stuck in sockets become daemon threads and die with the
# process — we don't block on them.
per_site: Dict[str, List[tuple]] = {} # site_name -> [(idx, ProbeHit), ...]
max_probe_seconds = self.config.probe_timeout
# Use daemon threads so stuck workers die with the process
import concurrent.futures as _cf
pool = _cf.ThreadPoolExecutor(
max_workers=self.config.max_parallel_probes,
thread_name_prefix="probe",
)
# Mark workers as daemon so they don't prevent interpreter shutdown.
# (Patch the pool's thread factory before first submit.)
_orig_adjust = pool._adjust_thread_count
def _daemonize_workers():
_orig_adjust()
for t in pool._threads:
if not t.daemon:
try:
t.daemon = True
except RuntimeError:
pass
pool._adjust_thread_count = _daemonize_workers
try:
futs = {pool.submit(probe_one, j): j for j in jobs}
try:
for f in _cf.as_completed(futs, timeout=max_probe_seconds):
try:
r = f.result()
except Exception as e:
self.log.debug(f"Probe exception: {e}")
continue
if not r:
continue
site_name, idx, hit = r
per_site.setdefault(site_name, []).append((idx, hit))
except _cf.TimeoutError:
pending = sum(1 for f in futs if not f.done())
self.log.warning(f"Probe phase timed out after {max_probe_seconds}s "
f"({pending} of {len(jobs)} probes still pending)")
finally:
# Don't wait for stuck probes — they're daemon threads.
pool.shutdown(wait=False, cancel_futures=True)
# For each site, pick the best hit: first by entry_count, then by pattern order
# (pattern order = user's preference in sites.json)
hits: List[ProbeHit] = []
for site_name, candidates in per_site.items():
# Sort by (-entry_count, idx) so higher count wins, tie broken by pattern order
candidates.sort(key=lambda t: (-t[1].entry_count, t[0]))
best = candidates[0][1]
hits.append(best)
self.progress.note_hit(best.site, best.entry_count, url=best.url)
self.log.info(f" HIT: {best.site} ({best.entry_count} videos) @ {best.url}")
if len(candidates) > 1:
others = [f"{c[1].url[:60]} ({c[1].entry_count})" for c in candidates[1:]]
self.log.debug(f" (also saw: {', '.join(others)})")
hits.sort(key=lambda h: -h.entry_count)
return hits
# ── Custom scraper probe (parallel to yt-dlp probe) ──────────────────────
def probe_custom_scrapers(self, performer: str) -> List[tuple]:
"""Probe all custom scrapers (with spelling variants). Returns
list of (scraper, ProbeHit, variant_used) tuples, best hit per scraper."""
variants = _username_variants(performer)
self.log.info(f"Probing {len(self.custom_scrapers)} custom scrapers "
f"with {len(variants)} variants")
jobs = [] # (scraper, variant)
for scraper in self.custom_scrapers:
for v in variants:
jobs.append((scraper, v))
# Track custom-scraper probe progress alongside yt-dlp's so the UI
# reflects the full probe pipeline.
cp_counter = [0]
cp_lock = threading.Lock()
total_probes = self.progress.session.get("probe_total", 0) + len(jobs)
base_done = self.progress.session.get("probe_done", 0)
with cp_lock:
self.progress.set_phase("probing", f"Probing {len(self.custom_scrapers)} custom scrapers...")
self.progress.note_probe("", base_done, total_probes)
def _probe(job):