Debian Codegraph @

gallery_dl/__init__.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2014-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 import os
10 import sys
11 import logging
12 from . import version, config, option, output, extractor, job, util, exception
13
14 __author__ = "Mike Fährmann"
15 __copyright__ = "Copyright 2014-2026 Mike Fährmann"
16 __license__ = "GPLv2"
17 __maintainer__ = "Mike Fährmann"
18 __email__ = "[email protected]"
19 __version__ = version.__version__
20
21
22 def main():
23 try:
24 parser = option.build_parser()
25 args = parser.parse_args()
26 log = output.initialize_logging(args.loglevel)
27
28 # configuration
29 if args.config_type:
30 try:
31 config.default(args.config_type)
32 except Exception as exc:
33 config.log.error(exc)
34 if args.config_load:
35 config.load()
36 if args.configs_extra:
37 config.load(args.configs_extra, strict=True)
38 if args.configs_json:
39 config.load(args.configs_json, strict=True, loads=util.json_loads)
40 if args.configs_yaml:
41 import yaml
42 config.load(args.configs_yaml, strict=True, loads=yaml.safe_load)
43 if args.configs_toml:
44 try:
45 import tomllib as toml
46 except ImportError:
47 import toml
48 config.load(args.configs_toml, strict=True, loads=toml.loads)
49 if not args.colors:
50 output.ANSI = False
51 config.set((), "colors", False)
52 if util.WINDOWS:
53 config.set(("output",), "ansi", False)
54 if args.filename:
55 filename = args.filename
56 if filename == "/O":
57 filename = "{filename}.{extension}"
58 elif filename.startswith("\\f"):
59 filename = f"\f{filename[2:]}"
60 config.set((), "filename", filename)
61 if args.directory is not None:
62 config.set((), "base-directory", args.directory)
63 config.set((), "directory", ())
64 if args.postprocessors:
65 config.set((), "postprocessors", args.postprocessors)
66 if args.abort:
67 config.set((), "skip", "abort:" + args.abort)
68 if args.terminate:
69 config.set((), "skip", "terminate:" + args.terminate)
70 if args.cookies_from_browser:
71 browser, _, profile = args.cookies_from_browser.partition(":")
72 browser, _, keyring = browser.partition("+")
73 browser, _, domain = browser.partition("/")
74 if profile and profile[0] == ":":
75 container = profile[1:]
76 profile = None
77 else:
78 profile, _, container = profile.partition("::")
79 config.set((), "cookies", (
80 browser, profile, keyring, container, domain))
81 if args.options_pp:
82 config.set((), "postprocessor-options", args.options_pp)
83 for opts in args.options:
84 config.set(*opts)
85
86 # environment variables
87 if env := config.getg("environment"):
88 if isinstance(env, dict):
89 env = env.dicts()
90 environ = os.environ
91 if config.getg("environment-expand", True):
92 for key, value in env:
93 environ[key] = util.expand_path(value)
94 else:
95 for key, value in env: # faster than '.update()'
96 environ[key] = value
97
98 output.configure_standard_streams()
99 output.configure_units()
100
101 # signals
102 if signals := config.getg("signals-ignore"):
103 import signal
104 if isinstance(signals, str):
105 signals = signals.split(",")
106 for signal_name in signals:
107 signal_num = getattr(signal, signal_name, None)
108 if signal_num is None:
109 log.warning("signal '%s' is not defined", signal_name)
110 else:
111 signal.signal(signal_num, signal.SIG_IGN)
112
113 if signals := config.getg("signals-actions"):
114 from . import actions
115 actions.parse_signals(signals)
116
117 # enable ANSI escape sequences on Windows
118 if util.WINDOWS and config.get(("output",), "ansi", output.COLORS):
119 from ctypes import windll, wintypes, byref
120 kernel32 = windll.kernel32
121 mode = wintypes.DWORD()
122
123 for handle_id in (-11, -12): # stdout and stderr
124 handle = kernel32.GetStdHandle(handle_id)
125 kernel32.GetConsoleMode(handle, byref(mode))
126 if not mode.value & 0x4:
127 mode.value |= 0x4
128 kernel32.SetConsoleMode(handle, mode)
129
130 output.ANSI = True
131
132 # filter environment
133 filterenv = config.getg("filters-environment", True)
134 if filterenv is True:
135 pass
136 elif not filterenv:
137 util.compile_expression = util.compile_expression_raw
138 elif isinstance(filterenv, str):
139 if filterenv == "raw":
140 util.compile_expression = util.compile_expression_raw
141 elif filterenv.startswith("default"):
142 util.compile_expression = util.compile_expression_defaultdict
143
144 # format string options
145 if not config.getg("format-operator-dot", True):
146 from . import formatter
147 formatter._attrgetter = formatter.operator.attrgetter
148 if separator := config.getg("format-separator"):
149 from . import formatter
150 formatter._SEPARATOR = separator
151
152 # eval globals
153 if path := config.getg("globals"):
154 util.GLOBALS.update(util.import_file(path).__dict__)
155
156 # symlinks
157 if config.getg("follow-symlinks"):
158 util.SYMLINKS = True
159
160 # loglevels
161 output.configure_logging(args.loglevel)
162 if args.loglevel >= logging.WARNING:
163 config.set(("output",), "mode", "null")
164 config.set(("downloader",), "progress", None)
165 elif args.loglevel <= logging.DEBUG:
166 import platform
167 import requests
168
169 if util.EXECUTABLE:
170 extra = f" - Executable ({version.__variant__})"
171 elif git_head := util.git_head():
172 extra = " - Git HEAD: " + git_head
173 else:
174 extra = ""
175
176 log.debug("Version %s%s", __version__, extra)
177 log.debug("Python %s - %s",
178 platform.python_version(), platform.platform())
179 try:
180 log.debug("requests %s - urllib3 %s",
181 requests.__version__,
182 requests.packages.urllib3.__version__)
183 except AttributeError:
184 pass
185
186 log.debug("Configuration Files %s", config._files)
187
188 if args.cache_file:
189 config.set(("cache",), "file", args.cache_file)
190
191 if args.cache_status:
192 from . import cache, text
193 from collections import defaultdict
194
195 path = cache.path()
196 rows = cache.get("ALL")
197 if rows is None:
198 return cache.error()
199
200 try:
201 size = os.stat(path).st_size
202 except Exception:
203 size = 0
204
205 cnts = defaultdict(int)
206 for row in rows:
207 key = row[0].split(".")
208 if key[2] == "utils":
209 key = key[3].partition("_")[0]
210 elif key[1] == "oauth":
211 key = text.extr(key[2], "'", "'")
212 else:
213 key = key[2]
214 cnts[key] += 1
215 cnts["Total"] += 1
216
217 key_max = 0
218 cnt_max = len(str(cnts["Total"]))
219 for key in cnts:
220 if key_max < (key_len := len(key)):
221 key_max = key_len
222 if key_max > 24:
223 key_max = 24
224
225 write = sys.stdout.write
226 write(f"""\
227 File:
228 {cache.path()}
229 Size:
230 {output.format_bytes(size)}
231 Entries:
232 """)
233 for key, cnt in sorted(cnts.items(), key=lambda i: (-i[1], i[0])):
234 write(f" {key}{' ' * (key_max-len(key))}: {cnt:>{cnt_max}}\n")
235
236 return 0
237
238 if args.cache_show:
239 from . import cache
240 rows = cache.get(args.cache_show)
241 if rows is None:
242 return cache.error()
243 import pickle
244 cut = 2 if args.cache_show in {"ALL", "EXP", "VAL"} else 3
245 for key, value, expires in rows:
246 try:
247 value = util.json_dumps(pickle.loads(value))
248 except Exception:
249 value = "<Invalid Value>"
250 expires = f" ({expires})" if expires else ""
251 key = ".".join(key.split(".")[cut:])
252 sys.stdout.write(f"{key}{expires}:\n {value}\n\n")
253 return 0
254
255 if args.cache_clear:
256 from . import cache
257 cnt = cache.clear(args.cache_clear)
258 if cnt is None:
259 return cache.error()
260
261 cache.log.info("Deleted %d entr%s from '%s'",
262 cnt, "y" if cnt == 1 else "ies", cache.path())
263 return 0
264
265 if args.cache_vacuum:
266 from . import cache
267 if (db := cache.database()) is None:
268 return cache.error()
269 path = cache.path()
270 before = os.stat(path).st_size
271 cache.log.info("Running 'VACUUM'")
272 db.execute("VACUUM")
273 after = os.stat(path).st_size
274 if before - after:
275 cache.log.info("Reduced database size by %s bytes",
276 output.format_bytes(before - after))
277 return 0
278
279 if args.config:
280 if args.config == "init":
281 return config.initialize()
282 elif args.config == "status":
283 return config.status()
284 else:
285 return config.open_extern()
286
287 if args.print_traffic:
288 import requests
289 requests.packages.urllib3.connection.HTTPConnection.debuglevel = 1
290
291 if args.update:
292 from . import update
293 extr = update.UpdateExtractor.from_url("update:" + args.update)
294 ujob = update.UpdateJob(extr)
295 return ujob.run()
296
297 # category renaming
298 config.remap_categories()
299
300 # extractor modules
301 modules = config.get(("extractor",), "modules")
302 if modules is not None:
303 if isinstance(modules, str):
304 modules = modules.split(",")
305 extractor.modules = modules
306
307 # external modules
308 if args.extractor_sources:
309 sources = args.extractor_sources
310 sources.append(None)
311 else:
312 sources = config.get(("extractor",), "module-sources")
313
314 if sources:
315 modules = []
316
317 for source in sources:
318 if isinstance(source, str):
319 path = util.expand_path(source)
320 try:
321 files = [name[:-3] for name in os.listdir(path)
322 if name.endswith(".py")]
323 modules.append(extractor._modules_path(path, files))
324 except Exception as exc:
325 log.warning("Unable to load modules from %s (%s: %s)",
326 path, exc.__class__.__name__, exc)
327 elif isinstance(source, dict):
328 path = util.expand_path(source["from"])
329 files = source["import"]
330 try:
331 modules.append(extractor._modules_path(path, files))
332 except Exception as exc:
333 log.warning("Unable to load modules [%s] "
334 "from %s (%s: %s)",
335 files, path, exc.__class__.__name__, exc)
336 else:
337 modules.append(extractor._modules_internal())
338
339 if len(modules) > 1:
340 import itertools
341 extractor._module_iter = itertools.chain(*modules)
342 elif not modules:
343 extractor._module_iter = ()
344 else:
345 extractor._module_iter = iter(modules[0])
346
347 if args.list_modules:
348 extractor.modules.append("")
349 sys.stdout.write("\n".join(extractor.modules))
350
351 elif args.list_extractors is not None:
352 write = sys.stdout.write
353 fmt = ("{}{}\nCategory: {} - Subcategory: {}"
354 "\nExample : {}\n\n").format
355
356 extractors = extractor.extractors()
357 if args.list_extractors:
358 fltr = util.build_extractor_filter(
359 args.list_extractors, negate=False)
360 extractors = filter(fltr, extractors)
361
362 for extr in extractors:
363 write(fmt(
364 extr.__name__,
365 "\n" + extr.__doc__ if extr.__doc__ else "",
366 extr.category, extr.subcategory,
367 extr.example,
368 ))
369
370 else:
371 if input_files := config.getg("input-files"):
372 for input_file in input_files:
373 if isinstance(input_file, str):
374 input_file = (input_file, None)
375 args.input_files.append(input_file)
376
377 nourls = (not args.urls and not args.input_files)
378 if not args.server:
379 if nourls:
380 if args.cookies_from_browser or config.interpolate(
381 ("extractor",), "cookies"):
382 args.urls.append("noop")
383 else:
384 parser.error(
385 "The following arguments are required: URL\n"
386 "Use 'gallery-dl --help' to get a list of all "
387 "options.")
388 else:
389 args.server = config.get(("server",), "enabled", False)
390
391 if args.list_urls:
392 jobtype = job.UrlJob
393 jobtype.maxdepth = args.list_urls
394 if config.get(("output",), "fallback", True):
395 jobtype.handle_url = jobtype.handle_url_fallback
396 elif args.dump_json:
397 jobtype = job.DataJob
398 jobtype.resolve = args.dump_json - 1
399 else:
400 jobtype = args.jobtype or job.DownloadJob
401
402 if args.server:
403 from . import server
404 input_manager = server.start() if nourls else InputManager()
405 else:
406 input_manager = InputManager()
407 input_manager.log = input_log = logging.getLogger("inputfile")
408
409 # unsupported file logging handler
410 if handler := output.setup_logging_handler(
411 "unsupportedfile", fmt="{message}", defer=True):
412 ulog = job.Job.ulog = logging.getLogger("unsupported")
413 ulog.addHandler(handler)
414 ulog.propagate = False
415
416 # error file logging handler
417 if handler := output.setup_logging_handler(
418 "errorfile", fmt="{message}", mode="a", defer=True):
419 elog = input_manager.err = logging.getLogger("errorfile")
420 elog.addHandler(handler)
421 elog.propagate = False
422
423 # collect input URLs
424 input_manager.add_list(args.urls)
425
426 if args.input_files:
427 for input_file, action in args.input_files:
428 try:
429 path = util.expand_path(input_file)
430 input_manager.add_file(path, action)
431 except Exception as exc:
432 input_log.error(exc)
433 return getattr(exc, "code", 128)
434
435 if args.server and not nourls and input_manager.urls:
436 return server.send([
437 url[0] if isinstance(url, tuple) else url
438 for url in input_manager.urls
439 ])
440
441 pformat = config.get(("output",), "progress", True)
442 if pformat and args.loglevel < logging.ERROR and (
443 args.server or len(input_manager.urls) > 1):
444 input_manager.progress(pformat)
445
446 if catmap := config.interpolate(("extractor",), "category-map"):
447 if catmap == "compat":
448 catmap = {
449 "coomer" : "coomerparty",
450 "kemono" : "kemonoparty",
451 "turbo" : "saint",
452 "schalenetwork": "koharu",
453 "naver-blog" : "naver",
454 "naver-chzzk" : "chzzk",
455 "naver-webtoon": "naverwebtoon",
456 "pixiv-novel" : "pixiv",
457 "pixiv-novel:novel" : ("pixiv", "novel"),
458 "pixiv-novel:user" : ("pixiv", "novel-user"),
459 "pixiv-novel:series" : ("pixiv", "novel-series"),
460 "pixiv-novel:bookmark": ("pixiv", "novel-bookmark"),
461 }
462 from .extractor import common
463 common.CATEGORY_MAP = catmap
464
465 # process input URLs
466 retval = 0
467 for url in input_manager:
468 try:
469 log.debug("Starting %s for '%s'", jobtype.__name__, url)
470
471 if isinstance(url, ExtendedUrl):
472 for opts in url.gconfig:
473 config.set(*opts)
474 with config.apply(url.lconfig):
475 status = jobtype(url.value).run()
476 else:
477 status = jobtype(url).run()
478
479 if status:
480 retval |= status
481 input_manager.error()
482 else:
483 input_manager.success()
484
485 except exception.RestartExtraction:
486 log.debug("Restarting '%s'", url)
487 continue
488 except exception.ControlException:
489 pass
490 except exception.NoExtractorError:
491 log.error("Unsupported URL '%s'", url)
492 retval |= 64
493 input_manager.error()
494
495 input_manager.next()
496 return retval
497 return 0
498
499 except KeyboardInterrupt:
500 raise SystemExit("\nKeyboardInterrupt")
501 except BrokenPipeError:
502 pass
503 except OSError as exc:
504 import errno
505 if exc.errno != errno.EPIPE:
506 raise
507 return 1
508
509
510 class InputManager():
511
512 def __init__(self):
513 self.urls = []
514 self.files = ()
515 self.log = self.err = None
516
517 self._url = ""
518 self._item = None
519 self._index = 0
520 self._pformat = None
521
522 def add_url(self, url):
523 self.urls.append(url)
524
525 def add_list(self, urls):
526 self.urls += urls
527
528 def add_file(self, path, action=None):
529 """Process an input file.
530
531 Lines starting with '#' and empty lines will be ignored.
532 Lines starting with '-' will be interpreted as a key-value pair
533 separated by an '='. where
534 'key' is a dot-separated option name and
535 'value' is a JSON-parsable string.
536 These configuration options will be applied
537 while processing the next URL only.
538 Lines starting with '-G' are the same as above, except these options
539 will be applied for *all* following URLs, i.e. they are Global.
540 Everything else will be used as a potential URL.
541
542 Example input file:
543
544 # settings global options
545 -G base-directory = "/tmp/"
546 -G skip = false
547
548 # setting local options for the next URL
549 -filename="spaces_are_optional.jpg"
550 -skip = true
551
552 https://example.org/
553
554 # next URL uses default filename and 'skip' is false.
555 https://example.com/index.htm # comment1
556 https://example.com/404.htm # comment2
557 """
558 if path == "-" and not action:
559 try:
560 lines = sys.stdin.readlines()
561 except Exception:
562 raise exception.InputFileError("stdin is not readable")
563 path = None
564 else:
565 try:
566 with open(path, encoding="utf-8") as fp:
567 lines = fp.readlines()
568 except Exception as exc:
569 raise exception.InputFileError(str(exc))
570
571 if self.files:
572 self.files[path] = lines
573 else:
574 self.files = {path: lines}
575
576 if action == "c":
577 action = self._action_comment
578 elif action == "d":
579 action = self._action_delete
580 else:
581 action = None
582
583 gconf = []
584 lconf = []
585 indicies = []
586 strip_comment = None
587 append = self.urls.append
588
589 for n, line in enumerate(lines):
590 line = line.strip()
591
592 if not line or line[0] == "#":
593 # empty line or comment
594 continue
595
596 elif line[0] == "-":
597 # config spec
598 if len(line) >= 2 and line[1] == "G":
599 conf = gconf
600 line = line[2:]
601 else:
602 conf = lconf
603 line = line[1:]
604 if action:
605 indicies.append(n)
606
607 key, sep, value = line.partition("=")
608 if not sep:
609 raise exception.InputFileError(
610 f"Invalid KEY=VALUE pair '{line}' "
611 f"on line {n+1} in {path}")
612
613 try:
614 value = util.json_loads(value.strip())
615 except ValueError as exc:
616 self.log.debug("%s: %s", exc.__class__.__name__, exc)
617 raise exception.InputFileError(
618 f"Unable to parse '{value}' on line {n+1} in {path}")
619
620 key = key.strip().split(".")
621 conf.append((key[:-1], key[-1], value))
622
623 else:
624 # url
625 if " #" in line or "\t#" in line:
626 if strip_comment is None:
627 strip_comment = util.re(r"\s+#.*").sub
628 line = strip_comment("", line)
629 if gconf or lconf:
630 url = ExtendedUrl(line, gconf, lconf)
631 gconf = []
632 lconf = []
633 else:
634 url = line
635
636 if action:
637 indicies.append(n)
638 append((url, path, action, indicies))
639 indicies = []
640 else:
641 append(url)
642
643 def progress(self, pformat=True):
644 if pformat is True:
645 pformat = "[{current}/{total}] {url}\n"
646 else:
647 pformat += "\n"
648 self._pformat = pformat.format_map
649
650 def next(self):
651 self._index += 1
652
653 def success(self):
654 if self._item:
655 self._rewrite()
656
657 def error(self):
658 if self.err:
659 if self._item:
660 url, path, action, indicies = self._item
661 lines = self.files[path]
662 out = "".join(lines[i] for i in indicies)
663 if out and out[-1] == "\n":
664 out = out[:-1]
665 self._rewrite()
666 else:
667 out = str(self._url)
668 self.err.info(out)
669
670 def _rewrite(self):
671 url, path, action, indicies = self._item
672 path_tmp = path + ".tmp"
673 lines = self.files[path]
674 action(lines, indicies)
675
676 try:
677 with open(path_tmp, "w", encoding="utf-8") as fp:
678 fp.writelines(lines)
679 if util.SYMLINKS and os.path.islink(path):
680 path = os.path.realpath(path)
681 os.replace(path_tmp, path)
682 except Exception as exc:
683 self.log.warning(
684 "Unable to update '%s' (%s: %s)",
685 path, exc.__class__.__name__, exc)
686
687 def _action_comment(self, lines, indicies):
688 for i in indicies:
689 lines[i] = "# " + lines[i]
690
691 def _action_delete(self, lines, indicies):
692 for i in indicies:
693 lines[i] = ""
694
695 def __iter__(self):
696 self._index = 0
697 return self
698
699 def __next__(self):
700 try:
701 url = self.urls[self._index]
702 except IndexError:
703 raise StopIteration
704
705 if isinstance(url, tuple):
706 self._item = url
707 url = url[0]
708 else:
709 self._item = None
710 self._url = url
711
712 if self._pformat:
713 output.stderr_write(self._pformat({
714 "total" : len(self.urls),
715 "current": self._index + 1,
716 "url" : url,
717 }))
718 return url
719
720
721 class ExtendedUrl():
722 """URL with attached config key-value pairs"""
723 __slots__ = ("value", "gconfig", "lconfig")
724
725 def __init__(self, url, gconf, lconf):
726 self.value = url
727 self.gconfig = gconf
728 self.lconfig = lconf
729
730 def __str__(self):
731 return self.value