-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscrape.py
executable file
·2286 lines (1980 loc) · 89.5 KB
/
scrape.py
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
import argparse
import yaml
import art
import requests
import cloudscraper
from bs4 import BeautifulSoup
import os
import tempfile
import subprocess
import time
import re
import sys
import urllib.parse
from urllib.parse import urlparse
from smb.SMBConnection import SMBConnection
from datetime import datetime
import random
import io
import shlex
import json
import pwd
import grp
import shutil
import shlex
import json
import uuid
from loguru import logger
from tqdm import tqdm
from termcolor import colored
import textwrap
from rich.console import Console
from rich.table import Table
from rich.style import Style
from rich.text import Text
SELENIUM_AVAILABLE = True
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
except:
SELENIUM_AVAILABLE = False
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
SITE_DIR = os.path.join(SCRIPT_DIR, 'sites')
STATE_FILE = os.path.join(SCRIPT_DIR, '.state')
last_vpn_action_time = 0
session = requests.Session()
console = Console()
class ProgressFile:
"""A file-like wrapper to track progress during SMB upload."""
def __init__(self, file_obj, progress_bar):
self.file_obj = file_obj
self.pbar = progress_bar
self.total_size = os.fstat(file_obj.fileno()).st_size
def read(self, size=-1):
data = self.file_obj.read(size)
if data:
self.pbar.update(len(data))
return data
def __getattr__(self, name):
return getattr(self.file_obj, name)
def load_state():
"""Load processed video URLs from .state file into a set."""
if not os.path.exists(STATE_FILE):
return set()
try:
with open(STATE_FILE, 'r', encoding='utf-8') as f:
return set(line.strip() for line in f if line.strip())
except Exception as e:
logger.error(f"Failed to load state file '{STATE_FILE}': {e}")
return set()
def save_state(url):
"""Append a single URL to the end of the .state file."""
try:
with open(STATE_FILE, 'a', encoding='utf-8') as f:
f.write(f"{url}\n")
logger.debug(f"Appended URL to state: {url}")
except Exception as e:
logger.error(f"Failed to append to state file '{STATE_FILE}': {e}")
def is_url_processed(url, state_set):
"""Check if a URL is in the state set."""
return url in state_set
def load_configuration(config_type='general', identifier=None):
"""Load general or site-specific configuration."""
if config_type == 'general':
config_path = os.path.join(SCRIPT_DIR, 'config.yaml')
try:
with open(config_path, 'r') as file:
return yaml.safe_load(file)
except Exception as e:
logger.error(f"Failed to load general config from '{config_path}': {e}")
raise
elif config_type == 'site':
if not identifier:
raise ValueError("Site identifier required for site config loading")
identifier_lower = identifier.lower()
for config_file in os.listdir(SITE_DIR):
if config_file.endswith('.yaml'):
config_path = os.path.join(SITE_DIR, config_file)
try:
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
if any(config.get(key, '').lower() == identifier_lower
for key in ['shortcode', 'name', 'domain']):
logger.debug(f"Loaded site config for '{identifier}' from '{config_file}'")
return config
except Exception as e:
logger.warning(f"Failed to load config '{config_file}': {e}")
logger.error(f"No site config found for '{identifier}'")
return None
raise ValueError(f"Unknown config type: {config_type}")
def process_title(title, invalid_chars):
logger.debug(f"Processing {title} for invalid chars...")
for char in invalid_chars:
title = title.replace(char, "")
return title
def construct_filename(title, site_config, general_config):
prefix = site_config.get('name_prefix', '')
suffix = site_config.get('name_suffix', '')
extension = general_config['file_naming']['extension']
invalid_chars = general_config['file_naming']['invalid_chars']
max_chars = general_config['file_naming'].get('max_chars', 255) # Default to 255 if not specified
# Process title by removing invalid characters
processed_title = process_title(title, invalid_chars)
# Calculate available length for the title
fixed_length = len(prefix) + len(suffix) + len(extension)
max_title_chars = min(max_chars, 255) - fixed_length # Hard cap at 255 chars total
if max_title_chars <= 0:
logger.warning(f"Fixed filename parts ({fixed_length} chars) exceed max_chars ({max_chars}); truncating to fit.")
max_title_chars = max(1, 255 - fixed_length) # Ensure at least 1 char for title if possible
# Truncate title if necessary
if len(processed_title) > max_title_chars:
processed_title = processed_title[:max_title_chars].rstrip()
logger.debug(f"Truncated title to {max_title_chars} chars: {processed_title}")
# Construct final filename
filename = f"{prefix}{processed_title}{suffix}{extension}"
# Double-check byte length (Linux limit is 255 bytes, not chars)
while len(filename.encode('utf-8')) > 255:
excess = len(filename.encode('utf-8')) - 255
trim_chars = excess // 4 + 1 # Rough estimate for UTF-8; adjust conservatively
processed_title = processed_title[:-trim_chars].rstrip()
filename = f"{prefix}{processed_title}{suffix}{extension}"
logger.debug(f"Filename exceeded 255 bytes; trimmed to: {filename}")
return filename
def construct_url(base_url, pattern, site_config, mode=None, **kwargs):
encoding_rules = (
site_config['modes'][mode]['url_encoding_rules']
if mode and mode in site_config['modes'] and 'url_encoding_rules' in site_config['modes'][mode]
else site_config.get('url_encoding_rules', {})
)
encoded_kwargs = {}
logger.debug(f"Constructing URL with pattern '{pattern}' and mode '{mode}' using encoding rules: {encoding_rules}")
# Handle arithmetic expressions like {page - 1}, {page + 2}, etc.
page_pattern = r'\{page\s*([+-])\s*(\d+)\}' # Matches {page - 1}, {page + 2}, etc.
match = re.search(page_pattern, pattern)
if match and 'page' in kwargs:
operator, value = match.group(1), int(match.group(2))
page_value = kwargs.get('page')
if page_value is not None:
try:
page_num = int(page_value)
if operator == '+':
adjusted_page = page_num + value
elif operator == '-':
adjusted_page = page_num - value
# Replace the full expression (e.g., "{page - 1}") with the computed value
pattern = pattern.replace(match.group(0), str(adjusted_page))
logger.debug(f"Adjusted page {page_value} {operator} {value} = {adjusted_page}")
except (ValueError, TypeError):
logger.error(f"Invalid page value '{page_value}' for arithmetic adjustment")
pattern = pattern.replace(match.group(0), str(page_value)) # Fallback to original
else:
pattern = pattern.replace(match.group(0), '') # Remove if page is None
elif 'page' in kwargs:
encoded_kwargs['page'] = kwargs['page'] # Regular page handling if no arithmetic
# Encode remaining kwargs with rules
for k, v in kwargs.items():
if k == 'page' and match: # Skip page if already handled by arithmetic
continue
if isinstance(v, str):
encoded_v = v
for original, replacement in encoding_rules.items():
encoded_v = encoded_v.replace(original, replacement)
encoded_kwargs[k] = encoded_v
else:
encoded_kwargs[k] = v
# Format the pattern with encoded kwargs, handling missing keys gracefully
try:
path = pattern.format(**encoded_kwargs)
except KeyError as e:
logger.error(f"Missing key in URL pattern '{pattern}': {e}")
return None
full_url = urllib.parse.urljoin(base_url, path)
logger.debug(f"Constructed URL: {full_url}")
return full_url
def get_selenium_driver(general_config, force_new=False):
selenium_config = general_config.get('selenium', {})
chromedriver_path = selenium_config.get('chromedriver_path') # None if not specified
create_new = force_new or 'selenium_driver' not in general_config
if not create_new:
try:
driver = general_config['selenium_driver']
driver.current_url # Test if the driver is still valid
except Exception as e:
logger.warning(f"Existing Selenium driver invalid: {e}")
create_new = True
if create_new:
if 'selenium_driver' in general_config:
try:
general_config['selenium_driver'].quit()
except:
pass
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
chrome_binary = selenium_config.get('chrome_binary')
if chrome_binary:
chrome_options.binary_location = chrome_binary
logger.debug(f"Set Chrome binary location to: {chrome_binary}")
try:
if chromedriver_path:
# Use user-specified ChromeDriver path
logger.debug(f"Using user-specified ChromeDriver at: {chromedriver_path}")
service = Service(executable_path=chromedriver_path)
else:
# Fallback to webdriver_manager
logger.debug("No chromedriver_path specified; using webdriver_manager to fetch ChromeDriver")
service = Service(ChromeDriverManager().install())
logger.debug(f"Using ChromeDriver at: {service.path}")
driver = webdriver.Chrome(service=service, options=chrome_options)
logger.debug(f"Initialized Selenium driver with Chrome version: {driver.capabilities['browserVersion']}")
except Exception as e:
logger.error(f"Failed to initialize Selenium driver: {e}")
return None
driver.execute_script("""
(function() {
let open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
if (url.includes(".m3u8")) {
console.log("🔥 Found M3U8 via XHR:", url);
}
return open.apply(this, arguments);
};
})();
""")
general_config['selenium_driver'] = driver
# Store User-Agent for later use
user_agent = driver.execute_script("return navigator.userAgent;")
general_config['selenium_user_agent'] = user_agent
logger.debug(f"Selenium User-Agent: {user_agent}")
return general_config['selenium_driver']
def process_url(url, site_config, general_config, overwrite, re_nfo, start_page, apply_state=False, state_set=None):
headers = general_config.get("headers", {}).copy()
headers["User-Agent"] = random.choice(general_config["user_agents"])
mode, scraper = match_url_to_mode(url, site_config)
# Split start_page into page_num and video_offset
page_parts = start_page.split('.')
page_num = int(page_parts[0])
video_offset = int(page_parts[1]) if len(page_parts) > 1 else 0
if mode:
logger.info(f"Matched URL to mode '{mode}' with scraper '{scraper}'")
if mode == "video":
success = process_video_page(url, site_config, general_config, overwrite, headers, re_nfo, apply_state=apply_state, state_set=state_set)
else:
identifier = url.split("/")[-1].split(".")[0]
current_page_num = page_num
current_video_offset = video_offset
mode_config = site_config["modes"][mode]
if page_num > 1 and mode_config.get("url_pattern_pages"):
url = construct_url(
site_config["base_url"],
mode_config["url_pattern_pages"],
site_config,
mode=mode,
**{mode: identifier, "page": page_num}
)
logger.info(f"Starting at custom page {page_num}.{video_offset}: {url}")
elif page_num == 1:
url = construct_url(
site_config["base_url"],
mode_config["url_pattern"],
site_config,
mode=mode,
**{mode: identifier}
)
success = False
while url:
next_page, new_page_number, page_success = process_list_page(
url, site_config, general_config, current_page_num, current_video_offset,
mode, identifier, overwrite, headers, re_nfo, apply_state=apply_state, state_set=state_set
)
success = success or page_success
url = next_page
current_page_num = new_page_number
current_video_offset = 0 # Reset after first page
time.sleep(general_config["sleep"]["between_pages"])
else:
logger.warning("URL didn't match any specific mode; attempting all configured modes.")
available_modes = site_config.get("modes", {})
success = False
for mode_name in available_modes:
if mode_name == "video":
logger.info("Trying 'video' mode...")
success = process_video_page(url, site_config, general_config, overwrite, headers, re_nfo, apply_state=apply_state, state_set=state_set)
if success:
logger.info("Video mode succeeded.")
break
else:
logger.info(f"Attempting mode '{mode_name}'...")
identifier = url.split("/")[-1].split(".")[0]
current_page_num = page_num
current_video_offset = video_offset
mode_config = site_config["modes"][mode_name]
if mode_config.get("url_pattern"):
try:
constructed_url = construct_url(
site_config["base_url"],
mode_config["url_pattern"] if current_page_num == 1 else mode_config.get("url_pattern_pages", mode_config["url_pattern"]),
site_config,
mode=mode_name,
**{mode_name: identifier, "page": current_page_num if current_page_num > 1 else None}
)
logger.info(f"Starting at custom page {current_page_num}.{current_video_offset}: {constructed_url}")
success = False
while constructed_url:
next_page, new_page_number, page_success = process_list_page(
constructed_url, site_config, general_config, current_page_num, current_video_offset,
mode_name, identifier, overwrite, headers, re_nfo, apply_state=apply_state, state_set=state_set
)
success = success or page_success
constructed_url = next_page
current_page_num = new_page_number
current_video_offset = 0 # Reset after first page
time.sleep(general_config["sleep"]["between_pages"])
if success:
logger.info(f"Mode '{mode_name}' succeeded.")
break
except Exception as e:
logger.debug(f"Mode '{mode_name}' failed: {e}")
continue
if not success:
logger.error(f"Failed to process URL '{url}' with any mode.")
process_fallback_download(url, general_config, overwrite)
return success
def process_list_page(url, site_config, general_config, page_num=1, video_offset=0, mode=None, identifier=None, overwrite=False, headers=None, new_nfo=False, do_not_ignore=False, apply_state=False, state_set=None):
use_selenium = site_config.get('use_selenium', False)
driver = get_selenium_driver(general_config) if use_selenium else None
soup = fetch_page(url, general_config['user_agents'], headers if headers else {}, use_selenium, driver)
if soup is None:
logger.error(f"Failed to fetch page: {url}")
return None, None, False
list_scraper = site_config['scrapers']['list_scraper']
base_url = site_config['base_url']
container_selector = list_scraper['video_container']['selector']
container = None
if isinstance(container_selector, list):
for selector in container_selector:
container = soup.select_one(selector)
if container:
logger.debug(f"Found container with selector '{selector}': {container.name}[class={container.get('class', [])}]")
break
if not container:
logger.error(f"Could not find video container at {url} with any selector in {container_selector}")
return None, None, False
else:
logger.debug(f"Searching for container with selector: '{container_selector}'")
container = soup.select_one(container_selector)
if not container:
logger.error(f"Could not find video container at {url} with selector '{container_selector}'")
return None, None, False
logger.debug(f"Found container: {container.name}[class={container.get('class', [])}]")
item_selector = list_scraper['video_item']['selector']
logger.debug(f"Searching for video items with selector: '{item_selector}'")
video_elements = container.select(item_selector)
logger.debug(f"Found {len(video_elements)} video items")
if not video_elements:
logger.debug(f"No videos found on page {page_num} with selector '{item_selector}'")
return None, None, False
term_width = get_terminal_width()
print()
print()
page_info = f" page {page_num}, {site_config['name'].lower()} {mode}: \"{identifier}\" "
page_line = page_info.center(term_width, "═")
print(colored(page_line, "yellow"))
success = False
for i, video_element in enumerate(video_elements, 1):
if video_offset > 0 and i < video_offset: # Start at video_offset, 1-based
continue
video_data = extract_data(video_element, list_scraper['video_item']['fields'], driver, site_config)
if 'url' in video_data:
video_url = video_data['url']
if not video_url.startswith(('http://', 'https://')):
video_url = f"http:{video_url}" if video_url.startswith('//') else urllib.parse.urljoin(base_url, video_url)
elif 'video_key' in video_data:
video_url = construct_url(base_url, site_config['modes']['video']['url_pattern'], site_config, mode='video', video=video_data['video_key'])
else:
logger.warning("Unable to construct video URL")
continue
video_title = video_data.get('title', '').strip() or video_element.text.strip()
print()
counter = f"{i} of {len(video_elements)}"
counter_line = f"┈┈┈ {counter} ┈ {video_url} ".ljust(term_width, "┈")
print(colored(counter_line, "magenta"))
if is_url_processed(video_url, state_set) and not (overwrite or new_nfo):
logger.info(f"Skipping already processed video: {video_url}")
success = True
continue
video_success = process_video_page(video_url, site_config, general_config, overwrite, headers, new_nfo, do_not_ignore, apply_state=apply_state, state_set=state_set)
if video_success:
success = True
if driver:
driver.quit()
if mode not in site_config['modes']:
logger.warning(f"No pagination for mode '{mode}' as it’s not defined in site_config['modes']")
return None, None, success
mode_config = site_config['modes'][mode]
scraper_pagination = list_scraper.get('pagination', {})
url_pattern_pages = mode_config.get('url_pattern_pages')
max_pages = mode_config.get('max_pages', scraper_pagination.get('max_pages', float('inf')))
if page_num >= max_pages:
logger.warning(f"Stopping pagination: page_num={page_num} >= max_pages={max_pages}")
return None, None, success
next_url = None
if url_pattern_pages:
next_url = construct_url(
base_url,
url_pattern_pages,
site_config,
mode=mode,
**{mode: identifier, 'page': page_num + 1}
)
logger.debug(f"Generated next page URL (pattern-based): {next_url}")
elif scraper_pagination:
if 'next_page' in scraper_pagination:
next_page_config = scraper_pagination['next_page']
next_page = soup.select_one(next_page_config.get('selector', ''))
if next_page:
next_url = next_page.get(next_page_config.get('attribute', 'href'))
if next_url and not next_url.startswith(('http://', 'https://')):
next_url = urllib.parse.urljoin(base_url, next_url)
logger.debug(f"Found next page URL (selector-based): {next_url}")
else:
logger.warning(f"No 'next' element found with selector '{next_page_config.get('selector')}'")
if next_url:
return next_url, page_num + 1, success
logger.warning("No next page URL generated; stopping pagination")
return None, None, success
def process_video_page(url, site_config, general_config, overwrite=False, headers=None, new_nfo=False, do_not_ignore=False, apply_state=False, state_set=None):
global last_vpn_action_time
vpn_config = general_config.get('vpn', {})
if vpn_config.get('enabled', False):
current_time = time.time()
if current_time - last_vpn_action_time > vpn_config.get('new_node_time', 300):
handle_vpn(general_config, 'new_node')
logger.debug(f"Processing video page: {url}")
use_selenium = site_config.get('use_selenium', False)
driver = get_selenium_driver(general_config) if use_selenium else None
original_url = url
iframe_url = None
video_url = None
raw_data = {'title': original_url.split('/')[-2]}
if site_config.get('m3u8_mode', False) and driver:
video_scraper = site_config['scrapers']['video_scraper']
iframe_config = next(({'enabled': True, 'selector': config['iframe']} for field, config in video_scraper.items()
if isinstance(config, dict) and 'iframe' in config), None)
if iframe_config:
logger.debug(f"Piercing iframe '{iframe_config['selector']}' for M3U8")
driver.get(original_url)
time.sleep(random.uniform(1, 2))
try:
iframe = driver.find_element(By.CSS_SELECTOR, iframe_config['selector'])
iframe_url = iframe.get_attribute("src")
if iframe_url:
logger.info(f"Found iframe: {iframe_url}")
driver.get(iframe_url)
time.sleep(random.uniform(1, 2))
m3u8_url, cookies = extract_m3u8_urls(driver, iframe_url, site_config)
if m3u8_url:
video_url = m3u8_url
headers = headers or general_config.get('headers', {}).copy()
headers.update({"Cookie": cookies, "Referer": iframe_url,
"User-Agent": general_config.get('selenium_user_agent', random.choice(general_config['user_agents']))})
except Exception as e:
logger.warning(f"Iframe error: {e}")
soup = fetch_page(original_url, general_config['user_agents'], headers or {}, use_selenium, driver)
if soup:
raw_data = extract_data(soup, site_config['scrapers']['video_scraper'], driver, site_config)
video_url = video_url or raw_data.get('download_url')
else:
soup = fetch_page(original_url, general_config['user_agents'], headers or {}, use_selenium, driver)
if soup is None and use_selenium:
logger.warning("Selenium failed; retrying with requests")
soup = fetch_page(original_url, general_config['user_agents'], headers or {}, False, None)
if soup is None:
logger.error(f"Failed to fetch: {original_url}")
if driver:
driver.quit()
return False
raw_data = extract_data(soup, site_config['scrapers']['video_scraper'], driver, site_config)
video_url = raw_data.get('download_url')
video_url = video_url or original_url
video_title = raw_data.get('title', '').strip() or 'Untitled'
raw_data['Title'] = video_title
raw_data['URL'] = original_url
if not do_not_ignore and should_ignore_video(raw_data, general_config['ignored']):
if driver:
driver.quit()
return True
final_metadata = finalize_metadata(raw_data, general_config)
file_name = construct_filename(final_metadata['title'], site_config, general_config)
destination_config = general_config['download_destinations'][0]
state_updated = False
if destination_config['type'] == 'smb':
smb_path = os.path.join(destination_config['path'], file_name)
if not overwrite and file_exists_on_smb(destination_config, smb_path):
logger.info(f"File '{smb_path}' exists on SMB share. Skipping download.")
if apply_state and not is_url_processed(original_url, state_set):
state_set.add(original_url)
save_state(original_url)
logger.debug(f"Retroactively added {original_url} to state due to existing file and --applystate")
state_updated = True
if general_config.get('make_nfo', False) and has_metadata_selectors(site_config):
smb_nfo_path = os.path.join(destination_config['path'], f"{file_name.rsplit('.', 1)[0]}.nfo")
if not (new_nfo or file_exists_on_smb(destination_config, smb_nfo_path)):
temp_nfo_path = os.path.join(tempfile.gettempdir(), 'smutscrape', f"{file_name.rsplit('.', 1)[0]}.nfo")
os.makedirs(os.path.dirname(temp_nfo_path), exist_ok=True)
generate_nfo(temp_nfo_path, final_metadata, True)
upload_to_smb(temp_nfo_path, smb_nfo_path, destination_config, overwrite)
os.remove(temp_nfo_path)
if driver:
driver.quit()
return True
if destination_config['type'] == 'smb':
temp_dir = destination_config.get('temporary_storage', os.path.join(tempfile.gettempdir(), 'smutscrape'))
os.makedirs(temp_dir, exist_ok=True)
final_destination_path = os.path.join(temp_dir, file_name)
temp_destination_path = f"{final_destination_path}.part"
else:
final_destination_path = os.path.join(destination_config['path'], file_name)
temp_destination_path = final_destination_path # No .part for local
# Check for existing complete file in temp dir
if destination_config['type'] == 'smb' and not overwrite and os.path.exists(final_destination_path):
video_info = get_video_metadata(final_destination_path)
if video_info:
logger.info(f"Valid complete file '{final_destination_path}' exists in temp dir. Skipping download.")
success = True
else:
logger.warning(f"Invalid file '{final_destination_path}' in temp dir. Redownloading.")
os.remove(final_destination_path)
success = download_video(video_url, final_destination_path, site_config, general_config, headers, final_metadata, overwrite)
else:
success = download_video(video_url, final_destination_path, site_config, general_config, headers, final_metadata, overwrite)
if success and general_config.get('make_nfo', False) and has_metadata_selectors(site_config):
generate_nfo(final_destination_path, final_metadata, overwrite or new_nfo)
if success and destination_config['type'] == 'smb':
manage_file(final_destination_path, destination_config, overwrite, video_url=original_url, state_set=state_set)
if success and not is_url_processed(original_url, state_set):
state_set.add(original_url)
save_state(original_url)
if driver:
driver.quit()
time.sleep(general_config['sleep']['between_videos'])
return success or state_updated
def pierce_iframe(driver, url, site_config):
"""
Attempts to pierce into an iframe if specified in site_config.
Returns the final URL loaded (iframe src or original URL).
"""
iframe_config = site_config.get('iframe', {})
if not iframe_config.get('enabled', False):
driver.get(url)
return url
logger.debug(f"Attempting iframe piercing for: {url}")
driver.get(url)
time.sleep(random.uniform(1, 2)) # Initial page load
try:
iframe_selector = iframe_config.get('selector', 'iframe')
iframe = driver.find_element(By.CSS_SELECTOR, iframe_selector)
iframe_url = iframe.get_attribute("src")
if iframe_url:
logger.info(f"Found iframe with src: {iframe_url}")
driver.get(iframe_url)
time.sleep(random.uniform(1, 2))
return iframe_url
else:
logger.warning("Iframe found but no src attribute.")
return url
except Exception as e:
logger.warning(f"No iframe found or error piercing: {e}")
return url
def extract_m3u8_urls(driver, url, site_config):
logger.debug(f"Extracting M3U8 URLs from: {url}")
# URL is already loaded (iframe or original) by process_video_page
driver.get(url) # Redundant but ensures we’re on the right page
driver.execute_script("""
(function() {
let open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
if (url.includes(".m3u8")) {
console.log("🔥 Found M3U8 via XHR:", url);
}
return open.apply(this, arguments);
};
})();
""")
time.sleep(5)
logs = driver.get_log("performance")
m3u8_urls = []
logger.debug(f"Analyzing {len(logs)} performance logs")
for log in logs:
try:
message = json.loads(log["message"])["message"]
if "Network.responseReceived" in message["method"]:
request_url = message["params"]["response"]["url"]
if ".m3u8" in request_url:
m3u8_urls.append(request_url)
logger.debug(f"Found M3U8 URL: {request_url}")
except KeyError:
continue
if not m3u8_urls:
logger.warning("No M3U8 URLs detected in network traffic")
return None, None
best_m3u8 = sorted(m3u8_urls, key=lambda u: "1920x1080" in u, reverse=True)[0]
cookies_list = driver.get_cookies()
cookies_str = "; ".join([f"{c['name']}={c['value']}" for c in cookies_list])
logger.debug(f"Cookies after load: {cookies_str if cookies_str else 'None'}")
logger.info(f"Selected best M3U8: {best_m3u8}")
return best_m3u8, cookies_str
def fetch_page(url, user_agents, headers, use_selenium=False, driver=None, retry_count=0):
if not use_selenium:
scraper = cloudscraper.create_scraper()
if 'User-Agent' not in headers:
headers['User-Agent'] = random.choice(user_agents)
logger.debug(f"Fetching URL (requests): {url}")
time.sleep(random.uniform(1, 3))
try:
response = scraper.get(url, headers=headers, timeout=30)
response.raise_for_status()
return BeautifulSoup(response.content, "html.parser")
except requests.exceptions.RequestException as e:
logger.error(f"Error fetching {url}: {e}")
return None
else:
if driver is None:
logger.warning("Selenium requested, but no driver provided.")
return None
logger.debug(f"Fetching URL (selenium): {url}")
try:
site_config = globals().get('site_config', {})
if site_config.get('iframe', {}).get('enabled'):
final_url = pierce_iframe(driver, url, site_config)
else:
driver.get(url)
final_url = url
logger.debug(f"Final URL after iframe handling: {final_url}")
time.sleep(random.uniform(2, 4))
return BeautifulSoup(driver.page_source, 'html.parser')
except Exception as e:
if retry_count < 2 and 'general_config' in globals():
logger.warning(f"Selenium error: {e}. Retrying with new session...")
new_driver = get_selenium_driver(globals()['general_config'], force_new=True)
if new_driver:
return fetch_page(url, user_agents, headers, use_selenium, new_driver, retry_count + 1)
logger.error(f"Failed to fetch {url} with Selenium: {e}")
return None
def extract_data(soup, selectors, driver=None, site_config=None):
data = {}
if soup is None:
logger.error("Soup is None; cannot extract data")
return data
for field, config in selectors.items():
if field == 'download_url' and site_config.get('m3u8_mode', False):
continue
if isinstance(config, str):
elements = soup.select(config)
elif isinstance(config, dict):
if 'iframe' in config and driver and site_config:
iframe_selector = config['iframe']
logger.debug(f"Piercing iframe '{iframe_selector}' for field '{field}'")
try:
iframe = driver.find_element(By.CSS_SELECTOR, iframe_selector)
driver.switch_to.frame(iframe)
iframe_soup = BeautifulSoup(driver.page_source, 'html.parser')
elements = iframe_soup.select(config.get('selector', ''))
driver.switch_to.default_content()
except Exception as e:
logger.error(f"Failed to pierce iframe '{iframe_selector}' for '{field}': {e}")
elements = []
elif 'selector' in config:
selector = config['selector']
if isinstance(selector, list):
elements = []
for sel in selector:
elements.extend(soup.select(sel))
if elements:
break
else:
elements = soup.select(selector)
elif 'attribute' in config:
elements = [soup]
else:
elements = []
else:
elements = []
if not elements:
data[field] = ''
logger.debug(f"No elements found for '{field}'")
continue
if isinstance(config, dict) and 'attribute' in config:
# Handle attribute-based extraction (e.g., href, src)
values = [element.get(config['attribute']) for element in elements if element.get(config['attribute'])]
# If only one value, use it directly; otherwise, keep as list for post-processing
value = values[0] if len(values) == 1 else values if values else ''
if value is None:
logger.debug(f"Attribute '{config['attribute']}' for '{field}' is None; defaulting to empty string")
value = ''
else:
# Handle text-based extraction
value = elements[0].text.strip() if hasattr(elements[0], 'text') and elements[0].text else ''
if value is None:
value = ''
# Handle multi-value fields with deduplication only for text-based fields
if field in ['tags', 'actors', 'producers', 'studios'] and not (isinstance(config, dict) and 'attribute' in config):
values = [element.text.strip() for element in elements if hasattr(element, 'text') and element.text and element.text.strip()]
normalized_values = {v.lower() for v in values if v}
value = [v for v in values if v.lower() in normalized_values]
seen = set()
value = [v for v in value if not (v.lower() in seen or seen.add(v.lower()))]
# Apply post-processing if present, or default to first value for lists without postProcess
if isinstance(config, dict):
if 'postProcess' in config:
for step in config['postProcess']:
if 'replace' in step:
for pair in step['replace']:
regex, replacement = pair['regex'], pair['with']
try:
if isinstance(value, list):
value = [re.sub(regex, replacement, v, flags=re.DOTALL) if v else '' for v in value]
else:
old_value = value
value = re.sub(regex, replacement, value, flags=re.DOTALL) if value else ''
if value != old_value:
logger.debug(f"Applied regex '{regex}' -> '{replacement}' for '{field}': {value}")
except re.error as e:
logger.error(f"Regex error for '{field}': regex={regex}, error={e}")
value = ''
elif 'max_attribute' in step:
if not isinstance(value, list):
logger.debug(f"Skipping max_attribute for '{field}' as value is not a list: {value}")
continue
attr_name = step.get('attribute')
attr_type = step.get('type', 'str')
if not attr_name:
logger.error(f"max_attribute for '{field}' missing 'attribute' key")
continue
try:
attr_values = [(val, elements[i].get(attr_name)) for i, val in enumerate(value) if elements[i].get(attr_name) is not None]
if not attr_values:
logger.debug(f"No valid '{attr_name}' attributes found for '{field}'; using first value")
value = value[0] if value else ''
else:
if attr_type == 'int':
converted_attrs = [(val, int(attr)) for val, attr in attr_values]
elif attr_type == 'float':
converted_attrs = [(val, float(attr)) for val, attr in attr_values]
else:
converted_attrs = [(val, str(attr)) for val, attr in attr_values]
value = max(converted_attrs, key=lambda x: x[1])[0]
logger.debug(f"Applied max_attribute '{attr_name}' (type: {attr_type}) for '{field}': selected {value}")
except (ValueError, TypeError) as e:
logger.error(f"Failed to convert '{attr_name}' to {attr_type} for '{field}': {e}")
value = value[0] if value else ''
elif 'first' in step and step['first'] and isinstance(value, list):
value = value[0] if value else ''
elif isinstance(value, list) and field not in ['tags', 'actors', 'studios']:
# Default to first value for lists without postProcess, except multi-value fields
value = value[0] if value else ''
logger.debug(f"No postProcess for '{field}' with multiple values; defaulted to first: {value}")
data[field] = value if value or isinstance(value, list) else ''
logger.debug(f"Final value for '{field}': {data[field]}")
return data
def should_ignore_video(data, ignored_terms):
if not ignored_terms:
return False
ignored_terms_lower = [term.lower() for term in ignored_terms]
ignored_terms_encoded = [term.lower().replace(' ', '-') for term in ignored_terms]
# Compile regex patterns with word boundaries for efficiency
term_patterns = [re.compile(r'\b' + re.escape(term) + r'\b') for term in ignored_terms_lower]
encoded_patterns = [re.compile(r'\b' + re.escape(encoded) + r'\b') for encoded in ignored_terms_encoded]
for field, value in data.items():
if isinstance(value, str):
value_lower = value.lower()
for term, term_pattern, encoded_pattern in zip(ignored_terms_lower, term_patterns, encoded_patterns):
if term_pattern.search(value_lower) or encoded_pattern.search(value_lower):
logger.warning(f"Ignoring video due to term '{term}' in {field}: '{value}'")
return True
elif isinstance(value, list):
for item in value:
item_lower = item.lower()
for term, term_pattern, encoded_pattern in zip(ignored_terms_lower, term_patterns, encoded_patterns):
if term_pattern.search(item_lower) or encoded_pattern.search(item_lower):
logger.warning(f"Ignoring video due to term '{term}' in {field}: '{item}'")
return True
return False
def apply_permissions(file_path, destination_config):
if 'permissions' not in destination_config:
return
permissions = destination_config['permissions']
try:
uid = pwd.getpwnam(permissions['owner']).pw_uid if 'owner' in permissions and permissions['owner'].isalpha() else int(permissions.get('uid', -1))
gid = grp.getgrnam(permissions['group']).gr_gid if 'group' in permissions and permissions['group'].isalpha() else int(permissions.get('gid', -1))
if uid != -1 or gid != -1:
current_uid = os.stat(file_path).st_uid if uid == -1 else uid
current_gid = os.stat(file_path).st_gid if gid == -1 else gid
os.chown(file_path, current_uid, current_gid)
if 'mode' in permissions:
os.chmod(file_path, int(permissions['mode'], 8))
except Exception as e:
logger.error(f"Failed to apply permissions to {file_path}: {e}")
def upload_to_smb(local_path, smb_path, destination_config, overwrite=False):
conn = SMBConnection(destination_config['username'], destination_config['password'], "videoscraper", destination_config['server'])
try:
if conn.connect(destination_config['server'], 445):
if not overwrite and file_exists_on_smb(destination_config, smb_path):
logger.info(f"File '{smb_path}' exists on SMB share. Skipping.")
return
file_size = os.path.getsize(local_path)
with open(local_path, 'rb') as file:
with tqdm(total=file_size, unit='B', unit_scale=True, desc="Uploading to SMB") as pbar:
progress_file = ProgressFile(file, pbar)
conn.storeFile(destination_config['share'], smb_path, progress_file)
else:
logger.error("Failed to connect to SMB share.")
except Exception as e:
logger.error(f"Error uploading to SMB: {e}")
finally:
conn.close()
def get_video_metadata(file_path):
"""Extract video duration, resolution, and bitrate using ffprobe, with sanity check."""
command = [
"ffprobe",
"-v", "error",
"-show_entries", "format=duration,bit_rate,size:stream=width,height",
"-of", "json",
file_path
]
try:
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, check=True)
metadata = json.loads(result.stdout)
# File size in bytes (from ffprobe or os)
file_size = int(metadata.get('format', {}).get('size', os.path.getsize(file_path)))
# Duration in seconds
duration = float(metadata.get('format', {}).get('duration', 0))
duration_str = f"{int(duration // 3600):02d}:{int((duration % 3600) // 60):02d}:{int(duration % 60):02d}"
# Resolution
streams = metadata.get('streams', [])
video_stream = next((s for s in streams if s.get('width') and s.get('height')), None)
resolution = f"{video_stream['width']}x{video_stream['height']}" if video_stream else "Unknown"
# Bitrate in kbps
bitrate = int(metadata.get('format', {}).get('bit_rate', 0)) // 1000 if metadata.get('format', {}).get('bit_rate') else 0
# Sanity check: reject if file is too small for claimed duration (e.g., < 10KB/s)
if duration > 0 and file_size / duration < 10240: # ~10KB/s minimum, adjustable
logger.warning(f"File {file_path} too small ({file_size} bytes) for duration {duration}s")
return None
return {
'size': file_size,
'size_str': f"{file_size / 1024 / 1024:.2f} MB",
'duration': duration_str,
'resolution': resolution,
'bitrate': f"{bitrate} kbps" if bitrate else "Unknown"
}
except subprocess.CalledProcessError as e:
logger.error(f"ffprobe failed for {file_path}: {e.stderr}")
return None
except Exception as e:
logger.error(f"Error extracting metadata for {file_path}: {e}")
return None