| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2014-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Common classes and constants used by extractor modules.""" |
| 10 |
|
| 11 |
import os |
| 12 |
import re |
| 13 |
import ssl |
| 14 |
import time |
| 15 |
import netrc |
| 16 |
import queue |
| 17 |
import pickle |
| 18 |
import random |
| 19 |
import getpass |
| 20 |
import logging |
| 21 |
import requests |
| 22 |
import threading |
| 23 |
from xml.etree import ElementTree |
| 24 |
from requests.adapters import HTTPAdapter |
| 25 |
from .message import Message |
| 26 |
from .. import config, output, text, util, dt, cache, exception |
| 27 |
urllib3 = requests.packages.urllib3 |
| 28 |
|
| 29 |
|
| 30 |
class Extractor(): |
| 31 |
|
| 32 |
category = "" |
| 33 |
subcategory = "" |
| 34 |
basecategory = "" |
| 35 |
basesubcategory = "" |
| 36 |
categorytransfer = False |
| 37 |
parent = False |
| 38 |
directory_fmt = ("{category}",) |
| 39 |
filename_fmt = "{filename}.{extension}" |
| 40 |
archive_fmt = "" |
| 41 |
status = 0 |
| 42 |
root = "" |
| 43 |
cookies_file = "" |
| 44 |
cookies_index = 0 |
| 45 |
cookies_domain = "" |
| 46 |
session = None |
| 47 |
referer = True |
| 48 |
ciphers = None |
| 49 |
tls12 = True |
| 50 |
browser = None |
| 51 |
useragent = util.USERAGENT_FIREFOX |
| 52 |
geobypass = None |
| 53 |
download_interval = 0.0 |
| 54 |
request_interval = 0.0 |
| 55 |
request_interval_min = 0.0 |
| 56 |
request_interval_429 = 60.0 |
| 57 |
request_timestamp = 0.0 |
| 58 |
async_mode = False |
| 59 |
exc = exception |
| 60 |
finalize = skip_files = skip_posts = skip_children = skip_date = \ |
| 61 |
import_blacklist = None |
| 62 |
|
| 63 |
def __init__(self, match): |
| 64 |
self.log = logging.getLogger(self.category) |
| 65 |
self.url = match.string |
| 66 |
self.match = match |
| 67 |
self.groups = match.groups() |
| 68 |
self.kwdict = {} |
| 69 |
|
| 70 |
if self.category in CATEGORY_MAP: |
| 71 |
catsub = f"{self.category}:{self.subcategory}" |
| 72 |
if catsub in CATEGORY_MAP: |
| 73 |
self.category, self.subcategory = CATEGORY_MAP[catsub] |
| 74 |
else: |
| 75 |
self.category = CATEGORY_MAP[self.category] |
| 76 |
|
| 77 |
self.parse_datetime = dt.parse |
| 78 |
self.parse_datetime_iso = dt.parse_iso |
| 79 |
self.parse_timestamp = dt.parse_ts |
| 80 |
|
| 81 |
self._cfgpath = ("extractor", self.category, self.subcategory) |
| 82 |
self._parentdir = "" |
| 83 |
|
| 84 |
def __str__(self): |
| 85 |
return f"{self.__class__.__name__} <{self.url}>" |
| 86 |
|
| 87 |
@classmethod |
| 88 |
def from_url(cls, url): |
| 89 |
if isinstance(cls.pattern, str): |
| 90 |
cls.pattern = util.re_compile(cls.pattern) |
| 91 |
match = cls.pattern.match(url) |
| 92 |
return cls(match) if match else None |
| 93 |
|
| 94 |
def __iter__(self): |
| 95 |
self.initialize() |
| 96 |
return self.items() |
| 97 |
|
| 98 |
def initialize(self): |
| 99 |
self._init_options() |
| 100 |
|
| 101 |
if self.session is None: |
| 102 |
self._init_session() |
| 103 |
self.cookies = self.session.cookies |
| 104 |
if self.cookies_domain is not None: |
| 105 |
self._init_cookies() |
| 106 |
else: |
| 107 |
self.cookies = self.session.cookies |
| 108 |
|
| 109 |
self._init() |
| 110 |
self.initialize = util.noop |
| 111 |
|
| 112 |
def items(self): |
| 113 |
return |
| 114 |
yield |
| 115 |
|
| 116 |
def config(self, key, default=None): |
| 117 |
return config.interpolate(self._cfgpath, key, default) |
| 118 |
|
| 119 |
def config2(self, key, key2, default=None, sentinel=util.SENTINEL): |
| 120 |
value = self.config(key, sentinel) |
| 121 |
if value is not sentinel: |
| 122 |
return value |
| 123 |
return self.config(key2, default) |
| 124 |
|
| 125 |
def config_accumulate(self, key): |
| 126 |
return config.accumulate(self._cfgpath, key) |
| 127 |
|
| 128 |
def config_instance(self, key, default=None): |
| 129 |
return default |
| 130 |
|
| 131 |
def _config_shared(self, key, default=None): |
| 132 |
return config.interpolate_common( |
| 133 |
("extractor",), self._cfgpath, key, default) |
| 134 |
|
| 135 |
def _config_shared_accumulate(self, key): |
| 136 |
first = True |
| 137 |
extr = ("extractor",) |
| 138 |
|
| 139 |
for path in self._cfgpath: |
| 140 |
if first: |
| 141 |
first = False |
| 142 |
values = config.accumulate(extr + path, key) |
| 143 |
elif conf := config.get(extr, path[0]): |
| 144 |
values[:0] = config.accumulate( |
| 145 |
(self.subcategory,), key, conf=conf) |
| 146 |
|
| 147 |
return values |
| 148 |
|
| 149 |
def request(self, url, method="GET", session=None, fatal=True, |
| 150 |
retries=None, retry_codes=None, expected=(), interval=True, |
| 151 |
encoding=None, notfound=None, **kwargs): |
| 152 |
if session is None: |
| 153 |
session = self.session |
| 154 |
if retries is None: |
| 155 |
retries = self._retries |
| 156 |
if retry_codes is None: |
| 157 |
retry_codes = self._retry_codes |
| 158 |
if "proxies" not in kwargs: |
| 159 |
kwargs["proxies"] = self._proxies |
| 160 |
if "timeout" not in kwargs: |
| 161 |
kwargs["timeout"] = self._timeout |
| 162 |
if "verify" not in kwargs: |
| 163 |
kwargs["verify"] = self._verify |
| 164 |
|
| 165 |
if "json" in kwargs: |
| 166 |
if (json := kwargs["json"]) is not None: |
| 167 |
kwargs["data"] = util.json_dumps(json).encode() |
| 168 |
del kwargs["json"] |
| 169 |
if headers := kwargs.get("headers"): |
| 170 |
headers["Content-Type"] = "application/json" |
| 171 |
else: |
| 172 |
kwargs["headers"] = {"Content-Type": "application/json"} |
| 173 |
|
| 174 |
response = challenge = None |
| 175 |
tries = 1 |
| 176 |
|
| 177 |
if self._interval_request is not None and interval: |
| 178 |
seconds = (self._interval_request() - |
| 179 |
(time.time() - Extractor.request_timestamp)) |
| 180 |
if seconds > 0.0: |
| 181 |
self.sleep(seconds, "request") |
| 182 |
|
| 183 |
while True: |
| 184 |
try: |
| 185 |
response = session.request(method, url, **kwargs) |
| 186 |
except requests.exceptions.ConnectionError as exc: |
| 187 |
try: |
| 188 |
reason = exc.args[0].reason |
| 189 |
cls = reason.__class__.__name__ |
| 190 |
pre, _, err = str(reason.args[-1]).partition(":") |
| 191 |
msg = f" {cls}: {(err or pre).lstrip()}" |
| 192 |
except Exception: |
| 193 |
msg = exc |
| 194 |
code = 0 |
| 195 |
except (requests.exceptions.Timeout, |
| 196 |
requests.exceptions.ChunkedEncodingError, |
| 197 |
requests.exceptions.ContentDecodingError) as exc: |
| 198 |
msg = exc |
| 199 |
code = 0 |
| 200 |
except (requests.exceptions.RequestException) as exc: |
| 201 |
msg = exc |
| 202 |
break |
| 203 |
else: |
| 204 |
code = response.status_code |
| 205 |
if self._write_pages: |
| 206 |
self._dump_response(response) |
| 207 |
if ( |
| 208 |
code < 400 or |
| 209 |
code in expected or |
| 210 |
code < 500 and ( |
| 211 |
not fatal and code != 429 or fatal is None) or |
| 212 |
fatal is ... |
| 213 |
): |
| 214 |
if encoding: |
| 215 |
response.encoding = encoding |
| 216 |
return response |
| 217 |
if notfound is not None and code == 404: |
| 218 |
if notfound is True: |
| 219 |
notfound = self.__class__.subcategory |
| 220 |
self.status |= exception.NotFoundError.code |
| 221 |
raise exception.NotFoundError(notfound) |
| 222 |
|
| 223 |
msg = f"'{code} {response.reason}' for '{response.url}'" |
| 224 |
|
| 225 |
challenge = util.detect_challenge(response) |
| 226 |
if challenge is not None: |
| 227 |
self.log.warning(challenge) |
| 228 |
|
| 229 |
if code == 429 and self._handle_429(response): |
| 230 |
continue |
| 231 |
elif code == 429 and self._interval_429: |
| 232 |
pass |
| 233 |
elif code not in retry_codes and code < 500: |
| 234 |
break |
| 235 |
|
| 236 |
finally: |
| 237 |
if interval: |
| 238 |
Extractor.request_timestamp = time.time() |
| 239 |
|
| 240 |
self.log.debug("%s (%s/%s)", msg, tries, retries+1) |
| 241 |
if tries > retries: |
| 242 |
break |
| 243 |
|
| 244 |
seconds = self._interval_retry(tries) |
| 245 |
if self._interval_request is not None: |
| 246 |
s = self._interval_request() |
| 247 |
if seconds < s: |
| 248 |
seconds = s |
| 249 |
if code == 429 and self._interval_429 is not None: |
| 250 |
s = self._interval_429(tries) |
| 251 |
if seconds < s: |
| 252 |
seconds = s |
| 253 |
self.wait(seconds=seconds, reason="429 Too Many Requests") |
| 254 |
else: |
| 255 |
self.sleep(seconds, "retry") |
| 256 |
tries += 1 |
| 257 |
|
| 258 |
if not fatal or fatal is ...: |
| 259 |
self.log.warning(msg) |
| 260 |
return util.NullResponse(url, msg) |
| 261 |
|
| 262 |
if challenge is None: |
| 263 |
exc = exception.HttpError(msg, response) |
| 264 |
else: |
| 265 |
exc = exception.ChallengeError(challenge, response) |
| 266 |
self.status |= exc.code |
| 267 |
raise exc |
| 268 |
|
| 269 |
def request_location(self, url, **kwargs): |
| 270 |
kwargs.setdefault("method", "HEAD") |
| 271 |
kwargs.setdefault("allow_redirects", False) |
| 272 |
kwargs.setdefault("interval", False) |
| 273 |
return self.request(url, **kwargs).headers.get("location", "") |
| 274 |
|
| 275 |
def request_json(self, url, **kwargs): |
| 276 |
if headers := kwargs.get("headers"): |
| 277 |
headers.setdefault("Referer", self.root + "/") |
| 278 |
headers.setdefault("Origin" , self.root) |
| 279 |
headers.setdefault("Sec-Fetch-Dest", "empty") |
| 280 |
headers.setdefault("Sec-Fetch-Mode", "cors") |
| 281 |
headers.setdefault("Sec-Fetch-Site", "same-site") |
| 282 |
elif headers is None: |
| 283 |
kwargs["headers"] = { |
| 284 |
"Referer": self.root + "/", |
| 285 |
"Origin" : self.root, |
| 286 |
"Sec-Fetch-Dest": "empty", |
| 287 |
"Sec-Fetch-Mode": "cors", |
| 288 |
"Sec-Fetch-Site": "same-site", |
| 289 |
} |
| 290 |
else: |
| 291 |
del kwargs["headers"] |
| 292 |
response = self.request(url, **kwargs) |
| 293 |
|
| 294 |
try: |
| 295 |
return util.json_loads(response.text) |
| 296 |
except Exception as exc: |
| 297 |
fatal = kwargs.get("fatal", True) |
| 298 |
if not fatal or fatal is ...: |
| 299 |
if challenge := util.detect_challenge(response): |
| 300 |
self.log.warning(challenge) |
| 301 |
else: |
| 302 |
self.log.warning("%s: %s", exc.__class__.__name__, exc) |
| 303 |
return {} |
| 304 |
raise |
| 305 |
|
| 306 |
def request_xml(self, url, xmlns=True, **kwargs): |
| 307 |
response = self.request(url, **kwargs) |
| 308 |
|
| 309 |
if xmlns: |
| 310 |
text = response.text |
| 311 |
else: |
| 312 |
text = response.text.replace(" xmlns=", " ns=") |
| 313 |
|
| 314 |
parser = ElementTree.XMLParser() |
| 315 |
try: |
| 316 |
parser.feed(text) |
| 317 |
return parser.close() |
| 318 |
except Exception as exc: |
| 319 |
fatal = kwargs.get("fatal", True) |
| 320 |
if not fatal or fatal is ...: |
| 321 |
if challenge := util.detect_challenge(response): |
| 322 |
self.log.warning(challenge) |
| 323 |
else: |
| 324 |
self.log.warning("%s: %s", exc.__class__.__name__, exc) |
| 325 |
return ElementTree.Element("") |
| 326 |
raise |
| 327 |
|
| 328 |
_handle_429 = util.false |
| 329 |
|
| 330 |
def wait(self, seconds=None, until=None, adjust=1.0, |
| 331 |
reason="rate limit"): |
| 332 |
now = time.time() |
| 333 |
|
| 334 |
if seconds: |
| 335 |
seconds = float(seconds) |
| 336 |
until = now + seconds |
| 337 |
elif until: |
| 338 |
if isinstance(until, dt.datetime): |
| 339 |
# convert to UTC timestamp |
| 340 |
until = dt.to_ts(until) |
| 341 |
else: |
| 342 |
until = float(until) |
| 343 |
seconds = until - now |
| 344 |
else: |
| 345 |
raise ValueError("Either 'seconds' or 'until' is required") |
| 346 |
|
| 347 |
seconds += adjust |
| 348 |
if seconds <= 0.0: |
| 349 |
return |
| 350 |
|
| 351 |
if reason: |
| 352 |
if seconds >= 3600.0: |
| 353 |
h, m = divmod(seconds, 3600.0) |
| 354 |
dur = f"{int(h)}h {int(m/60.0)}min" |
| 355 |
elif seconds >= 60.0: |
| 356 |
dur = str(int(seconds/60.0)) + " minutes" |
| 357 |
else: |
| 358 |
dur = str(int(seconds)) + " seconds" |
| 359 |
t = time.localtime(until) |
| 360 |
iso = f"{t.tm_hour:02}:{t.tm_min:02}:{t.tm_sec:02}" |
| 361 |
self.log.info("Waiting for %s until %s (%s)", dur, iso, reason) |
| 362 |
time.sleep(seconds) |
| 363 |
|
| 364 |
def sleep(self, seconds, reason): |
| 365 |
self.log.debug("Sleeping %.2f seconds (%s)", |
| 366 |
seconds, reason) |
| 367 |
time.sleep(seconds) |
| 368 |
|
| 369 |
def utils(self, module="", name=None): |
| 370 |
module = (self.__class__.category if not module else |
| 371 |
module[1:] if module[0] == "/" else |
| 372 |
f"{self.__class__.category}_{module}") |
| 373 |
if module in CACHE_UTILS: |
| 374 |
res = CACHE_UTILS[module] |
| 375 |
else: |
| 376 |
res = CACHE_UTILS[module] = __import__( |
| 377 |
"utils." + module, globals(), None, module, 1) |
| 378 |
return res if name is None else getattr(res, name, None) |
| 379 |
|
| 380 |
def cache(self, func, *args, _key=0, _exp=0, _mem=True): |
| 381 |
if _key is None: |
| 382 |
key = f"{func.__module__}.{func.__name__}" |
| 383 |
else: |
| 384 |
key = f"{func.__module__}.{func.__name__}-{args[_key]}" |
| 385 |
|
| 386 |
try: |
| 387 |
value, expires = CACHE_MEMORY[key] |
| 388 |
except KeyError: |
| 389 |
expires = 1 |
| 390 |
|
| 391 |
if not expires or expires > (now := int(time.time())): |
| 392 |
return value |
| 393 |
|
| 394 |
if not _mem and (db := cache.database()): |
| 395 |
with db: |
| 396 |
cursor = db.cursor() |
| 397 |
try: |
| 398 |
cursor.execute("BEGIN EXCLUSIVE") |
| 399 |
except Exception: |
| 400 |
pass # swallow exception when already in a transaction |
| 401 |
cursor.execute( |
| 402 |
"SELECT value, expires FROM data WHERE key=? LIMIT 1", |
| 403 |
(key,)) |
| 404 |
|
| 405 |
if (result := cursor.fetchone()) and ( |
| 406 |
not (expires := result[1]) or expires > now): |
| 407 |
value, expires = result |
| 408 |
value = pickle.loads(value) |
| 409 |
else: |
| 410 |
value = func(*args) |
| 411 |
expires = _exp and _exp+now |
| 412 |
cursor.execute( |
| 413 |
"INSERT OR REPLACE INTO data VALUES (?,?,?)", |
| 414 |
(key, pickle.dumps(value), expires)) |
| 415 |
else: |
| 416 |
value = func(*args) |
| 417 |
expires = _exp and _exp+now |
| 418 |
|
| 419 |
CACHE_MEMORY[key] = value, expires |
| 420 |
return value |
| 421 |
|
| 422 |
def cache_update(self, func, key=..., value=None, _exp=0, _mem=False): |
| 423 |
if key is ...: |
| 424 |
key = f"{func.__module__}.{func.__name__}" |
| 425 |
else: |
| 426 |
key = f"{func.__module__}.{func.__name__}-{key}" |
| 427 |
|
| 428 |
if value is None: |
| 429 |
# delete cached value |
| 430 |
try: |
| 431 |
del CACHE_MEMORY[key] |
| 432 |
except KeyError: |
| 433 |
pass |
| 434 |
if not _mem and (db := cache.database()): |
| 435 |
with db: |
| 436 |
db.execute("DELETE FROM data WHERE key=?", (key,)) |
| 437 |
else: |
| 438 |
# replace cached value |
| 439 |
expires = _exp and _exp+int(time.time()) |
| 440 |
CACHE_MEMORY[key] = value, expires |
| 441 |
if not _mem and (db := cache.database()): |
| 442 |
with db: |
| 443 |
db.execute( |
| 444 |
"INSERT OR REPLACE INTO data VALUES (?,?,?)", |
| 445 |
(key, pickle.dumps(value), expires)) |
| 446 |
|
| 447 |
def input(self, prompt, echo=True): |
| 448 |
self._check_input_allowed(prompt) |
| 449 |
|
| 450 |
if echo: |
| 451 |
try: |
| 452 |
return input(prompt) |
| 453 |
except (EOFError, OSError): |
| 454 |
return None |
| 455 |
else: |
| 456 |
return getpass.getpass(prompt) |
| 457 |
|
| 458 |
def _check_input_allowed(self, prompt=""): |
| 459 |
input = self.config("input") |
| 460 |
if input is None: |
| 461 |
input = output.TTY_STDIN |
| 462 |
if not input: |
| 463 |
raise exception.AbortExtraction( |
| 464 |
f"User input required ({prompt.strip(' :')})") |
| 465 |
|
| 466 |
def _get_auth_info(self, password=None): |
| 467 |
"""Return authentication information as (username, password) tuple""" |
| 468 |
username = self.config("username") |
| 469 |
|
| 470 |
if username or password: |
| 471 |
password = self.config("password") |
| 472 |
if not password: |
| 473 |
self._check_input_allowed("password") |
| 474 |
password = util.LazyPrompt() |
| 475 |
|
| 476 |
elif self.config("netrc", False): |
| 477 |
try: |
| 478 |
info = netrc.netrc().authenticators(self.category) |
| 479 |
username, _, password = info |
| 480 |
except (OSError, netrc.NetrcParseError) as exc: |
| 481 |
self.log.error("netrc: %s", exc) |
| 482 |
except TypeError: |
| 483 |
self.log.warning("netrc: No authentication info") |
| 484 |
|
| 485 |
return username, password |
| 486 |
|
| 487 |
def _init(self): |
| 488 |
pass |
| 489 |
|
| 490 |
def _init_options(self): |
| 491 |
self._write_pages = self.config("write-pages", False) |
| 492 |
self._retry_codes = self.config("retry-codes") |
| 493 |
self._retries = self.config("retries", 4) |
| 494 |
self._timeout = self.config("timeout", 30) |
| 495 |
self._verify = self.config("verify", True) |
| 496 |
self._proxies = util.build_proxy_map(self.config("proxy"), self.log) |
| 497 |
|
| 498 |
if self._retries < 0: |
| 499 |
self._retries = float("inf") |
| 500 |
if not self._retry_codes: |
| 501 |
self._retry_codes = () |
| 502 |
|
| 503 |
self._interval_request = util.build_duration_func( |
| 504 |
self.config("sleep-request", self.request_interval), |
| 505 |
self.request_interval_min) |
| 506 |
|
| 507 |
_interval_retry = self.config("sleep-retries") |
| 508 |
if _interval_retry is None: |
| 509 |
self._interval_retry = util.identity |
| 510 |
else: |
| 511 |
try: |
| 512 |
self._interval_retry = util.build_duration_func_ex( |
| 513 |
_interval_retry) |
| 514 |
except Exception as exc: |
| 515 |
self.log.error("Invalid 'sleep-retry' value '%s' (%s: %s)", |
| 516 |
_interval_retry, exc.__class__.__name__, exc) |
| 517 |
self._interval_retry = util.identity |
| 518 |
|
| 519 |
_interval_429 = self.config("sleep-429") |
| 520 |
if _interval_429 is None: |
| 521 |
_interval_429 = self.request_interval_429 |
| 522 |
try: |
| 523 |
self._interval_429 = util.build_duration_func_ex(_interval_429) |
| 524 |
except Exception as exc: |
| 525 |
self.log.error("Invalid 'sleep-429' value '%s' (%s: %s)", |
| 526 |
_interval_429, exc.__class__.__name__, exc) |
| 527 |
self._interval_429 = util.build_duration_func_ex( |
| 528 |
self.request_interval_429) |
| 529 |
|
| 530 |
def _init_session(self): |
| 531 |
self.session = session = requests.Session() |
| 532 |
headers = session.headers |
| 533 |
headers.clear() |
| 534 |
ssl_options = ssl_ciphers = 0 |
| 535 |
|
| 536 |
# .netrc Authorization headers are always disabled |
| 537 |
session.trust_env = True if self.config("proxy-env", True) else False |
| 538 |
|
| 539 |
browser = self.config("browser") |
| 540 |
if browser is None: |
| 541 |
browser = self.browser |
| 542 |
if browser and isinstance(browser, str): |
| 543 |
browser, _, platform = browser.lower().partition(":") |
| 544 |
|
| 545 |
if not platform or platform == "auto": |
| 546 |
platform = ("Windows NT 10.0; Win64; x64" |
| 547 |
if util.WINDOWS else "X11; Linux x86_64") |
| 548 |
elif platform == "windows": |
| 549 |
platform = "Windows NT 10.0; Win64; x64" |
| 550 |
elif platform == "linux": |
| 551 |
platform = "X11; Linux x86_64" |
| 552 |
elif platform == "macos": |
| 553 |
platform = "Macintosh; Intel Mac OS X 15.5" |
| 554 |
|
| 555 |
if browser.startswith("chrome") and \ |
| 556 |
platform.startswith("Macintosh"): |
| 557 |
platform = platform.replace(".", "_") |
| 558 |
|
| 559 |
if browser not in HEADERS: |
| 560 |
self.log.warning("Unsupported browser %r. " |
| 561 |
"Falling back to 'firefox'", browser) |
| 562 |
browser = "firefox" |
| 563 |
|
| 564 |
for key, value in HEADERS[browser]: |
| 565 |
if value and "{}" in value: |
| 566 |
headers[key] = value.replace("{}", platform) |
| 567 |
else: |
| 568 |
headers[key] = value |
| 569 |
|
| 570 |
ssl_options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | |
| 571 |
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) |
| 572 |
ssl_ciphers = CIPHERS[browser] |
| 573 |
else: |
| 574 |
headers["User-Agent"] = self.useragent |
| 575 |
headers["Accept"] = "*/*" |
| 576 |
headers["Accept-Language"] = "en-US,en;q=0.5" |
| 577 |
|
| 578 |
ssl_ciphers = self.ciphers |
| 579 |
if ssl_ciphers is not None and ssl_ciphers in CIPHERS: |
| 580 |
ssl_ciphers = CIPHERS[ssl_ciphers] |
| 581 |
|
| 582 |
if BROTLI: |
| 583 |
headers["Accept-Encoding"] = "gzip, deflate, br" |
| 584 |
else: |
| 585 |
headers["Accept-Encoding"] = "gzip, deflate" |
| 586 |
if ZSTD: |
| 587 |
headers["Accept-Encoding"] += ", zstd" |
| 588 |
|
| 589 |
if referer := self.config("referer", self.referer): |
| 590 |
if isinstance(referer, str): |
| 591 |
headers["Referer"] = referer |
| 592 |
elif self.root: |
| 593 |
headers["Referer"] = self.root + "/" |
| 594 |
|
| 595 |
custom_ua = self.config("user-agent") |
| 596 |
if not custom_ua or custom_ua == "auto": |
| 597 |
pass |
| 598 |
elif custom_ua == "browser": |
| 599 |
headers["User-Agent"] = self.cache( |
| 600 |
_browser_useragent, None, _exp=86400, _mem=False) |
| 601 |
elif custom_ua[0] == "@": |
| 602 |
headers["User-Agent"] = self.cache( |
| 603 |
_browser_useragent, custom_ua[1:], _exp=86400, _mem=False) |
| 604 |
elif custom_ua[0] == "+": |
| 605 |
custom_ua = custom_ua[1:].lower() |
| 606 |
if custom_ua in {"firefox", "ff"}: |
| 607 |
headers["User-Agent"] = util.USERAGENT_FIREFOX |
| 608 |
elif custom_ua in {"chrome", "cr"}: |
| 609 |
headers["User-Agent"] = util.USERAGENT_CHROME |
| 610 |
elif custom_ua in {"gallery-dl", "gallerydl", "gdl"}: |
| 611 |
headers["User-Agent"] = util.USERAGENT_GALLERYDL |
| 612 |
elif custom_ua in {"google-bot", "googlebot", "bot"}: |
| 613 |
headers["User-Agent"] = "Googlebot-Image/1.0" |
| 614 |
else: |
| 615 |
self.log.warning( |
| 616 |
"Unsupported User-Agent preset '%s'", custom_ua) |
| 617 |
elif self.useragent is Extractor.useragent and not self.browser or \ |
| 618 |
custom_ua is not config.get(("extractor",), "user-agent"): |
| 619 |
headers["User-Agent"] = custom_ua |
| 620 |
|
| 621 |
custom_xff = self.config("geo-bypass") |
| 622 |
if custom_xff is None or custom_xff == "auto": |
| 623 |
custom_xff = self.geobypass |
| 624 |
if custom_xff is not None: |
| 625 |
if ip := self.utils("/geo").random_ipv4(custom_xff): |
| 626 |
headers["X-Forwarded-For"] = ip |
| 627 |
self.log.debug("Using fake IP %s as 'X-Forwarded-For'", ip) |
| 628 |
else: |
| 629 |
self.log.warning("xff: Invalid ISO 3166 country code '%s'", |
| 630 |
custom_xff) |
| 631 |
|
| 632 |
if custom_headers := self.config("headers"): |
| 633 |
if isinstance(custom_headers, str): |
| 634 |
if custom_headers in HEADERS: |
| 635 |
custom_headers = HEADERS[custom_headers] |
| 636 |
else: |
| 637 |
self.log.error("Invalid 'headers' value '%s'", |
| 638 |
custom_headers) |
| 639 |
custom_headers = () |
| 640 |
headers.update(custom_headers) |
| 641 |
|
| 642 |
if custom_ciphers := self.config("ciphers"): |
| 643 |
if isinstance(custom_ciphers, list): |
| 644 |
ssl_ciphers = ":".join(custom_ciphers) |
| 645 |
elif custom_ciphers in CIPHERS: |
| 646 |
ssl_ciphers = CIPHERS[custom_ciphers] |
| 647 |
else: |
| 648 |
ssl_ciphers = custom_ciphers |
| 649 |
|
| 650 |
if source_address := self.config("source-address"): |
| 651 |
if isinstance(source_address, str): |
| 652 |
source_address = (source_address, 0) |
| 653 |
else: |
| 654 |
source_address = (source_address[0], source_address[1]) |
| 655 |
|
| 656 |
tls12 = self.config("tls12") |
| 657 |
if tls12 is None: |
| 658 |
tls12 = self.tls12 |
| 659 |
if not tls12: |
| 660 |
ssl_options |= ssl.OP_NO_TLSv1_2 |
| 661 |
self.log.debug("TLS 1.2 disabled.") |
| 662 |
|
| 663 |
if self.config("truststore"): |
| 664 |
try: |
| 665 |
from truststore import SSLContext as ssl_ctx |
| 666 |
except ImportError as exc: |
| 667 |
self.log.error("%s: %s", exc.__class__.__name__, exc) |
| 668 |
ssl_ctx = None |
| 669 |
else: |
| 670 |
ssl_ctx = None |
| 671 |
|
| 672 |
adapter = _build_requests_adapter( |
| 673 |
ssl_options, ssl_ciphers, ssl_ctx, source_address) |
| 674 |
session.mount("https://", adapter) |
| 675 |
session.mount("http://", adapter) |
| 676 |
|
| 677 |
def _init_cookies(self): |
| 678 |
"""Populate the session's cookiejar""" |
| 679 |
if cookies := self.config("cookies"): |
| 680 |
if select := self.config("cookies-select"): |
| 681 |
if select == "rotate": |
| 682 |
cookies = cookies[self.cookies_index % len(cookies)] |
| 683 |
Extractor.cookies_index += 1 |
| 684 |
else: |
| 685 |
cookies = random.choice(cookies) |
| 686 |
self.cookies_load(cookies) |
| 687 |
|
| 688 |
def cookies_load(self, cookies_source): |
| 689 |
if isinstance(cookies_source, dict): |
| 690 |
self.cookies_update_dict(cookies_source, self.cookies_domain) |
| 691 |
|
| 692 |
elif isinstance(cookies_source, str): |
| 693 |
path = util.expand_path(cookies_source) |
| 694 |
try: |
| 695 |
with open(path, encoding="utf-8") as fp: |
| 696 |
cookies = util.cookiestxt_load(fp) |
| 697 |
except ValueError as exc: |
| 698 |
self.log.warning("cookies: Invalid Netscape cookies.txt file " |
| 699 |
"'%s' (%s: %s)", |
| 700 |
cookies_source, exc.__class__.__name__, exc) |
| 701 |
except Exception as exc: |
| 702 |
self.log.warning("cookies: Failed to load '%s' (%s: %s)", |
| 703 |
cookies_source, exc.__class__.__name__, exc) |
| 704 |
else: |
| 705 |
self.log.debug("cookies: Loading cookies from '%s'", |
| 706 |
cookies_source) |
| 707 |
set_cookie = self.cookies.set_cookie |
| 708 |
for cookie in cookies: |
| 709 |
set_cookie(cookie) |
| 710 |
self.cookies_file = path |
| 711 |
|
| 712 |
elif isinstance(cookies_source, (list, tuple)): |
| 713 |
key = tuple(cookies_source) |
| 714 |
cookies = CACHE_COOKIES.get(key) |
| 715 |
|
| 716 |
if cookies is None: |
| 717 |
from ..cookies import load_cookies |
| 718 |
try: |
| 719 |
cookies = load_cookies(cookies_source) |
| 720 |
except Exception as exc: |
| 721 |
self.log.warning("cookies: %s", exc) |
| 722 |
cookies = () |
| 723 |
else: |
| 724 |
CACHE_COOKIES[key] = cookies |
| 725 |
else: |
| 726 |
self.log.debug("cookies: Using cached cookies from %s", key) |
| 727 |
|
| 728 |
set_cookie = self.cookies.set_cookie |
| 729 |
for cookie in cookies: |
| 730 |
set_cookie(cookie) |
| 731 |
|
| 732 |
else: |
| 733 |
self.log.error( |
| 734 |
"cookies: Expected 'dict', 'list', or 'str' value for " |
| 735 |
"'cookies' option, got '%s' instead (%r)", |
| 736 |
cookies_source.__class__.__name__, cookies_source) |
| 737 |
|
| 738 |
def cookies_store(self): |
| 739 |
"""Store the session's cookies in a cookies.txt file""" |
| 740 |
export = self.config("cookies-update", True) |
| 741 |
if not export: |
| 742 |
return |
| 743 |
|
| 744 |
if isinstance(export, str): |
| 745 |
path = util.expand_path(export) |
| 746 |
else: |
| 747 |
path = self.cookies_file |
| 748 |
if not path: |
| 749 |
return |
| 750 |
|
| 751 |
path_tmp = path + ".tmp" |
| 752 |
try: |
| 753 |
with open(path_tmp, "w", encoding="utf-8") as fp: |
| 754 |
util.cookiestxt_store(fp, self.cookies) |
| 755 |
if util.SYMLINKS and os.path.islink(path): |
| 756 |
path = os.path.realpath(path) |
| 757 |
os.replace(path_tmp, path) |
| 758 |
except OSError as exc: |
| 759 |
self.log.error("cookies: Failed to write to '%s' " |
| 760 |
"(%s: %s)", path, exc.__class__.__name__, exc) |
| 761 |
|
| 762 |
def cookies_update(self, cookies, domain=""): |
| 763 |
"""Update the session's cookiejar with 'cookies'""" |
| 764 |
if isinstance(cookies, dict): |
| 765 |
self.cookies_update_dict(cookies, domain or self.cookies_domain) |
| 766 |
else: |
| 767 |
set_cookie = self.cookies.set_cookie |
| 768 |
try: |
| 769 |
cookies = iter(cookies) |
| 770 |
except TypeError: |
| 771 |
set_cookie(cookies) |
| 772 |
else: |
| 773 |
for cookie in cookies: |
| 774 |
set_cookie(cookie) |
| 775 |
|
| 776 |
def cookies_update_dict(self, cookiedict, domain): |
| 777 |
"""Update cookiejar with name-value pairs from a dict""" |
| 778 |
set_cookie = self.cookies.set |
| 779 |
for name, value in cookiedict.items(): |
| 780 |
set_cookie(name, value, domain=domain) |
| 781 |
|
| 782 |
def cookies_check(self, cookies_names, domain=None, subdomains=False): |
| 783 |
"""Check if all 'cookies_names' are in the session's cookiejar""" |
| 784 |
if not self.cookies: |
| 785 |
return False |
| 786 |
|
| 787 |
if domain is None: |
| 788 |
domain = self.cookies_domain |
| 789 |
names = set(cookies_names) |
| 790 |
now = time.time() |
| 791 |
|
| 792 |
for cookie in self.cookies: |
| 793 |
if cookie.name not in names: |
| 794 |
continue |
| 795 |
|
| 796 |
if not domain or cookie.domain == domain: |
| 797 |
pass |
| 798 |
elif not subdomains or not cookie.domain.endswith(domain): |
| 799 |
continue |
| 800 |
|
| 801 |
if cookie.expires: |
| 802 |
diff = int(cookie.expires - now) |
| 803 |
|
| 804 |
if diff <= 0: |
| 805 |
self.log.warning( |
| 806 |
"cookies: %s/%s expired at %s", |
| 807 |
cookie.domain.lstrip("."), cookie.name, |
| 808 |
dt.datetime.fromtimestamp(cookie.expires)) |
| 809 |
continue |
| 810 |
|
| 811 |
elif diff <= 86400: |
| 812 |
hours = diff // 3600 |
| 813 |
self.log.warning( |
| 814 |
"cookies: %s/%s will expire in less than %s hour%s", |
| 815 |
cookie.domain.lstrip("."), cookie.name, |
| 816 |
hours + 1, "s" if hours else "") |
| 817 |
|
| 818 |
names.discard(cookie.name) |
| 819 |
if not names: |
| 820 |
return True |
| 821 |
return False |
| 822 |
|
| 823 |
def _extract_jsonld(self, page): |
| 824 |
return util.json_loads( |
| 825 |
text.extr(page, '<script type="application/ld+json">', |
| 826 |
"</script>") or |
| 827 |
text.extr(page, "<script type='application/ld+json'>", |
| 828 |
"</script>")) |
| 829 |
|
| 830 |
def _extract_nextdata(self, page): |
| 831 |
pos = page.find(' id="__NEXT_DATA__"') |
| 832 |
if pos < 0: |
| 833 |
pos = page.find(" id='__NEXT_DATA__'") |
| 834 |
return util.json_loads( |
| 835 |
page[page.find(">", pos)+1:page.find("</script>", pos)]) |
| 836 |
|
| 837 |
def _extract_nuxtdata(self, page): |
| 838 |
pos = page.find(' id="__NUXT_DATA__"') |
| 839 |
if pos < 0: |
| 840 |
pos = page.find(" id='__NUXT_DATA__'") |
| 841 |
return self.utils("/nuxt").resolve(util.json_loads( |
| 842 |
page[page.find(">", pos)+1:page.find("</script>", pos)])) |
| 843 |
|
| 844 |
def _async_items_main(self): |
| 845 |
messages = queue.Queue(self._async_queue) |
| 846 |
thread = threading.Thread( |
| 847 |
target=self._async_items_thread, |
| 848 |
args=(messages,), |
| 849 |
daemon=True, |
| 850 |
) |
| 851 |
|
| 852 |
self._async_exception = None |
| 853 |
self.log.debug("Starting background thread") |
| 854 |
|
| 855 |
thread.start() |
| 856 |
while True: |
| 857 |
msg = messages.get() |
| 858 |
if msg is None: |
| 859 |
thread.join() |
| 860 |
if self._async_exception: |
| 861 |
raise self._async_exception |
| 862 |
return |
| 863 |
yield msg |
| 864 |
messages.task_done() |
| 865 |
|
| 866 |
def _async_items_thread(self, messages): |
| 867 |
try: |
| 868 |
for msg in self._async_items(): |
| 869 |
messages.put(msg) |
| 870 |
except Exception as exc: |
| 871 |
self._async_exception = exc |
| 872 |
messages.put(None) |
| 873 |
|
| 874 |
def _get_date_min_max(self, dmin=None, dmax=None): |
| 875 |
"""Retrieve and parse 'date-min' and 'date-max' config values""" |
| 876 |
def get(key, default): |
| 877 |
ts = self.config(key, default) |
| 878 |
if isinstance(ts, str): |
| 879 |
dt_obj = dt.parse_iso(ts) |
| 880 |
if dt_obj is dt.NONE: |
| 881 |
self.log.warning("Unable to parse '%s': Invalid ISO 8601 " |
| 882 |
"date/time value '%s'", key, ts) |
| 883 |
ts = default |
| 884 |
else: |
| 885 |
ts = int(dt.to_ts(dt_obj)) |
| 886 |
return ts |
| 887 |
if self.config("date-format"): |
| 888 |
self.log.error("'date-format' is no longer supported. " |
| 889 |
"Use ISO 8601 date/time values instead.") |
| 890 |
return get("date-min", dmin), get("date-max", dmax) |
| 891 |
|
| 892 |
def _dump_response(self, response, history=True): |
| 893 |
"""Write the response content to a .txt file in the current directory. |
| 894 |
|
| 895 |
The file name is derived from the response url, |
| 896 |
replacing special characters with "_" |
| 897 |
""" |
| 898 |
if history: |
| 899 |
for resp in response.history: |
| 900 |
self._dump_response(resp, False) |
| 901 |
|
| 902 |
if hasattr(Extractor, "_dump_index"): |
| 903 |
Extractor._dump_index += 1 |
| 904 |
else: |
| 905 |
Extractor._dump_index = 1 |
| 906 |
Extractor._dump_sanitize = util.re_compile( |
| 907 |
r"[\\\\|/<>:\"?*&=#]+").sub |
| 908 |
|
| 909 |
fname = (f"{Extractor._dump_index:>02}_" |
| 910 |
f"{Extractor._dump_sanitize('_', response.url)}") |
| 911 |
|
| 912 |
if util.WINDOWS: |
| 913 |
path = os.path.abspath(fname)[:255] |
| 914 |
else: |
| 915 |
path = fname[:251] |
| 916 |
|
| 917 |
try: |
| 918 |
with open(path + ".txt", 'wb') as fp: |
| 919 |
util.dump_response( |
| 920 |
response, fp, |
| 921 |
headers=(self._write_pages in {"all", "ALL"}), |
| 922 |
hide_auth=(self._write_pages != "ALL") |
| 923 |
) |
| 924 |
self.log.info("Writing '%s' response to '%s'", |
| 925 |
response.url, path + ".txt") |
| 926 |
except Exception as e: |
| 927 |
self.log.warning("Failed to dump HTTP request (%s: %s)", |
| 928 |
e.__class__.__name__, e) |
| 929 |
|
| 930 |
|
| 931 |
class GalleryExtractor(Extractor): |
| 932 |
|
| 933 |
subcategory = "gallery" |
| 934 |
filename_fmt = "{category}_{gallery_id}_{num:>03}.{extension}" |
| 935 |
directory_fmt = ("{category}", "{gallery_id} {title}") |
| 936 |
archive_fmt = "{gallery_id}_{num}" |
| 937 |
start = 1 |
| 938 |
enum = "num" |
| 939 |
|
| 940 |
def __init__(self, match, url=None): |
| 941 |
Extractor.__init__(self, match) |
| 942 |
|
| 943 |
if url is None and (path := self.groups[0]) and path[0] == "/": |
| 944 |
self.page_url = self.root + path |
| 945 |
else: |
| 946 |
self.page_url = url |
| 947 |
|
| 948 |
def items(self): |
| 949 |
self.login() |
| 950 |
|
| 951 |
if self.page_url: |
| 952 |
page = self.request( |
| 953 |
self.page_url, notfound=self.subcategory).text |
| 954 |
else: |
| 955 |
page = None |
| 956 |
|
| 957 |
data = self.metadata(page) |
| 958 |
imgs = self.images(page) |
| 959 |
assets = self.assets(page) |
| 960 |
|
| 961 |
if "count" in data: |
| 962 |
if self.config("page-reverse"): |
| 963 |
images = util.enumerate_reversed( |
| 964 |
imgs, self.start, data["count"]) |
| 965 |
else: |
| 966 |
images = zip( |
| 967 |
range(self.start, data["count"]+1), |
| 968 |
imgs, |
| 969 |
) |
| 970 |
else: |
| 971 |
enum = enumerate |
| 972 |
try: |
| 973 |
data["count"] = len(imgs) |
| 974 |
except TypeError: |
| 975 |
pass |
| 976 |
else: |
| 977 |
if self.config("page-reverse"): |
| 978 |
enum = util.enumerate_reversed |
| 979 |
images = enum(imgs, self.start) |
| 980 |
|
| 981 |
yield Message.Directory, "", data |
| 982 |
enum_key = self.enum |
| 983 |
|
| 984 |
if assets: |
| 985 |
for asset in assets: |
| 986 |
url = asset["url"] |
| 987 |
asset.update(data) |
| 988 |
asset[enum_key] = 0 |
| 989 |
if "extension" not in asset: |
| 990 |
text.nameext_from_url(url, asset) |
| 991 |
yield Message.Url, url, asset |
| 992 |
|
| 993 |
for data[enum_key], (url, imgdata) in images: |
| 994 |
if imgdata: |
| 995 |
data.update(imgdata) |
| 996 |
if "extension" not in imgdata: |
| 997 |
text.nameext_from_url(url, data) |
| 998 |
else: |
| 999 |
text.nameext_from_url(url, data) |
| 1000 |
yield Message.Url, url, data |
| 1001 |
|
| 1002 |
def login(self): |
| 1003 |
"""Login and set necessary cookies""" |
| 1004 |
|
| 1005 |
def metadata(self, page): |
| 1006 |
"""Return a dict with general metadata""" |
| 1007 |
|
| 1008 |
def images(self, page): |
| 1009 |
"""Return a list or iterable of all (image-url, metadata)-tuples""" |
| 1010 |
|
| 1011 |
def assets(self, page): |
| 1012 |
"""Return an iterable of additional gallery assets |
| 1013 |
|
| 1014 |
Each asset must be a 'dict' containing at least 'url' and 'type' |
| 1015 |
""" |
| 1016 |
|
| 1017 |
|
| 1018 |
class ChapterExtractor(GalleryExtractor): |
| 1019 |
|
| 1020 |
subcategory = "chapter" |
| 1021 |
directory_fmt = ( |
| 1022 |
"{category}", "{manga}", |
| 1023 |
"{volume:?v/ />02}c{chapter:>03}{chapter_minor:?//}{title:?: //}") |
| 1024 |
filename_fmt = ( |
| 1025 |
"{manga}_c{chapter:>03}{chapter_minor:?//}_{page:>03}.{extension}") |
| 1026 |
archive_fmt = ( |
| 1027 |
"{manga}_{chapter}{chapter_minor}_{page}") |
| 1028 |
enum = "page" |
| 1029 |
|
| 1030 |
|
| 1031 |
class MangaExtractor(Extractor): |
| 1032 |
|
| 1033 |
subcategory = "manga" |
| 1034 |
categorytransfer = True |
| 1035 |
chapterclass = None |
| 1036 |
reverse = True |
| 1037 |
|
| 1038 |
def __init__(self, match, url=None): |
| 1039 |
Extractor.__init__(self, match) |
| 1040 |
|
| 1041 |
if url is None and (path := self.groups[0]) and path[0] == "/": |
| 1042 |
self.page_url = self.root + path |
| 1043 |
else: |
| 1044 |
self.page_url = url |
| 1045 |
|
| 1046 |
if self.config("chapter-reverse", False): |
| 1047 |
self.reverse = not self.reverse |
| 1048 |
|
| 1049 |
def items(self): |
| 1050 |
self.login() |
| 1051 |
|
| 1052 |
if self.page_url: |
| 1053 |
page = self.request(self.page_url, notfound=self.subcategory).text |
| 1054 |
else: |
| 1055 |
page = None |
| 1056 |
|
| 1057 |
chapters = self.chapters(page) |
| 1058 |
if self.reverse: |
| 1059 |
chapters.reverse() |
| 1060 |
|
| 1061 |
for chapter, data in chapters: |
| 1062 |
data["_extractor"] = self.chapterclass |
| 1063 |
yield Message.Queue, chapter, data |
| 1064 |
|
| 1065 |
def login(self): |
| 1066 |
"""Login and set necessary cookies""" |
| 1067 |
|
| 1068 |
def chapters(self, page): |
| 1069 |
"""Return a list of all (chapter-url, metadata)-tuples""" |
| 1070 |
|
| 1071 |
|
| 1072 |
class Dispatch(): |
| 1073 |
subcategory = "user" |
| 1074 |
cookies_domain = None |
| 1075 |
finalize = Extractor.finalize |
| 1076 |
skip_files = None |
| 1077 |
|
| 1078 |
def __iter__(self): |
| 1079 |
return self.items() |
| 1080 |
|
| 1081 |
def initialize(self): |
| 1082 |
pass |
| 1083 |
|
| 1084 |
def _dispatch_extractors(self, extractor_data, default=(), alt=None): |
| 1085 |
extractors = { |
| 1086 |
data[0].subcategory: data |
| 1087 |
for data in extractor_data |
| 1088 |
} |
| 1089 |
|
| 1090 |
include = self.config("include", default) or () |
| 1091 |
if include == "all": |
| 1092 |
include = extractors |
| 1093 |
else: |
| 1094 |
if isinstance(include, str): |
| 1095 |
include = include.replace(" ", "").split(",") |
| 1096 |
if alt is not None: |
| 1097 |
for sub, sub_alt, url in alt: |
| 1098 |
extractors[sub_alt] = (extractors[sub] if url is None else |
| 1099 |
(extractors[sub][0], url)) |
| 1100 |
|
| 1101 |
results = [] |
| 1102 |
for category in include: |
| 1103 |
try: |
| 1104 |
extr, url = extractors[category] |
| 1105 |
except KeyError: |
| 1106 |
self.log.warning("Invalid include '%s'", category) |
| 1107 |
else: |
| 1108 |
results.append((Message.Queue, url, {"_extractor": extr})) |
| 1109 |
return iter(results) |
| 1110 |
|
| 1111 |
|
| 1112 |
class BaseExtractor(Extractor): |
| 1113 |
instances = () |
| 1114 |
|
| 1115 |
def __init__(self, match): |
| 1116 |
if not self.category: |
| 1117 |
self._init_category(match) |
| 1118 |
Extractor.__init__(self, match) |
| 1119 |
|
| 1120 |
def _init_category(self, match): |
| 1121 |
for index, group in enumerate(match.groups()): |
| 1122 |
if group is not None: |
| 1123 |
if index: |
| 1124 |
self.category, self.root, info = self.instances[index-1] |
| 1125 |
if not self.root: |
| 1126 |
self.root = text.root_from_url(match[0]) |
| 1127 |
self.config_instance = info.get |
| 1128 |
else: |
| 1129 |
self.root = group |
| 1130 |
self.category = group.partition("://")[2] |
| 1131 |
break |
| 1132 |
|
| 1133 |
@classmethod |
| 1134 |
def update(cls, instances): |
| 1135 |
if extra_instances := config.get(("extractor",), cls.basecategory): |
| 1136 |
for category, info in extra_instances.items(): |
| 1137 |
if isinstance(info, dict) and "root" in info: |
| 1138 |
instances[category] = info |
| 1139 |
|
| 1140 |
pattern_list = [] |
| 1141 |
instance_list = cls.instances = [] |
| 1142 |
for category, info in instances.items(): |
| 1143 |
if root := info["root"]: |
| 1144 |
root = root.rstrip("/") |
| 1145 |
instance_list.append((category, root, info)) |
| 1146 |
|
| 1147 |
pattern = info.get("pattern") |
| 1148 |
if not pattern: |
| 1149 |
pattern = re.escape(root[root.index(":") + 3:]) |
| 1150 |
pattern_list.append(pattern + "()") |
| 1151 |
|
| 1152 |
return (f"(?:{cls.basecategory}:(https?://[^/?#]+)|" |
| 1153 |
f"(?:https?://)?(?:{'|'.join(pattern_list)}))") |
| 1154 |
|
| 1155 |
|
| 1156 |
class RequestsAdapter(HTTPAdapter): |
| 1157 |
|
| 1158 |
def __init__(self, ssl_context=None, source_address=None): |
| 1159 |
self.ssl_context = ssl_context |
| 1160 |
self.source_address = source_address |
| 1161 |
HTTPAdapter.__init__(self) |
| 1162 |
|
| 1163 |
def init_poolmanager(self, *args, **kwargs): |
| 1164 |
kwargs["ssl_context"] = self.ssl_context |
| 1165 |
kwargs["source_address"] = self.source_address |
| 1166 |
return HTTPAdapter.init_poolmanager(self, *args, **kwargs) |
| 1167 |
|
| 1168 |
def proxy_manager_for(self, *args, **kwargs): |
| 1169 |
kwargs["ssl_context"] = self.ssl_context |
| 1170 |
kwargs["source_address"] = self.source_address |
| 1171 |
return HTTPAdapter.proxy_manager_for(self, *args, **kwargs) |
| 1172 |
|
| 1173 |
|
| 1174 |
def _build_requests_adapter( |
| 1175 |
ssl_options, ssl_ciphers, ssl_ctx, source_address): |
| 1176 |
|
| 1177 |
key = (ssl_options, ssl_ciphers, ssl_ctx, source_address) |
| 1178 |
try: |
| 1179 |
return CACHE_ADAPTERS[key] |
| 1180 |
except KeyError: |
| 1181 |
pass |
| 1182 |
|
| 1183 |
if ssl_options or ssl_ciphers or ssl_ctx: |
| 1184 |
if ssl_ctx is None: |
| 1185 |
ssl_context = urllib3.connection.create_urllib3_context( |
| 1186 |
options=ssl_options or None, ciphers=ssl_ciphers) |
| 1187 |
if not requests.__version__ < "2.32": |
| 1188 |
# https://github.com/psf/requests/pull/6731 |
| 1189 |
ssl_context.load_verify_locations(requests.certs.where()) |
| 1190 |
else: |
| 1191 |
ssl_ctx_orig = urllib3.util.ssl_.SSLContext |
| 1192 |
try: |
| 1193 |
urllib3.util.ssl_.SSLContext = ssl_ctx |
| 1194 |
ssl_context = urllib3.connection.create_urllib3_context( |
| 1195 |
options=ssl_options or None, ciphers=ssl_ciphers) |
| 1196 |
finally: |
| 1197 |
urllib3.util.ssl_.SSLContext = ssl_ctx_orig |
| 1198 |
ssl_context.check_hostname = False |
| 1199 |
else: |
| 1200 |
ssl_context = None |
| 1201 |
|
| 1202 |
adapter = CACHE_ADAPTERS[key] = RequestsAdapter( |
| 1203 |
ssl_context, source_address) |
| 1204 |
return adapter |
| 1205 |
|
| 1206 |
|
| 1207 |
def _browser_useragent(browser): |
| 1208 |
"""Get User-Agent header from default browser""" |
| 1209 |
import webbrowser |
| 1210 |
try: |
| 1211 |
open = webbrowser.get(browser).open |
| 1212 |
except webbrowser.Error: |
| 1213 |
if not browser: |
| 1214 |
raise |
| 1215 |
import shutil |
| 1216 |
if not (browser := shutil.which(browser)): |
| 1217 |
raise |
| 1218 |
|
| 1219 |
def open(url): |
| 1220 |
util.Popen((browser, url), |
| 1221 |
start_new_session=False if util.WINDOWS else True) |
| 1222 |
|
| 1223 |
import socket |
| 1224 |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1225 |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1226 |
server.bind(("127.0.0.1", 0)) |
| 1227 |
server.listen(1) |
| 1228 |
|
| 1229 |
host, port = server.getsockname() |
| 1230 |
open(f"http://{host}:{port}/user-agent") |
| 1231 |
|
| 1232 |
client = server.accept()[0] |
| 1233 |
server.close() |
| 1234 |
|
| 1235 |
for line in client.recv(1024).split(b"\r\n"): |
| 1236 |
key, _, value = line.partition(b":") |
| 1237 |
if key.strip().lower() == b"user-agent": |
| 1238 |
useragent = value.strip() |
| 1239 |
break |
| 1240 |
else: |
| 1241 |
useragent = b"" |
| 1242 |
|
| 1243 |
client.send(b"HTTP/1.1 200 OK\r\n\r\n" + useragent) |
| 1244 |
client.close() |
| 1245 |
|
| 1246 |
return useragent.decode() |
| 1247 |
|
| 1248 |
|
| 1249 |
CACHE_ADAPTERS = {} |
| 1250 |
CACHE_COOKIES = {} |
| 1251 |
CACHE_MEMORY = {} |
| 1252 |
CACHE_UTILS = {} |
| 1253 |
CATEGORY_MAP = () |
| 1254 |
|
| 1255 |
|
| 1256 |
HEADERS_FIREFOX_153 = ( |
| 1257 |
("User-Agent", "Mozilla/5.0 ({}; rv:153.0) Gecko/20100101 Firefox/153.0"), |
| 1258 |
("Accept", "text/html,application/xhtml+xml," |
| 1259 |
"application/xml;q=0.9,*/*;q=0.8"), |
| 1260 |
("Accept-Language", "en-US,en;q=0.9"), |
| 1261 |
("Accept-Encoding", None), |
| 1262 |
("Referer", None), |
| 1263 |
("Content-Type", None), |
| 1264 |
("Content-Length", None), |
| 1265 |
("Origin", None), |
| 1266 |
("Alt-Used", None), |
| 1267 |
("Connection", "keep-alive"), |
| 1268 |
("Cookie", None), |
| 1269 |
("Upgrade-Insecure-Requests", "1"), |
| 1270 |
("Sec-Fetch-Dest", "document"), |
| 1271 |
("Sec-Fetch-Mode", "navigate"), |
| 1272 |
("Sec-Fetch-Site", "same-site"), |
| 1273 |
# ("Sec-Fetch-User", "?1"), |
| 1274 |
("Priority", "u=0, i"), |
| 1275 |
("TE", "trailers"), |
| 1276 |
) |
| 1277 |
HEADERS_FIREFOX_140 = ( |
| 1278 |
("User-Agent", "Mozilla/5.0 ({}; rv:140.0) Gecko/20100101 Firefox/140.0"), |
| 1279 |
("Accept", "text/html,application/xhtml+xml," |
| 1280 |
"application/xml;q=0.9,*/*;q=0.8"), |
| 1281 |
("Accept-Language", "en-US,en;q=0.5"), |
| 1282 |
("Accept-Encoding", None), |
| 1283 |
("Connection", "keep-alive"), |
| 1284 |
("Content-Type", None), |
| 1285 |
("Content-Length", None), |
| 1286 |
("Referer", None), |
| 1287 |
("Origin", None), |
| 1288 |
("Cookie", None), |
| 1289 |
("Sec-Fetch-Dest", "empty"), |
| 1290 |
("Sec-Fetch-Mode", "cors"), |
| 1291 |
("Sec-Fetch-Site", "same-origin"), |
| 1292 |
("TE", "trailers"), |
| 1293 |
) |
| 1294 |
HEADERS_FIREFOX_128 = ( |
| 1295 |
("User-Agent", "Mozilla/5.0 ({}; rv:128.0) Gecko/20100101 Firefox/128.0"), |
| 1296 |
("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9," |
| 1297 |
"image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8"), |
| 1298 |
("Accept-Language", "en-US,en;q=0.5"), |
| 1299 |
("Accept-Encoding", None), |
| 1300 |
("Referer", None), |
| 1301 |
("Connection", "keep-alive"), |
| 1302 |
("Upgrade-Insecure-Requests", "1"), |
| 1303 |
("Cookie", None), |
| 1304 |
("Sec-Fetch-Dest", "empty"), |
| 1305 |
("Sec-Fetch-Mode", "no-cors"), |
| 1306 |
("Sec-Fetch-Site", "same-origin"), |
| 1307 |
("TE", "trailers"), |
| 1308 |
) |
| 1309 |
HEADERS_CHROMIUM_150 = ( |
| 1310 |
("Connection", "keep-alive"), |
| 1311 |
("sec-ch-ua", '"Not;A=Brand";v="8", "Chromium";v="150"'), |
| 1312 |
("sec-ch-ua-mobile", "?0"), |
| 1313 |
("sec-ch-ua-platform", '"Windows"'), |
| 1314 |
("Upgrade-Insecure-Requests", "1"), |
| 1315 |
("User-Agent", "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, " |
| 1316 |
"like Gecko) Chrome/150.0.0.0 Safari/537.36"), |
| 1317 |
("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9," |
| 1318 |
"image/avif,image/webp,image/apng,*/*;q=0.8," |
| 1319 |
"application/signed-exchange;v=b3;q=0.7"), |
| 1320 |
("Sec-Fetch-Site", "none"), |
| 1321 |
("Sec-Fetch-Mode", "navigate"), |
| 1322 |
# ("Sec-Fetch-User", "?1"), |
| 1323 |
("Sec-Fetch-Dest", "document"), |
| 1324 |
("Accept-Encoding", None), |
| 1325 |
("Accept-Language", "en-US,en;q=0.9"), |
| 1326 |
) |
| 1327 |
HEADERS_CHROMIUM_138 = ( |
| 1328 |
("Connection", "keep-alive"), |
| 1329 |
("sec-ch-ua", '"Not)A;Brand";v="8", "Chromium";v="138"'), |
| 1330 |
("sec-ch-ua-mobile", "?0"), |
| 1331 |
("sec-ch-ua-platform", '"Linux"'), |
| 1332 |
("Upgrade-Insecure-Requests", "1"), |
| 1333 |
("User-Agent", "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, " |
| 1334 |
"like Gecko) Chrome/138.0.0.0 Safari/537.36"), |
| 1335 |
("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9," |
| 1336 |
"image/avif,image/webp,image/apng,*/*;q=0.8," |
| 1337 |
"application/signed-exchange;v=b3;q=0.7"), |
| 1338 |
("Referer", None), |
| 1339 |
("Sec-Fetch-Site", "same-origin"), |
| 1340 |
("Sec-Fetch-Mode", "no-cors"), |
| 1341 |
# ("Sec-Fetch-User", "?1"), |
| 1342 |
("Sec-Fetch-Dest", "empty"), |
| 1343 |
("Accept-Encoding", None), |
| 1344 |
("Accept-Language", "en-US,en;q=0.9"), |
| 1345 |
) |
| 1346 |
HEADERS_CHROMIUM_111 = ( |
| 1347 |
("Connection", "keep-alive"), |
| 1348 |
("Upgrade-Insecure-Requests", "1"), |
| 1349 |
("User-Agent", "Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, " |
| 1350 |
"like Gecko) Chrome/111.0.0.0 Safari/537.36"), |
| 1351 |
("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9," |
| 1352 |
"image/avif,image/webp,image/apng,*/*;q=0.8," |
| 1353 |
"application/signed-exchange;v=b3;q=0.7"), |
| 1354 |
("Referer", None), |
| 1355 |
("Sec-Fetch-Site", "same-origin"), |
| 1356 |
("Sec-Fetch-Mode", "no-cors"), |
| 1357 |
("Sec-Fetch-Dest", "empty"), |
| 1358 |
("Accept-Encoding", None), |
| 1359 |
("Accept-Language", "en-US,en;q=0.9"), |
| 1360 |
("cookie", None), |
| 1361 |
("content-length", None), |
| 1362 |
) |
| 1363 |
HEADERS = { |
| 1364 |
"firefox" : HEADERS_FIREFOX_153, |
| 1365 |
"firefox/153": HEADERS_FIREFOX_153, |
| 1366 |
"firefox/140": HEADERS_FIREFOX_140, |
| 1367 |
"firefox/128": HEADERS_FIREFOX_128, |
| 1368 |
"chrome" : HEADERS_CHROMIUM_150, |
| 1369 |
"chrome/150" : HEADERS_CHROMIUM_150, |
| 1370 |
"chrome/138" : HEADERS_CHROMIUM_138, |
| 1371 |
"chrome/111" : HEADERS_CHROMIUM_111, |
| 1372 |
} |
| 1373 |
|
| 1374 |
CIPHERS_FIREFOX_153 = ( |
| 1375 |
"TLS_AES_128_GCM_SHA256:" |
| 1376 |
"TLS_CHACHA20_POLY1305_SHA256:" |
| 1377 |
"TLS_AES_256_GCM_SHA384:" |
| 1378 |
"ECDHE-ECDSA-AES128-GCM-SHA256:" |
| 1379 |
"ECDHE-RSA-AES128-GCM-SHA256:" |
| 1380 |
"ECDHE-ECDSA-CHACHA20-POLY1305:" |
| 1381 |
"ECDHE-RSA-CHACHA20-POLY1305:" |
| 1382 |
"ECDHE-ECDSA-AES256-GCM-SHA384:" |
| 1383 |
"ECDHE-RSA-AES256-GCM-SHA384:" |
| 1384 |
"ECDHE-ECDSA-AES256-SHA:" |
| 1385 |
"ECDHE-RSA-AES128-SHA:" |
| 1386 |
"ECDHE-RSA-AES256-SHA:" |
| 1387 |
"AES128-GCM-SHA256:" |
| 1388 |
"AES256-GCM-SHA384:" |
| 1389 |
"AES128-SHA:" |
| 1390 |
"AES256-SHA" |
| 1391 |
) |
| 1392 |
CIPHERS_FIREFOX_140 = ( |
| 1393 |
"TLS_AES_128_GCM_SHA256:" |
| 1394 |
"TLS_CHACHA20_POLY1305_SHA256:" |
| 1395 |
"TLS_AES_256_GCM_SHA384:" |
| 1396 |
"ECDHE-ECDSA-AES128-GCM-SHA256:" |
| 1397 |
"ECDHE-RSA-AES128-GCM-SHA256:" |
| 1398 |
"ECDHE-ECDSA-CHACHA20-POLY1305:" |
| 1399 |
"ECDHE-RSA-CHACHA20-POLY1305:" |
| 1400 |
"ECDHE-ECDSA-AES256-GCM-SHA384:" |
| 1401 |
"ECDHE-RSA-AES256-GCM-SHA384:" |
| 1402 |
"ECDHE-ECDSA-AES256-SHA:" |
| 1403 |
"ECDHE-ECDSA-AES128-SHA:" |
| 1404 |
"ECDHE-RSA-AES128-SHA:" |
| 1405 |
"ECDHE-RSA-AES256-SHA:" |
| 1406 |
"AES128-GCM-SHA256:" |
| 1407 |
"AES256-GCM-SHA384:" |
| 1408 |
"AES128-SHA:" |
| 1409 |
"AES256-SHA" |
| 1410 |
) |
| 1411 |
CIPHERS_CHROMIUM = ( |
| 1412 |
"TLS_AES_128_GCM_SHA256:" |
| 1413 |
"TLS_AES_256_GCM_SHA384:" |
| 1414 |
"TLS_CHACHA20_POLY1305_SHA256:" |
| 1415 |
"ECDHE-ECDSA-AES128-GCM-SHA256:" |
| 1416 |
"ECDHE-RSA-AES128-GCM-SHA256:" |
| 1417 |
"ECDHE-ECDSA-AES256-GCM-SHA384:" |
| 1418 |
"ECDHE-RSA-AES256-GCM-SHA384:" |
| 1419 |
"ECDHE-ECDSA-CHACHA20-POLY1305:" |
| 1420 |
"ECDHE-RSA-CHACHA20-POLY1305:" |
| 1421 |
"ECDHE-RSA-AES128-SHA:" |
| 1422 |
"ECDHE-RSA-AES256-SHA:" |
| 1423 |
"AES128-GCM-SHA256:" |
| 1424 |
"AES256-GCM-SHA384:" |
| 1425 |
"AES128-SHA:" |
| 1426 |
"AES256-SHA" |
| 1427 |
) |
| 1428 |
CIPHERS = { |
| 1429 |
"firefox" : CIPHERS_FIREFOX_153, |
| 1430 |
"firefox/153": CIPHERS_FIREFOX_153, |
| 1431 |
"firefox/140": CIPHERS_FIREFOX_140, |
| 1432 |
"firefox/128": CIPHERS_FIREFOX_140, |
| 1433 |
"chrome" : CIPHERS_CHROMIUM, |
| 1434 |
"chrome/150" : CIPHERS_CHROMIUM, |
| 1435 |
"chrome/138" : CIPHERS_CHROMIUM, |
| 1436 |
"chrome/111" : CIPHERS_CHROMIUM, |
| 1437 |
} |
| 1438 |
|
| 1439 |
|
| 1440 |
# disable Basic Authorization header injection from .netrc data |
| 1441 |
try: |
| 1442 |
requests.sessions.get_netrc_auth = lambda _: None |
| 1443 |
except Exception: |
| 1444 |
pass |
| 1445 |
|
| 1446 |
# detect brotli support |
| 1447 |
try: |
| 1448 |
BROTLI = urllib3.response.brotli is not None |
| 1449 |
except AttributeError: |
| 1450 |
BROTLI = False |
| 1451 |
|
| 1452 |
# detect zstandard support |
| 1453 |
try: |
| 1454 |
ZSTD = urllib3.response.HAS_ZSTD |
| 1455 |
except AttributeError: |
| 1456 |
ZSTD = False |
| 1457 |
|
| 1458 |
# set (urllib3) warnings filter |
| 1459 |
action = config.getg("warnings", "default") |
| 1460 |
if action: |
| 1461 |
try: |
| 1462 |
import warnings |
| 1463 |
warnings.simplefilter(action, urllib3.exceptions.HTTPWarning) |
| 1464 |
except Exception: |
| 1465 |
pass |
| 1466 |
del action |