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 SYMLINKS = False
766 SUFFIXES = "KMGTPEZY"
767 EXECUTABLE = getattr(sys, "frozen", False)
768 SPECIAL_EXTRACTORS = {"oauth", "recursive", "generic"}
769
770 EXTS_IMAGE = {"jpg", "jpeg", "png", "gif", "bmp", "svg", "psd", "ico",
771 "webp", "avif", "heic", "heif"}
772 EXTS_VIDEO = {"mp4", "m4v", "mov", "webm", "mkv", "ogv", "flv", "avi", "wmv"}
773 EXTS_ARCHIVE = {"zip", "rar", "7z", "tar", "gz", "bz2", "lzma", "xz"}
774
775 USERAGENT_GALLERYDL = "gallery-dl/" + version.__version__
776 USERAGENT_FIREFOX = (f"Mozilla/5.0 (Windows NT 10.0; Win64; x64; "
777 f"rv:{_ff_ver}.0) Gecko/20100101 Firefox/{_ff_ver}.0")
778 USERAGENT_CHROME = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
779 "AppleWebKit/537.36 (KHTML, like Gecko) "
780 f"Chrome/{_ch_ver}.0.0.0 Safari/537.36")
781
782 GLOBALS = {
783 "contains" : contains,
784 "parse_int": text.parse_int,
785 "urlsplit" : urllib.parse.urlsplit,
786 "datetime" : dt.datetime,
787 "timedelta": dt.timedelta,
788 "abort" : raises(exception.StopExtraction),
789 "error" : raises(exception.AbortExtraction),
790 "terminate": raises(exception.TerminateExtraction),
791 "restart" : raises(exception.RestartExtraction),
792 "hash_sha1": sha1,
793 "hash_md5" : md5,
794 "std" : ModuleProxy(),
795 "re" : text.re_module,
796 "exts_image" : EXTS_IMAGE,
797 "exts_video" : EXTS_VIDEO,
798 "exts_archive": EXTS_ARCHIVE,
799 }
800
801
802 if EXECUTABLE and hasattr(sys, "_MEIPASS"):
803 # https://github.com/pyinstaller/pyinstaller/blob/develop/doc
804 # /runtime-information.rst#ld_library_path--libpath-considerations
805 _popen_env = os.environ.copy()
806
807 orig = _popen_env.get("LD_LIBRARY_PATH_ORIG")
808 if orig is None:
809 _popen_env.pop("LD_LIBRARY_PATH", None)
810 else:
811 _popen_env["LD_LIBRARY_PATH"] = orig
812
813 orig = _popen_env.get("DYLD_LIBRARY_PATH_ORIG")
814 if orig is None:
815 _popen_env.pop("DYLD_LIBRARY_PATH", None)
816 else:
817 _popen_env["DYLD_LIBRARY_PATH"] = orig
818
819 del orig
820
821 def Popen(args, **kwargs):
822 kwargs["env"] = _popen_env
823 return subprocess.Popen(args, **kwargs)
824 else:
825 Popen = subprocess.Popen
826
827
828 def compile_expression_raw(expr, name="<expr>", globals=None):
829 code_object = compile(expr, name, "eval")
830 return functools.partial(eval, code_object, globals or GLOBALS)
831
832
833 def compile_expression_defaultdict(expr, name="<expr>", globals=None):
834 global GLOBALS_DEFAULT
835
836 if isinstance(__builtins__, dict):
837 # cpython
838 GLOBALS_DEFAULT = collections.defaultdict(lambda n=NONE: n, GLOBALS)
839 else:
840 # pypy3 - insert __builtins__ symbols into globals dict
841 GLOBALS_DEFAULT = collections.defaultdict(
842 lambda n=NONE: n, __builtins__.__dict__)
843 GLOBALS_DEFAULT.update(GLOBALS)
844
845 global compile_expression_defaultdict
846 compile_expression_defaultdict = compile_expression_defaultdict_impl
847 return compile_expression_defaultdict_impl(expr, name, globals)
848
849
850 def compile_expression_defaultdict_impl(expr, name="<expr>", globals=None):
851 code_object = compile(expr, name, "eval")
852 return functools.partial(eval, code_object, globals or GLOBALS_DEFAULT)
853
854
855 def compile_expression_tryexcept(expr, name="<expr>", globals=None):
856 code_object = compile(expr, name, "eval")
857 if globals is None:
858 globals = GLOBALS
859
860 def _eval(locals=None):
861 try:
862 return eval(code_object, globals, locals)
863 except exception.GalleryDLException:
864 raise
865 except Exception:
866 return NONE
867
868 return _eval
869
870
871 compile_expression = compile_expression_tryexcept
872
873
874 def compile_filter(expr, name="<filter>", globals=None):
875 if not isinstance(expr, str):
876 expr = f"({') and ('.join(expr)})"
877 return compile_expression(expr, name, globals)
878
879
880 def import_file(path):
881 """Import a Python module from a filesystem path"""
882 path, name = os.path.split(path)
883
884 name, sep, ext = name.rpartition(".")
885 if not sep:
886 name = ext
887
888 if path:
889 path = expand_path(path)
890 sys.path.insert(0, path)
891 try:
892 return __import__(name)
893 finally:
894 del sys.path[0]
895 else:
896 return __import__(name.replace("-", "_"))
897
898
899 def build_selection_func(value, min=0.0, conv=float):
900 if not value:
901 return (lambda: min) if min else None
902
903 if isinstance(value, str):
904 lower, _, upper = value.partition("-")
905 else:
906 try:
907 lower, upper = value
908 except TypeError:
909 lower = value
910 upper = None
911 lower = conv(lower)
912
913 if upper:
914 upper = conv(upper)
915 return functools.partial(
916 random.uniform if lower.__class__ is float else random.randint,
917 lower if lower > min else min,
918 upper if upper > min else min,
919 )
920 else:
921 if lower < min:
922 lower = min
923 return lambda: lower
924
925
926 build_duration_func = build_selection_func
927
928
929 def build_duration_func_ex(value):
930 if not value:
931 return None
932 if not isinstance(value, str) or "=" not in value:
933 value = build_duration_func(value)
934 return lambda _: value()
935
936 args, _, value = value.partition("=")
937 type, _, args = args.partition(":")
938 value = build_duration_func(value)
939
940 if "exponential".startswith(type):
941 if not args:
942 return lambda n: value() * (2 ** (n-1))
943 base, _, start = args.partition(":")
944 start, _, max = start.partition(":")
945 start = float(start) if start else 0
946 base = float(base) if base else 2
947 max = int(max) if max else 3600
948 return lambda n: min(start + value() * (base ** (n-1)), max)
949
950 if "linear".startswith(type):
951 if not args:
952 return lambda n: value() * n
953 start, _, max = args.partition(":")
954 start = float(start) if start else 0
955 max = int(max) if max else 3600
956 return lambda n: min(start + value() * n, max)
957
958 raise ValueError("Invalid duration type " + repr(type))
959
960
961 def build_extractor_filter(categories, negate=True, special=None):
962 """Build a function that takes an Extractor class as argument
963 and returns True if that class is allowed by 'categories'
964 """
965 if isinstance(categories, str):
966 categories = categories.split(",")
967
968 catset = set() # set of categories / basecategories
969 subset = set() # set of subcategories
970 catsub = [] # list of category-subcategory pairs
971
972 for item in categories:
973 category, _, subcategory = item.partition(":")
974 if category and category != "*":
975 if subcategory and subcategory != "*":
976 catsub.append((category, subcategory))
977 else:
978 catset.add(category)
979 elif subcategory and subcategory != "*":
980 subset.add(subcategory)
981
982 if special:
983 catset |= special
984 elif not catset and not subset and not catsub:
985 return true if negate else false
986
987 tests = []
988
989 if negate:
990 if catset:
991 tests.append(lambda extr:
992 extr.category not in catset and
993 extr.basecategory not in catset)
994 if subset:
995 tests.append(lambda extr: extr.subcategory not in subset)
996 else:
997 if catset:
998 tests.append(lambda extr:
999 extr.category in catset or
1000 extr.basecategory in catset)
1001 if subset:
1002 tests.append(lambda extr: extr.subcategory in subset)
1003
1004 if catsub:
1005 def test(extr):
1006 for category, subcategory in catsub:
1007 if subcategory == extr.subcategory and (
1008 category == extr.category or
1009 category == extr.basecategory):
1010 return not negate
1011 return negate
1012 tests.append(test)
1013
1014 if len(tests) == 1:
1015 return tests[0]
1016 if negate:
1017 return lambda extr: all(t(extr) for t in tests)
1018 else:
1019 return lambda extr: any(t(extr) for t in tests)
1020
1021
1022 def build_proxy_map(proxies, log=None):
1023 """Generate a proxy map"""
1024 if not proxies:
1025 return None
1026
1027 if isinstance(proxies, str):
1028 if "://" not in proxies:
1029 proxies = "http://" + proxies.lstrip("/")
1030 proxies = {"http": proxies, "https": proxies}
1031 elif isinstance(proxies, dict):
1032 for scheme, proxy in proxies.items():
1033 if "://" not in proxy:
1034 proxies[scheme] = "http://" + proxy.lstrip("/")
1035 else:
1036 proxies = None
1037
1038 if log is not None:
1039 if proxies is None:
1040 log.warning("Invalid proxy specifier: %r", proxies)
1041 else:
1042 log.debug("Proxy Map: %s", proxies)
1043
1044 return proxies
1045
1046
1047 def predicate_build(predicates):
1048 if not predicates:
1049 return true
1050
1051 if len(predicates) == 1:
1052 return predicates[0]
1053
1054 def chain(url, kwdict):
1055 for pred in predicates:
1056 if not pred(url, kwdict):
1057 return False
1058 return True
1059 return chain
1060
1061
1062 def predicate_unique():
1063 """Predicate; True if given URL has not been encountered before"""
1064 def _pred(url, _):
1065 if url.startswith("text:"):
1066 return True
1067 if url not in urls:
1068 urls.add(url)
1069 return True
1070 return False
1071 urls = set()
1072 return _pred
1073
1074
1075 def predicate_filter(expr, target="image"):
1076 """Predicate; True if evaluating the given expression returns True"""
1077 def _pred(_, kwdict):
1078 try:
1079 return expr(kwdict)
1080 except exception.GalleryDLException:
1081 raise
1082 except Exception as exc:
1083 raise exception.FilterError(exc)
1084 expr = compile_filter(expr, f"<{target} filter>")
1085 return _pred
1086
1087
1088 def predicate_tags(blacklist, negate=False):
1089 def _pred(_, kwdict):
1090 if not (tags := kwdict.get("tags") or kwdict.get("tag_string")):
1091 return True
1092
1093 if isinstance(tags, str):
1094 taglist = tags.split(", ")
1095 if len(taglist) < len(tags) / 16:
1096 taglist = tags.split(" ")
1097 tags = taglist
1098 elif isinstance(tags[0], dict):
1099 # pixiv "tags": "original"
1100 tags = [
1101 tag
1102 for tagdict in tags
1103 for tag in tagdict.values()
1104 if isinstance(tag, str)
1105 ]
1106
1107 for tag in tags:
1108 if tag in simple:
1109 return negate
1110 if complex is not None:
1111 for check in complex:
1112 if check(tags):
1113 return negate
1114 return not negate
1115 simple, complex = predicate_tags_parse(blacklist)
1116 return _pred
1117
1118
1119 def predicate_tags_parse(blacklist):
1120 if isinstance(blacklist, str):
1121 try:
1122 with open(expand_path(blacklist)) as fp:
1123 blacklist = fp.readlines()
1124 except OSError:
1125 blacklist = blacklist.split(",")
1126
1127 simple = set()
1128 complex = []
1129
1130 for line in blacklist:
1131 line = line.strip()
1132 if not line or line.startswith("# "):
1133 # empty or comment
1134 continue
1135 line = line.lower()
1136
1137 if " " in line:
1138 Or = []
1139 And = []
1140 for tag in line.split():
1141 if tag[0] == "~":
1142 Or.append(tag[1:])
1143 elif tag[0] == "-":
1144 And.append(predicate_tags_not(tag[1:]))
1145 else:
1146 And.append(predicate_tags_in(tag))
1147 if Or:
1148 And.append("")
1149 for tag in Or:
1150 And[-1] = predicate_tags_in(tag)
1151 complex.append(predicate_tags_chain(And.copy()))
1152 else:
1153 complex.append(predicate_tags_chain(And))
1154
1155 elif line[0] in "-~":
1156 if line[0] == "~":
1157 simple.add(line[1:])
1158 else:
1159 complex.append(predicate_tags_not(line[1:]))
1160 else:
1161 simple.add(line)
1162
1163 return simple, complex or None
1164
1165
1166 def predicate_tags_in(tag):
1167 return lambda tags: tag in tags
1168
1169
1170 def predicate_tags_not(tag):
1171 return lambda tags: tag not in tags
1172
1173
1174 def predicate_tags_chain(checks):
1175 def chain(tags):
1176 for check in checks:
1177 if not check(tags):
1178 return False
1179 return True
1180 return chain
1181
1182
1183 def predicate_date(before, after=None, skip=None):
1184 if after is None:
1185 if skip is not None and skip(before):
1186 return true
1187
1188 def _pred(_, kwdict):
1189 if (date := kwdict.get("date")) and date >= before:
1190 return False
1191 return True
1192
1193 elif before is None or after > before or skip is not None and skip(before):
1194 def _pred(_, kwdict):
1195 if (date := kwdict.get("date")) and date <= after:
1196 raise exception.StopExtraction()
1197 return True
1198
1199 else:
1200 def _pred(_, kwdict):
1201 if not (date := kwdict.get("date")):
1202 return True
1203 if date <= after:
1204 raise exception.StopExtraction()
1205 return date < before
1206 return _pred
1207
1208
1209 def predicate_range(ranges, skip=None, flag=None):
1210 """Predicate; True if the current index is in the given range(s)"""
1211 if ranges := predicate_range_parse(ranges):
1212 # technically wrong for 'step > 2', but good enough for now
1213 # and evaluating min/max for a large range is slow
1214 upper = max(r.stop for r in ranges) - 1
1215 lower = min(r.start for r in ranges)
1216 index = 0 if skip is None or lower <= 1 else skip(lower - 1)
1217 del lower
1218 else:
1219 index = upper = 0
1220
1221 if flag is None:
1222 def _pred(_url, _kwdict):
1223 nonlocal index
1224
1225 if index >= upper:
1226 raise exception.StopExtraction()
1227 index += 1
1228
1229 for range in ranges:
1230 if index in range:
1231 return True
1232 return False
1233 else:
1234 def _pred(_url, _kwdict):
1235 nonlocal index
1236
1237 index += 1
1238 if index >= upper:
1239 if index > upper:
1240 raise exception.StopExtraction()
1241 FLAGS.__dict__[flag.upper()] = "stop"
1242
1243 for range in ranges:
1244 if index in range:
1245 return True
1246 return False
1247 return _pred
1248
1249
1250 def predicate_range_parse(rangespec):
1251 """Parse an integer range string and return the resulting ranges
1252
1253 Examples:
1254 _parse("-2,4,6-8,10-") -> [(1,3), (4,5), (6,9), (10,INTMAX)]
1255 _parse(" - 3 , 4- 4, 2-6") -> [(1,4), (4,5), (2,7)]
1256 _parse("1:2,4:8:2") -> [(1,1), (4,7,2)]
1257 """
1258 ranges = []
1259
1260 if isinstance(rangespec, str):
1261 rangespec = rangespec.split(",")
1262 elif isinstance(rangespec, int):
1263 rangespec = (str(rangespec),)
1264
1265 for group in rangespec:
1266 if not group:
1267 continue
1268
1269 elif ":" in group:
1270 start, _, stop = group.partition(":")
1271 stop, _, step = stop.partition(":")
1272 ranges.append(range(
1273 int(start) if start.strip() else 1,
1274 int(stop) if stop.strip() else sys.maxsize,
1275 int(step) if step.strip() else 1,
1276 ))
1277
1278 elif "-" in group:
1279 start, _, stop = group.partition("-")
1280 ranges.append(range(
1281 int(start) if start.strip() else 1,
1282 int(stop) + 1 if stop.strip() else sys.maxsize,
1283 ))
1284
1285 else:
1286 start = int(group)
1287 ranges.append(range(start, start+1))
1288
1289 return ranges