Debian Codegraph @

gallery_dl/util.py

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