Debian Codegraph @

gallery_dl/util.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017-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 """Utility functions and classes"""
10
11 import os
12 import sys
13 import json
14 import math
15 import time
16 import random
17 import getpass
18 import hashlib
19 import binascii
20 import functools
21 import itertools
22 import subprocess
23 import collections
24 import urllib.parse
25 from http.cookiejar import Cookie
26 from email.utils import mktime_tz, parsedate_tz
27 from . import text, dt, version, exception
28
29
30 def bencode(num, alphabet="0123456789"):
31 """Encode an integer into a base-N encoded string"""
32 data = ""
33 base = len(alphabet)
34 while num:
35 num, remainder = divmod(num, base)
36 data = alphabet[remainder] + data
37 return data
38
39
40 def bdecode(data, alphabet="0123456789"):
41 """Decode a base-N encoded string ( N = len(alphabet) )"""
42 num = 0
43 base = len(alphabet)
44 for c in data:
45 num = num * base + alphabet.find(c)
46 return num
47
48
49 def b36encode(num):
50 return bencode(num, "0123456789abcdefghijklmnopqrstuvwxyz")
51
52
53 def b36decode(data_base36):
54 return int(data_base36, 36) if data_base36 else 0
55
56
57 def b64encode(s):
58 return binascii.b2a_base64(s).rstrip(b"\n=").decode()
59
60
61 def b64rencode(s):
62 return binascii.b2a_base64(s, newline=False)
63
64
65 def b64decode(data_base64):
66 return binascii.a2b_base64(data_base64).decode()
67
68
69 b64rdecode = binascii.a2b_base64
70
71
72 def decrypt_xor(encrypted, key, base64=True, fromhex=False):
73 if base64:
74 encrypted = binascii.a2b_base64(encrypted)
75 if fromhex:
76 encrypted = bytes.fromhex(encrypted.decode())
77
78 div = len(key)
79 return bytes([
80 encrypted[i] ^ key[i % div]
81 for i in range(len(encrypted))
82 ]).decode()
83
84
85 def advance(iterable, num):
86 """"Advance 'iterable' by 'num' steps"""
87 iterator = iter(iterable)
88 next(itertools.islice(iterator, num, num), None)
89 return iterator
90
91
92 def repeat(times):
93 """Return an iterator that returns None"""
94 if times < 0:
95 return itertools.repeat(None)
96 return itertools.repeat(None, times)
97
98
99 def unique(iterable):
100 """Yield unique elements from 'iterable' while preserving order"""
101 seen = set()
102 add = seen.add
103 for element in iterable:
104 if element not in seen:
105 add(element)
106 yield element
107
108
109 def unique_sequence(iterable):
110 """Yield sequentially unique elements from 'iterable'"""
111 last = None
112 for element in iterable:
113 if element != last:
114 last = element
115 yield element
116
117
118 def contains(values, elements, separator=" "):
119 """Returns True if at least one of 'elements' is contained in 'values'"""
120 if isinstance(values, str) and (separator or separator is None):
121 values = values.split(separator)
122
123 if not isinstance(elements, (tuple, list)):
124 return elements in values
125
126 for e in elements:
127 if e in values:
128 return True
129 return False
130
131
132 def raises(cls):
133 """Returns a function that raises 'cls' as exception"""
134 def wrap(*args):
135 raise cls(*args)
136 return wrap
137
138
139 def identity(x, _=None):
140 """Returns its argument"""
141 return x
142
143
144 def true(_, __=None):
145 """Always returns True"""
146 return True
147
148
149 def false(_, __=None):
150 """Always returns False"""
151 return False
152
153
154 def noop(_=None):
155 """Does nothing"""
156
157
158 def md5(s):
159 """Generate MD5 hexdigest of 's'"""
160 if not s:
161 s = b""
162 elif isinstance(s, str):
163 s = s.encode()
164 return hashlib.md5(s).hexdigest()
165
166
167 def sha1(s):
168 """Generate SHA1 hexdigest of 's'"""
169 if not s:
170 s = b""
171 elif isinstance(s, str):
172 s = s.encode()
173 return hashlib.sha1(s).hexdigest()
174
175
176 def generate_token(size=16):
177 """Generate a random token with hexadecimal digits"""
178 return random.getrandbits(size * 8).to_bytes(size, "big").hex()
179
180
181 def format_bytes_decimal(value):
182 value = str(value)
183 value_len = len(value)
184 index = value_len - 4
185 if index >= 0:
186 offset = (value_len - 1) % 3 + 1
187 return (f"{value[:offset]}.{value[offset:offset+2]}"
188 f"{SUFFIXES[index // 3]}")
189 return value
190
191
192 def format_bytes_binary(value):
193 try:
194 index = int(math.log2(value) / 10)
195 return (str(value) if index < 1 else
196 f"{value/1024**index:.2f}{SUFFIXES[index-1]}i")
197 except Exception:
198 return "0"
199
200
201 def combine_dict(a, b):
202 """Recursively combine the contents of 'b' into 'a'"""
203 for key, value in b.items():
204 if key in a and isinstance(value, dict) and isinstance(a[key], dict):
205 combine_dict(a[key], value)
206 else:
207 a[key] = value
208 return a
209
210
211 def transform_dict(a, func):
212 """Recursively apply 'func' to all values in 'a'"""
213 for key, value in a.items():
214 if isinstance(value, dict):
215 transform_dict(value, func)
216 else:
217 a[key] = func(value)
218
219
220 def filter_dict(a):
221 """Return a copy of 'a' without "private" entries"""
222 return {k: v for k, v in a.items() if k[0] != "_"}
223
224
225 def delete_items(obj, keys):
226 """Remove all 'keys' from 'obj'"""
227 for key in keys:
228 if key in obj:
229 del obj[key]
230
231
232 def enumerate_reversed(iterable, start=0, length=None):
233 """Enumerate 'iterable' and return its elements in reverse order"""
234 if length is None:
235 length = len(iterable)
236
237 try:
238 iterable = zip(range(start-1+length, start-1, -1), reversed(iterable))
239 except TypeError:
240 iterable = list(zip(range(start, start+length), iterable))
241 iterable.reverse()
242
243 return iterable
244
245
246 def number_to_string(value, numbers=(int, float)):
247 """Convert numbers (int, float) to string; Return everything else as is."""
248 return str(value) if value.__class__ in numbers else value
249
250
251 def to_string(value):
252 """str() with "better" defaults"""
253 if not value:
254 return ""
255 if value.__class__ is list:
256 try:
257 return ", ".join(value)
258 except Exception:
259 return ", ".join(map(str, value))
260 return str(value)
261
262
263 def json_default(obj):
264 if isinstance(obj, CustomNone):
265 return None
266 return str(obj)
267
268
269 json_loads = json._default_decoder.decode
270 json_dumps = json.JSONEncoder(
271 check_circular=False,
272 separators=(",", ":"),
273 default=json_default,
274 ).encode
275
276
277 def dump_json(obj, fp=sys.stdout, ensure_ascii=True, indent=4):
278 """Serialize 'obj' as JSON and write it to 'fp'"""
279 json.dump(
280 obj, fp,
281 ensure_ascii=ensure_ascii,
282 indent=indent,
283 default=json_default,
284 sort_keys=True,
285 )
286 fp.write("\n")
287
288
289 def dump_response(response, fp, headers=False, content=True, hide_auth=True):
290 """Write the contents of 'response' into a file-like object"""
291
292 if headers:
293 request = response.request
294 req_headers = request.headers.copy()
295 res_headers = response.headers.copy()
296
297 if hide_auth:
298 if authorization := req_headers.get("Authorization"):
299 atype, sep, _ = str(authorization).partition(" ")
300 req_headers["Authorization"] = f"{atype} ***" if sep else "***"
301
302 if cookie := req_headers.get("Cookie"):
303 req_headers["Cookie"] = ";".join(
304 c.partition("=")[0] + "=***"
305 for c in cookie.split(";")
306 )
307
308 if set_cookie := res_headers.get("Set-Cookie"):
309 res_headers["Set-Cookie"] = re(r"(^|, )([^ =]+)=[^,;]*").sub(
310 r"\1\2=***", set_cookie)
311
312 request_headers = "\n".join(
313 f"{name}: {value}"
314 for name, value in req_headers.items()
315 )
316 response_headers = "\n".join(
317 f"{name}: {value}"
318 for name, value in res_headers.items()
319 )
320
321 output = f"""\
322 {request.method} {request.url}
323 Status: {response.status_code} {response.reason}
324
325 Request Headers
326 ---------------
327 {request_headers}
328 """
329 if request.body:
330 output = f"""{output}
331 Request Body
332 ------------
333 {request.body}
334 """
335 output = f"""{output}
336 Response Headers
337 ----------------
338 {response_headers}
339 """
340 fp.write(output.encode())
341
342 if content:
343 if headers:
344 fp.write(b"\nContent\n-------\n")
345 fp.write(response.content)
346
347
348 def extract_headers(response):
349 headers = response.headers
350 data = dict(headers)
351
352 if hcd := headers.get("content-disposition"):
353 if name := text.filename_from_contentdisposition(hcd):
354 text.nameext_from_name(name, data)
355
356 if hlm := headers.get("last-modified"):
357 data["date"] = dt.datetime(*parsedate_tz(hlm)[:6])
358
359 return data
360
361
362 def detect_challenge(response):
363 server = response.headers.get("server")
364 if not server:
365 return
366
367 elif server.startswith("cloudflare"):
368 if response.status_code not in (403, 503):
369 return
370
371 mitigated = response.headers.get("cf-mitigated")
372 if mitigated and mitigated.lower() == "challenge":
373 return "Cloudflare challenge"
374
375 content = response.content
376 if b"_cf_chl_opt" in content or b"jschl-answer" in content:
377 return "Cloudflare challenge"
378 elif b'name="captcha-bypass"' in content:
379 return "Cloudflare CAPTCHA"
380
381 elif server.startswith("ddos-guard"):
382 if response.status_code == 403 and \
383 b"/ddos-guard/js-challenge/" in response.content:
384 return "DDoS-Guard challenge"
385
386
387 @functools.lru_cache(maxsize=None)
388 def git_head():
389 try:
390 out, err = Popen(
391 ("git", "rev-parse", "--short", "HEAD"),
392 stdout=subprocess.PIPE,
393 stderr=subprocess.PIPE,
394 cwd=os.path.dirname(os.path.abspath(__file__)),
395 ).communicate()
396 if out and not err:
397 return out.decode().rstrip()
398 except (OSError, subprocess.SubprocessError):
399 pass
400 return None
401
402
403 def expand_path(path):
404 """Expand environment variables and tildes (~)"""
405 if not path:
406 return path
407 if not isinstance(path, str):
408 import logging
409 logging.getLogger("gallery-dl").error(
410 "Non-string paths are no longer supported.")
411 return os.path.expandvars(os.path.expanduser(path))
412
413
414 def remove_file(path):
415 try:
416 os.unlink(path)
417 except OSError:
418 pass
419
420
421 def remove_directory(path):
422 try:
423 os.rmdir(path)
424 except OSError:
425 pass
426
427
428 def set_mtime(path, mtime):
429 try:
430 if isinstance(mtime, str):
431 mtime = mktime_tz(parsedate_tz(mtime))
432 os.utime(path, (time.time(), mtime))
433 except Exception:
434 pass
435
436
437 def cookiestxt_load(fp):
438 """Parse a Netscape cookies.txt file and add return its Cookies"""
439 cookies = []
440
441 for line in fp:
442
443 line = line.lstrip(" ")
444 # strip '#HttpOnly_'
445 if line.startswith("#HttpOnly_"):
446 line = line[10:]
447 # ignore empty lines and comments
448 if not line or line[0] in ("#", "$", "\n"):
449 continue
450 # strip trailing '\n'
451 if line[-1] == "\n":
452 line = line[:-1]
453
454 domain, domain_specified, path, secure, expires, name, value = \
455 line.split("\t")
456
457 if not name:
458 name = value
459 value = None
460
461 cookies.append(Cookie(
462 0, name, value,
463 None, False,
464 domain,
465 domain_specified == "TRUE",
466 domain[0] == "." if domain else False,
467 path, False,
468 secure == "TRUE",
469 None if expires == "0" or not expires else expires,
470 False, None, None, {},
471 ))
472
473 return cookies
474
475
476 def cookiestxt_store(fp, cookies):
477 """Write 'cookies' in Netscape cookies.txt format to 'fp'"""
478 fp.write("# Netscape HTTP Cookie File\n\n")
479
480 for cookie in cookies:
481 if not cookie.domain:
482 continue
483
484 if cookie.value is None:
485 name = ""
486 value = cookie.name
487 else:
488 name = cookie.name
489 value = cookie.value
490
491 domain = cookie.domain
492 fp.write(
493 f"{domain}\t"
494 f"{'TRUE' if domain and domain[0] == '.' else 'FALSE'}\t"
495 f"{cookie.path}\t"
496 f"{'TRUE' if cookie.secure else 'FALSE'}\t"
497 f"{'0' if cookie.expires is None else str(cookie.expires)}\t"
498 f"{name}\t"
499 f"{value}\n"
500 )
501
502
503 def code_to_language(code, default=None):
504 """Map an ISO 639-1 language code to its actual name"""
505 return CODES.get((code or "").lower(), default)
506
507
508 def language_to_code(lang, default=None):
509 """Map a language name to its ISO 639-1 code"""
510 if lang is None:
511 return default
512 lang = lang.capitalize()
513 for code, language in CODES.items():
514 if language == lang:
515 return code
516 return default
517
518
519 CODES = {
520 "ar": "Arabic",
521 "bg": "Bulgarian",
522 "bn": "Bengali",
523 "ca": "Catalan",
524 "cs": "Czech",
525 "da": "Danish",
526 "de": "German",
527 "el": "Greek",
528 "en": "English",
529 "es": "Spanish",
530 "fa": "Persian",
531 "fi": "Finnish",
532 "fr": "French",
533 "he": "Hebrew",
534 "hi": "Hindi",
535 "hu": "Hungarian",
536 "id": "Indonesian",
537 "it": "Italian",
538 "ja": "Japanese",
539 "ko": "Korean",
540 "ms": "Malay",
541 "nl": "Dutch",
542 "no": "Norwegian",
543 "pl": "Polish",
544 "pt": "Portuguese",
545 "ro": "Romanian",
546 "ru": "Russian",
547 "sk": "Slovak",
548 "sl": "Slovenian",
549 "sr": "Serbian",
550 "sv": "Swedish",
551 "th": "Thai",
552 "tr": "Turkish",
553 "uk": "Ukrainian",
554 "vi": "Vietnamese",
555 "zh": "Chinese",
556 }
557
558
559 def HTTPBasicAuth(username, password, type=b"Basic"):
560 authorization = type + b" " + binascii.b2a_base64(
561 f"{username}:{password}".encode("utf-8"), newline=False)
562 del username, password
563
564 def _apply(request):
565 request.headers["Authorization"] = authorization
566 return request
567 return _apply
568
569
570 class ModuleProxy():
571 __slots__ = ()
572
573 def __getitem__(self, key, modules=sys.modules):
574 try:
575 return modules[key]
576 except KeyError:
577 pass
578 try:
579 __import__(key)
580 except ImportError:
581 modules[key] = NONE
582 return NONE
583 return modules[key]
584
585 __getattr__ = __getitem__
586
587
588 class LazyPrompt():
589 __slots__ = ()
590
591 def __str__(self):
592 return getpass.getpass()
593
594
595 class NullContext():
596 __slots__ = ()
597
598 def __enter__(self):
599 return None
600
601 def __exit__(self, exc_type, exc_value, traceback):
602 pass
603
604
605 class NullResponse():
606 __slots__ = ("url", "reason")
607
608 ok = is_redirect = is_permanent_redirect = False
609 cookies = headers = history = links = {}
610 encoding = apparent_encoding = "utf-8"
611 content = b""
612 text = ""
613 status_code = 900
614 close = noop
615
616 def __init__(self, url, reason=""):
617 self.url = url
618 self.reason = str(reason)
619
620 def __enter__(self):
621 return self
622
623 def __exit__(self, exc_type, exc_value, traceback):
624 pass
625
626 def __str__(self):
627 return "900 " + self.reason
628
629 def json(self):
630 return {}
631
632
633 class CustomNone():
634 """None-style type that supports more operations than regular None"""
635 __slots__ = ()
636
637 __getattribute__ = identity
638 __getitem__ = identity
639 __iter__ = identity
640
641 def __call__(self, *args, **kwargs):
642 return self
643
644 def __next__(self):
645 raise StopIteration
646
647 def __eq__(self, other):
648 return other is self or other is None
649
650 def __ne__(self, other):
651 return other is not self and other is not None
652
653 __lt__ = true
654 __le__ = true
655 __gt__ = false
656 __ge__ = false
657 __bool__ = false
658
659 __add__ = identity
660 __sub__ = identity
661 __mul__ = identity
662 __matmul__ = identity
663 __truediv__ = identity
664 __floordiv__ = identity
665 __mod__ = identity
666
667 __radd__ = identity
668 __rsub__ = identity
669 __rmul__ = identity
670 __rmatmul__ = identity
671 __rtruediv__ = identity
672 __rfloordiv__ = identity
673 __rmod__ = identity
674
675 __lshift__ = identity
676 __rshift__ = identity
677 __and__ = identity
678 __xor__ = identity
679 __or__ = identity
680
681 __rlshift__ = identity
682 __rrshift__ = identity
683 __rand__ = identity
684 __rxor__ = identity
685 __ror__ = identity
686
687 __neg__ = identity
688 __pos__ = identity
689 __abs__ = identity
690 __invert__ = identity
691
692 def __len__(self):
693 return 0
694
695 __int__ = __len__
696 __hash__ = __len__
697 __index__ = __len__
698
699 def __format__(self, _):
700 return "None"
701
702 def __str__(self):
703 return "None"
704
705 __repr__ = __str__
706
707
708 class Flags():
709
710 def __init__(self):
711 self.FILE = self.POST = self.CHILD = self.DOWNLOAD = None
712
713 clear = __init__
714
715 def process(self, flag):
716 value = self.__dict__[flag]
717 if value is False: # flag was set to "skip"
718 if flag == "DOWNLOAD":
719 self.DOWNLOAD = None
720 raise exception.StopDownload()
721 return "skip"
722 if value == "pause":
723 while self.__dict__[flag] is not None:
724 time.sleep(1)
725 return "pause"
726 self.__dict__[flag] = None
727
728 if value == "abort":
729 raise exception.AbortExtraction()
730 if value == "terminate":
731 raise exception.TerminateExtraction()
732 if value == "restart":
733 raise exception.RestartExtraction()
734 raise exception.StopExtraction()
735
736
737 # v137.0 release of Firefox on 2025-04-01 has ordinal 739342
738 # 735506 == 739342 - 137 * 28
739 # v135.0 release of Chrome on 2025-04-01 has ordinal 739342
740 # 735562 == 739342 - 135 * 28
741 # _ord_today = dt.date.today().toordinal()
742 # _ff_ver = (_ord_today - 735506) // 28
743 # _ch_ver = (_ord_today - 735562) // 28
744
745 _ord_today = dt.date.today().toordinal()
746 _ff_ver = (_ord_today - 735_534) // 28 # 153 on 2026-07-21
747 _ch_ver = (_ord_today - 735_597) // 28 # 150 on 2026-06-30
748
749 re = text.re
750 re_compile = text.re_compile
751
752 NONE = CustomNone()
753 FLAGS = Flags()
754 WINDOWS = (os.name == "nt")
755 SENTINEL = object()
756 SUFFIXES = "KMGTPEZY"
757 EXECUTABLE = getattr(sys, "frozen", False)
758 SPECIAL_EXTRACTORS = {"oauth", "recursive", "generic"}
759
760 EXTS_IMAGE = {"jpg", "jpeg", "png", "gif", "bmp", "svg", "psd", "ico",
761 "webp", "avif", "heic", "heif"}
762 EXTS_VIDEO = {"mp4", "m4v", "mov", "webm", "mkv", "ogv", "flv", "avi", "wmv"}
763 EXTS_ARCHIVE = {"zip", "rar", "7z", "tar", "gz", "bz2", "lzma", "xz"}
764
765 USERAGENT_GALLERYDL = "gallery-dl/" + version.__version__
766 USERAGENT_FIREFOX = (f"Mozilla/5.0 (Windows NT 10.0; Win64; x64; "
767 f"rv:{_ff_ver}.0) Gecko/20100101 Firefox/{_ff_ver}.0")
768 USERAGENT_CHROME = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
769 "AppleWebKit/537.36 (KHTML, like Gecko) "
770 f"Chrome/{_ch_ver}.0.0.0 Safari/537.36")
771
772 GLOBALS = {
773 "contains" : contains,
774 "parse_int": text.parse_int,
775 "urlsplit" : urllib.parse.urlsplit,
776 "datetime" : dt.datetime,
777 "timedelta": dt.timedelta,
778 "abort" : raises(exception.StopExtraction),
779 "error" : raises(exception.AbortExtraction),
780 "terminate": raises(exception.TerminateExtraction),
781 "restart" : raises(exception.RestartExtraction),
782 "hash_sha1": sha1,
783 "hash_md5" : md5,
784 "std" : ModuleProxy(),
785 "re" : text.re_module,
786 "exts_image" : EXTS_IMAGE,
787 "exts_video" : EXTS_VIDEO,
788 "exts_archive": EXTS_ARCHIVE,
789 }
790
791
792 if EXECUTABLE and hasattr(sys, "_MEIPASS"):
793 # https://github.com/pyinstaller/pyinstaller/blob/develop/doc
794 # /runtime-information.rst#ld_library_path--libpath-considerations
795 _popen_env = os.environ.copy()
796
797 orig = _popen_env.get("LD_LIBRARY_PATH_ORIG")
798 if orig is None:
799 _popen_env.pop("LD_LIBRARY_PATH", None)
800 else:
801 _popen_env["LD_LIBRARY_PATH"] = orig
802
803 orig = _popen_env.get("DYLD_LIBRARY_PATH_ORIG")
804 if orig is None:
805 _popen_env.pop("DYLD_LIBRARY_PATH", None)
806 else:
807 _popen_env["DYLD_LIBRARY_PATH"] = orig
808
809 del orig
810
811 def Popen(args, **kwargs):
812 kwargs["env"] = _popen_env
813 return subprocess.Popen(args, **kwargs)
814 else:
815 Popen = subprocess.Popen
816
817
818 def compile_expression_raw(expr, name="<expr>", globals=None):
819 code_object = compile(expr, name, "eval")
820 return functools.partial(eval, code_object, globals or GLOBALS)
821
822
823 def compile_expression_defaultdict(expr, name="<expr>", globals=None):
824 global GLOBALS_DEFAULT
825
826 if isinstance(__builtins__, dict):
827 # cpython
828 GLOBALS_DEFAULT = collections.defaultdict(lambda n=NONE: n, GLOBALS)
829 else:
830 # pypy3 - insert __builtins__ symbols into globals dict
831 GLOBALS_DEFAULT = collections.defaultdict(
832 lambda n=NONE: n, __builtins__.__dict__)
833 GLOBALS_DEFAULT.update(GLOBALS)
834
835 global compile_expression_defaultdict
836 compile_expression_defaultdict = compile_expression_defaultdict_impl
837 return compile_expression_defaultdict_impl(expr, name, globals)
838
839
840 def compile_expression_defaultdict_impl(expr, name="<expr>", globals=None):
841 code_object = compile(expr, name, "eval")
842 return functools.partial(eval, code_object, globals or GLOBALS_DEFAULT)
843
844
845 def compile_expression_tryexcept(expr, name="<expr>", globals=None):
846 code_object = compile(expr, name, "eval")
847 if globals is None:
848 globals = GLOBALS
849
850 def _eval(locals=None):
851 try:
852 return eval(code_object, globals, locals)
853 except exception.GalleryDLException:
854 raise
855 except Exception:
856 return NONE
857
858 return _eval
859
860
861 compile_expression = compile_expression_tryexcept
862
863
864 def compile_filter(expr, name="<filter>", globals=None):
865 if not isinstance(expr, str):
866 expr = f"({') and ('.join(expr)})"
867 return compile_expression(expr, name, globals)
868
869
870 def import_file(path):
871 """Import a Python module from a filesystem path"""
872 path, name = os.path.split(path)
873
874 name, sep, ext = name.rpartition(".")
875 if not sep:
876 name = ext
877
878 if path:
879 path = expand_path(path)
880 sys.path.insert(0, path)
881 try:
882 return __import__(name)
883 finally:
884 del sys.path[0]
885 else:
886 return __import__(name.replace("-", "_"))
887
888
889 def build_selection_func(value, min=0.0, conv=float):
890 if not value:
891 return (lambda: min) if min else None
892
893 if isinstance(value, str):
894 lower, _, upper = value.partition("-")
895 else:
896 try:
897 lower, upper = value
898 except TypeError:
899 lower = value
900 upper = None
901 lower = conv(lower)
902
903 if upper:
904 upper = conv(upper)
905 return functools.partial(
906 random.uniform if lower.__class__ is float else random.randint,
907 lower if lower > min else min,
908 upper if upper > min else min,
909 )
910 else:
911 if lower < min:
912 lower = min
913 return lambda: lower
914
915
916 build_duration_func = build_selection_func
917
918
919 def build_duration_func_ex(value):
920 if not value:
921 return None
922 if not isinstance(value, str) or "=" not in value:
923 value = build_duration_func(value)
924 return lambda _: value()
925
926 args, _, value = value.partition("=")
927 type, _, args = args.partition(":")
928 value = build_duration_func(value)
929
930 if "exponential".startswith(type):
931 if not args:
932 return lambda n: value() * (2 ** (n-1))
933 base, _, start = args.partition(":")
934 start, _, max = start.partition(":")
935 start = float(start) if start else 0
936 base = float(base) if base else 2
937 max = int(max) if max else 3600
938 return lambda n: min(start + value() * (base ** (n-1)), max)
939
940 if "linear".startswith(type):
941 if not args:
942 return lambda n: value() * n
943 start, _, max = args.partition(":")
944 start = float(start) if start else 0
945 max = int(max) if max else 3600
946 return lambda n: min(start + value() * n, max)
947
948 raise ValueError("Invalid duration type " + repr(type))
949
950
951 def build_extractor_filter(categories, negate=True, special=None):
952 """Build a function that takes an Extractor class as argument
953 and returns True if that class is allowed by 'categories'
954 """
955 if isinstance(categories, str):
956 categories = categories.split(",")
957
958 catset = set() # set of categories / basecategories
959 subset = set() # set of subcategories
960 catsub = [] # list of category-subcategory pairs
961
962 for item in categories:
963 category, _, subcategory = item.partition(":")
964 if category and category != "*":
965 if subcategory and subcategory != "*":
966 catsub.append((category, subcategory))
967 else:
968 catset.add(category)
969 elif subcategory and subcategory != "*":
970 subset.add(subcategory)
971
972 if special:
973 catset |= special
974 elif not catset and not subset and not catsub:
975 return true if negate else false
976
977 tests = []
978
979 if negate:
980 if catset:
981 tests.append(lambda extr:
982 extr.category not in catset and
983 extr.basecategory not in catset)
984 if subset:
985 tests.append(lambda extr: extr.subcategory not in subset)
986 else:
987 if catset:
988 tests.append(lambda extr:
989 extr.category in catset or
990 extr.basecategory in catset)
991 if subset:
992 tests.append(lambda extr: extr.subcategory in subset)
993
994 if catsub:
995 def test(extr):
996 for category, subcategory in catsub:
997 if subcategory == extr.subcategory and (
998 category == extr.category or
999 category == extr.basecategory):
1000 return not negate
1001 return negate
1002 tests.append(test)
1003
1004 if len(tests) == 1:
1005 return tests[0]
1006 if negate:
1007 return lambda extr: all(t(extr) for t in tests)
1008 else:
1009 return lambda extr: any(t(extr) for t in tests)
1010
1011
1012 def build_proxy_map(proxies, log=None):
1013 """Generate a proxy map"""
1014 if not proxies:
1015 return None
1016
1017 if isinstance(proxies, str):
1018 if "://" not in proxies:
1019 proxies = "http://" + proxies.lstrip("/")
1020 proxies = {"http": proxies, "https": proxies}
1021 elif isinstance(proxies, dict):
1022 for scheme, proxy in proxies.items():
1023 if "://" not in proxy:
1024 proxies[scheme] = "http://" + proxy.lstrip("/")
1025 else:
1026 proxies = None
1027
1028 if log is not None:
1029 if proxies is None:
1030 log.warning("Invalid proxy specifier: %r", proxies)
1031 else:
1032 log.debug("Proxy Map: %s", proxies)
1033
1034 return proxies
1035
1036
1037 def predicate_build(predicates):
1038 if not predicates:
1039 return true
1040
1041 if len(predicates) == 1:
1042 return predicates[0]
1043
1044 def chain(url, kwdict):
1045 for pred in predicates:
1046 if not pred(url, kwdict):
1047 return False
1048 return True
1049 return chain
1050
1051
1052 def predicate_unique():
1053 """Predicate; True if given URL has not been encountered before"""
1054 def _pred(url, _):
1055 if url.startswith("text:"):
1056 return True
1057 if url not in urls:
1058 urls.add(url)
1059 return True
1060 return False
1061 urls = set()
1062 return _pred
1063
1064
1065 def predicate_filter(expr, target="image"):
1066 """Predicate; True if evaluating the given expression returns True"""
1067 def _pred(_, kwdict):
1068 try:
1069 return expr(kwdict)
1070 except exception.GalleryDLException:
1071 raise
1072 except Exception as exc:
1073 raise exception.FilterError(exc)
1074 expr = compile_filter(expr, f"<{target} filter>")
1075 return _pred
1076
1077
1078 def predicate_tags(blacklist, negate=False):
1079 def _pred(_, kwdict):
1080 if not (tags := kwdict.get("tags") or kwdict.get("tag_string")):
1081 return True
1082
1083 if isinstance(tags, str):
1084 taglist = tags.split(", ")
1085 if len(taglist) < len(tags) / 16:
1086 taglist = tags.split(" ")
1087 tags = taglist
1088 elif isinstance(tags[0], dict):
1089 # pixiv "tags": "original"
1090 tags = [
1091 tag
1092 for tagdict in tags
1093 for tag in tagdict.values()
1094 if isinstance(tag, str)
1095 ]
1096
1097 for tag in tags:
1098 if tag in simple:
1099 return negate
1100 if complex is not None:
1101 for check in complex:
1102 if check(tags):
1103 return negate
1104 return not negate
1105 simple, complex = predicate_tags_parse(blacklist)
1106 return _pred
1107
1108
1109 def predicate_tags_parse(blacklist):
1110 if isinstance(blacklist, str):
1111 try:
1112 with open(expand_path(blacklist)) as fp:
1113 blacklist = fp.readlines()
1114 except OSError:
1115 blacklist = blacklist.split(",")
1116
1117 simple = set()
1118 complex = []
1119
1120 for line in blacklist:
1121 line = line.strip()
1122 if not line or line.startswith("# "):
1123 # empty or comment
1124 continue
1125 line = line.lower()
1126
1127 if " " in line:
1128 Or = []
1129 And = []
1130 for tag in line.split():
1131 if tag[0] == "~":
1132 Or.append(tag[1:])
1133 elif tag[0] == "-":
1134 And.append(predicate_tags_not(tag[1:]))
1135 else:
1136 And.append(predicate_tags_in(tag))
1137 if Or:
1138 And.append("")
1139 for tag in Or:
1140 And[-1] = predicate_tags_in(tag)
1141 complex.append(predicate_tags_chain(And.copy()))
1142 else:
1143 complex.append(predicate_tags_chain(And))
1144
1145 elif line[0] in "-~":
1146 if line[0] == "~":
1147 simple.add(line[1:])
1148 else:
1149 complex.append(predicate_tags_not(line[1:]))
1150 else:
1151 simple.add(line)
1152
1153 return simple, complex or None
1154
1155
1156 def predicate_tags_in(tag):
1157 return lambda tags: tag in tags
1158
1159
1160 def predicate_tags_not(tag):
1161 return lambda tags: tag not in tags
1162
1163
1164 def predicate_tags_chain(checks):
1165 def chain(tags):
1166 for check in checks:
1167 if not check(tags):
1168 return False
1169 return True
1170 return chain
1171
1172
1173 def predicate_date(before, after=None, skip=None):
1174 if after is None:
1175 if skip is not None and skip(before):
1176 return true
1177
1178 def _pred(_, kwdict):
1179 if (date := kwdict.get("date")) and date >= before:
1180 return False
1181 return True
1182
1183 elif before is None or after > before or skip is not None and skip(before):
1184 def _pred(_, kwdict):
1185 if (date := kwdict.get("date")) and date <= after:
1186 raise exception.StopExtraction()
1187 return True
1188
1189 else:
1190 def _pred(_, kwdict):
1191 if not (date := kwdict.get("date")):
1192 return True
1193 if date <= after:
1194 raise exception.StopExtraction()
1195 return date < before
1196 return _pred
1197
1198
1199 def predicate_range(ranges, skip=None, flag=None):
1200 """Predicate; True if the current index is in the given range(s)"""
1201 if ranges := predicate_range_parse(ranges):
1202 # technically wrong for 'step > 2', but good enough for now
1203 # and evaluating min/max for a large range is slow
1204 upper = max(r.stop for r in ranges) - 1
1205 lower = min(r.start for r in ranges)
1206 index = 0 if skip is None or lower <= 1 else skip(lower - 1)
1207 del lower
1208 else:
1209 index = upper = 0
1210
1211 if flag is None:
1212 def _pred(_url, _kwdict):
1213 nonlocal index
1214
1215 if index >= upper:
1216 raise exception.StopExtraction()
1217 index += 1
1218
1219 for range in ranges:
1220 if index in range:
1221 return True
1222 return False
1223 else:
1224 def _pred(_url, _kwdict):
1225 nonlocal index
1226
1227 index += 1
1228 if index >= upper:
1229 if index > upper:
1230 raise exception.StopExtraction()
1231 FLAGS.__dict__[flag.upper()] = "stop"
1232
1233 for range in ranges:
1234 if index in range:
1235 return True
1236 return False
1237 return _pred
1238
1239
1240 def predicate_range_parse(rangespec):
1241 """Parse an integer range string and return the resulting ranges
1242
1243 Examples:
1244 _parse("-2,4,6-8,10-") -> [(1,3), (4,5), (6,9), (10,INTMAX)]
1245 _parse(" - 3 , 4- 4, 2-6") -> [(1,4), (4,5), (2,7)]
1246 _parse("1:2,4:8:2") -> [(1,1), (4,7,2)]
1247 """
1248 ranges = []
1249
1250 if isinstance(rangespec, str):
1251 rangespec = rangespec.split(",")
1252 elif isinstance(rangespec, int):
1253 rangespec = (str(rangespec),)
1254
1255 for group in rangespec:
1256 if not group:
1257 continue
1258
1259 elif ":" in group:
1260 start, _, stop = group.partition(":")
1261 stop, _, step = stop.partition(":")
1262 ranges.append(range(
1263 int(start) if start.strip() else 1,
1264 int(stop) if stop.strip() else sys.maxsize,
1265 int(step) if step.strip() else 1,
1266 ))
1267
1268 elif "-" in group:
1269 start, _, stop = group.partition("-")
1270 ranges.append(range(
1271 int(start) if start.strip() else 1,
1272 int(stop) + 1 if stop.strip() else sys.maxsize,
1273 ))
1274
1275 else:
1276 start = int(group)
1277 ranges.append(range(start, start+1))
1278
1279 return ranges