Debian Codegraph @

gallery_dl/__init__.py

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