Debian Codegraph @

gallery_dl/output.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2015-2025 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 shutil
12 import logging
13 import unicodedata
14 from . import config, util, formatter
15
16
17 # --------------------------------------------------------------------
18 # Globals
19
20 format_bytes = util.format_bytes_decimal
21
22 try:
23 TTY_STDOUT = sys.stdout.isatty()
24 except Exception:
25 TTY_STDOUT = False
26
27 try:
28 TTY_STDERR = sys.stderr.isatty()
29 except Exception:
30 TTY_STDERR = False
31
32 try:
33 TTY_STDIN = sys.stdin.isatty()
34 except Exception:
35 TTY_STDIN = False
36
37
38 COLORS_DEFAULT = {}
39 COLORS = not os.environ.get("NO_COLOR")
40 if COLORS:
41 if TTY_STDOUT:
42 COLORS_DEFAULT["success"] = "1;32"
43 COLORS_DEFAULT["skip"] = "2"
44 if TTY_STDERR:
45 COLORS_DEFAULT["debug"] = "0;37"
46 COLORS_DEFAULT["info"] = "1;37"
47 COLORS_DEFAULT["warning"] = "1;33"
48 COLORS_DEFAULT["error"] = "1;31"
49
50
51 if util.WINDOWS:
52 ANSI = COLORS and os.environ.get("TERM") == "ANSI"
53 OFFSET = 1
54 CHAR_SKIP = "# "
55 CHAR_SUCCESS = "* "
56 CHAR_ELLIPSIES = "..."
57 else:
58 ANSI = COLORS
59 OFFSET = 0
60 CHAR_SKIP = "# "
61 CHAR_SUCCESS = "✔ "
62 CHAR_ELLIPSIES = "…"
63 OFFSET_BYTES = 7
64
65 # --------------------------------------------------------------------
66 # Logging
67
68 LOG_FORMAT = "[{name}][{levelname}] {message}"
69 LOG_FORMAT_DATE = "%Y-%m-%d %H:%M:%S"
70 LOG_LEVEL = logging.INFO
71 LOG_LEVELS = ("debug", "info", "warning", "error")
72
73
74 class Logger(logging.Logger):
75 """Custom Logger that includes extra info in log records"""
76
77 def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
78 func=None, extra=None, sinfo=None,
79 factory=logging._logRecordFactory):
80 rv = factory(name, level, fn, lno, msg, args, exc_info, func, sinfo)
81 if extra:
82 rv.__dict__.update(extra)
83 return rv
84
85
86 class LoggerAdapter():
87 """Trimmed-down version of logging.LoggingAdapter"""
88 __slots__ = ("logger", "extra")
89
90 def __init__(self, logger, job):
91 self.logger = logger
92 self.extra = job._logger_extra
93
94 def traceback(self, exc):
95 if self.logger.isEnabledFor(logging.DEBUG):
96 self.logger._log(
97 logging.DEBUG, "", None, exc_info=exc, extra=self.extra)
98
99 def debug(self, msg, *args, **kwargs):
100 if self.logger.isEnabledFor(logging.DEBUG):
101 kwargs["extra"] = self.extra
102 self.logger._log(logging.DEBUG, msg, args, **kwargs)
103
104 def info(self, msg, *args, **kwargs):
105 if self.logger.isEnabledFor(logging.INFO):
106 kwargs["extra"] = self.extra
107 self.logger._log(logging.INFO, msg, args, **kwargs)
108
109 def warning(self, msg, *args, **kwargs):
110 if self.logger.isEnabledFor(logging.WARNING):
111 kwargs["extra"] = self.extra
112 self.logger._log(logging.WARNING, msg, args, **kwargs)
113
114 def error(self, msg, *args, **kwargs):
115 if self.logger.isEnabledFor(logging.ERROR):
116 kwargs["extra"] = self.extra
117 self.logger._log(logging.ERROR, msg, args, **kwargs)
118
119
120 class PathfmtProxy():
121 __slots__ = ("job",)
122
123 def __init__(self, job):
124 self.job = job
125
126 def __getattribute__(self, name):
127 pathfmt = object.__getattribute__(self, "job").pathfmt
128 return getattr(pathfmt, name, None) if pathfmt else None
129
130 def __str__(self):
131 if pathfmt := object.__getattribute__(self, "job").pathfmt:
132 return pathfmt.path or pathfmt.directory
133 return ""
134
135
136 class KwdictProxy():
137 __slots__ = ("job",)
138
139 def __init__(self, job):
140 self.job = job
141
142 def __getattribute__(self, name):
143 pathfmt = object.__getattribute__(self, "job").pathfmt
144 return pathfmt.kwdict.get(name) if pathfmt else None
145
146
147 class Formatter(logging.Formatter):
148 """Custom formatter that supports different formats per loglevel"""
149
150 def __init__(self, fmt, datefmt):
151 if isinstance(fmt, dict):
152 for key in LOG_LEVELS:
153 value = fmt[key] if key in fmt else LOG_FORMAT
154 fmt[key] = (formatter.parse(value).format_map,
155 "{asctime" in value)
156 else:
157 if fmt == LOG_FORMAT:
158 fmt = (fmt.format_map, False)
159 else:
160 fmt = (formatter.parse(fmt).format_map, "{asctime" in fmt)
161 fmt = {"debug": fmt, "info": fmt, "warning": fmt, "error": fmt}
162
163 self.formats = fmt
164 self.datefmt = datefmt
165
166 def format(self, record):
167 record.message = record.getMessage()
168 fmt, asctime = self.formats[record.levelname]
169 if asctime:
170 record.asctime = self.formatTime(record, self.datefmt)
171 msg = fmt(record.__dict__)
172 if record.exc_info and not record.exc_text:
173 record.exc_text = self.formatException(record.exc_info)
174 if record.exc_text:
175 msg = f"{msg}\n{record.exc_text}"
176 if record.stack_info:
177 msg = f"{msg}\n{record.stack_info}"
178 return msg
179
180
181 class FileHandler(logging.StreamHandler):
182 def __init__(self, path, mode, encoding, delay=True):
183 self.path = path
184 self.mode = mode
185 self.errors = None
186 self.encoding = encoding
187
188 if delay:
189 logging.Handler.__init__(self)
190 self.stream = None
191 self.emit = self.emit_delayed
192 else:
193 logging.StreamHandler.__init__(self, self._open())
194
195 def close(self):
196 with self.lock:
197 try:
198 if self.stream:
199 try:
200 self.flush()
201 self.stream.close()
202 finally:
203 self.stream = None
204 finally:
205 logging.StreamHandler.close(self)
206
207 def _open(self):
208 try:
209 return open(self.path, self.mode,
210 encoding=self.encoding, errors=self.errors)
211 except FileNotFoundError:
212 os.makedirs(os.path.dirname(self.path))
213 return open(self.path, self.mode,
214 encoding=self.encoding, errors=self.errors)
215
216 def emit_delayed(self, record):
217 if self.mode != "w" or not self._closed:
218 self.stream = self._open()
219 self.emit = logging.StreamHandler.emit.__get__(self)
220 self.emit(record)
221
222
223 def initialize_logging(loglevel):
224 """Setup basic logging functionality before configfiles have been loaded"""
225 # convert levelnames to lowercase
226 for level in (10, 20, 30, 40, 50):
227 name = logging.getLevelName(level)
228 logging.addLevelName(level, name.lower())
229
230 # register custom Logging class
231 logging.Logger.manager.setLoggerClass(Logger)
232
233 # setup basic logging to stderr
234 formatter = Formatter(LOG_FORMAT, LOG_FORMAT_DATE)
235 handler = logging.StreamHandler()
236 handler.setFormatter(formatter)
237 handler.setLevel(loglevel)
238 root = logging.getLogger()
239 root.setLevel(logging.NOTSET)
240 root.addHandler(handler)
241
242 return logging.getLogger("gallery-dl")
243
244
245 def configure_logging(loglevel):
246 root = logging.getLogger()
247 minlevel = loglevel
248
249 # stream logging handler
250 handler = root.handlers[0]
251 opts = config.interpolate(("output",), "log")
252
253 colors = config.interpolate(("output",), "colors")
254 if colors is None:
255 colors = COLORS_DEFAULT
256 if colors and not opts:
257 opts = LOG_FORMAT
258
259 if opts:
260 if isinstance(opts, str):
261 logfmt = opts
262 opts = {}
263 elif "format" in opts:
264 logfmt = opts["format"]
265 else:
266 logfmt = LOG_FORMAT
267
268 if not isinstance(logfmt, dict) and colors:
269 ansifmt = "\033[{}m{}\033[0m".format
270 lf = {}
271 for level in LOG_LEVELS:
272 c = colors.get(level)
273 lf[level] = ansifmt(c, logfmt) if c else logfmt
274 logfmt = lf
275
276 handler.setFormatter(Formatter(
277 logfmt, opts.get("format-date", LOG_FORMAT_DATE)))
278
279 if "level" in opts and handler.level == LOG_LEVEL:
280 handler.setLevel(opts["level"])
281
282 if minlevel > handler.level:
283 minlevel = handler.level
284
285 # file logging handler
286 if handler := setup_logging_handler("logfile", lvl=loglevel):
287 root.addHandler(handler)
288 if minlevel > handler.level:
289 minlevel = handler.level
290
291 root.setLevel(minlevel)
292
293
294 def setup_logging_handler(key, fmt=LOG_FORMAT, lvl=LOG_LEVEL, mode="w",
295 defer=False):
296 """Setup a new logging handler"""
297 opts = config.interpolate(("output",), key)
298 if not opts:
299 return None
300 if not isinstance(opts, dict):
301 opts = {"path": opts}
302
303 path = opts.get("path")
304 mode = opts.get("mode", mode)
305 encoding = opts.get("encoding", "utf-8")
306 delay = opts.get("defer", defer)
307 try:
308 path = util.expand_path(path)
309 handler = FileHandler(path, mode, encoding, delay)
310 except (OSError, ValueError) as exc:
311 logging.getLogger("gallery-dl").warning(
312 "%s: %s", key, exc)
313 return None
314 except TypeError as exc:
315 logging.getLogger("gallery-dl").warning(
316 "%s: missing or invalid path (%s)", key, exc)
317 return None
318
319 handler.setLevel(opts.get("level", lvl))
320 handler.setFormatter(Formatter(
321 opts.get("format", fmt),
322 opts.get("format-date", LOG_FORMAT_DATE),
323 ))
324 return handler
325
326
327 # --------------------------------------------------------------------
328 # Utility functions
329
330 def stdout_write_flush(s):
331 sys.stdout.write(s)
332 sys.stdout.flush()
333
334
335 def stderr_write_flush(s):
336 sys.stderr.write(s)
337 sys.stderr.flush()
338
339
340 if getattr(sys.stdout, "line_buffering", None):
341 def stdout_write(s):
342 sys.stdout.write(s)
343 else:
344 stdout_write = stdout_write_flush
345
346
347 if getattr(sys.stderr, "line_buffering", None):
348 def stderr_write(s):
349 sys.stderr.write(s)
350 else:
351 stderr_write = stderr_write_flush
352
353
354 def configure_standard_streams():
355 for name in ("stdout", "stderr", "stdin"):
356 stream = getattr(sys, name, None)
357 if not stream or not hasattr(stream, "reconfigure"):
358 continue
359
360 options = config.get(("output",), name)
361 if not options:
362 options = {"errors": "replace"}
363 elif isinstance(options, str):
364 options = {"errors": "replace", "encoding": options}
365 elif not options.get("errors"):
366 options["errors"] = "replace"
367
368 stream.reconfigure(**options)
369
370
371 def configure_units():
372 global format_bytes, OFFSET_BYTES
373
374 if config.get(("output",), "units") in {"binary", "base-2", "iec"}:
375 format_bytes = util.format_bytes_binary
376 OFFSET_BYTES = 8
377
378
379 # --------------------------------------------------------------------
380 # Downloader output
381
382 def select():
383 """Select a suitable output class"""
384 mode = config.get(("output",), "mode")
385
386 if mode is None or mode == "auto":
387 try:
388 if TTY_STDOUT:
389 output = ColorOutput() if ANSI else TerminalOutput()
390 else:
391 output = PipeOutput()
392 except Exception:
393 output = PipeOutput()
394 elif isinstance(mode, dict):
395 output = CustomOutput(mode)
396 elif not mode:
397 output = NullOutput()
398 else:
399 output = {
400 "default" : PipeOutput,
401 "pipe" : PipeOutput,
402 "term" : TerminalOutput,
403 "terminal": TerminalOutput,
404 "color" : ColorOutput,
405 "null" : NullOutput,
406 }[mode.lower()]()
407
408 if not config.get(("output",), "skip", True):
409 output.skip = util.identity
410 return output
411
412
413 class NullOutput():
414
415 def start(self, path):
416 """Print a message indicating the start of a download"""
417
418 def skip(self, path):
419 """Print a message indicating that a download has been skipped"""
420
421 def success(self, path):
422 """Print a message indicating the completion of a download"""
423
424 def progress(self, bytes_total, bytes_downloaded, bytes_per_second):
425 """Display download progress"""
426
427
428 class PipeOutput(NullOutput):
429
430 def skip(self, path):
431 stdout_write(f"{CHAR_SKIP}{path}\n")
432
433 def success(self, path):
434 stdout_write(f"{path}\n")
435
436
437 class TerminalOutput():
438
439 def __init__(self):
440 if shorten := config.get(("output",), "shorten", True):
441 func = shorten_string_eaw if shorten == "eaw" else shorten_string
442 limit = shutil.get_terminal_size().columns - OFFSET
443 sep = CHAR_ELLIPSIES
444 self.shorten = lambda txt: func(txt, limit, sep)
445 else:
446 self.shorten = util.identity
447
448 def start(self, path):
449 stdout_write_flush(self.shorten(f" {path}"))
450
451 def skip(self, path):
452 stdout_write(f"{self.shorten(CHAR_SKIP + path)}\n")
453
454 def success(self, path):
455 stdout_write(f"\r{self.shorten(CHAR_SUCCESS + path)}\n")
456
457 def progress(self, bytes_total, bytes_downloaded, bytes_per_second):
458 bdl = format_bytes(bytes_downloaded)
459 bps = format_bytes(bytes_per_second)
460 if bytes_total is None:
461 stderr_write(f"\r{bdl:>{OFFSET_BYTES}}B {bps:>{OFFSET_BYTES}}B/s ")
462 else:
463 stderr_write(f"\r{bytes_downloaded * 100 // bytes_total:>3}% "
464 f"{bdl:>{OFFSET_BYTES}}B {bps:>{OFFSET_BYTES}}B/s ")
465
466
467 class ColorOutput(TerminalOutput):
468
469 def __init__(self):
470 TerminalOutput.__init__(self)
471
472 colors = config.interpolate(("output",), "colors")
473 if colors is None:
474 colors = COLORS_DEFAULT
475
476 self.color_skip = f"\x1b[{colors.get('skip', '2')}m"
477 self.color_success = f"\r\x1b[{colors.get('success', '1;32')}m"
478
479 def start(self, path):
480 stdout_write_flush(self.shorten(path))
481
482 def skip(self, path):
483 stdout_write(f"{self.color_skip}{self.shorten(path)}\x1b[0m\n")
484
485 def success(self, path):
486 stdout_write(f"{self.color_success}{self.shorten(path)}\x1b[0m\n")
487
488
489 class CustomOutput():
490
491 def __init__(self, options):
492
493 fmt_skip = options.get("skip")
494 fmt_start = options.get("start")
495 fmt_success = options.get("success")
496 off_skip = off_start = off_success = 0
497
498 if isinstance(fmt_skip, list):
499 off_skip, fmt_skip = fmt_skip
500 if isinstance(fmt_start, list):
501 off_start, fmt_start = fmt_start
502 if isinstance(fmt_success, list):
503 off_success, fmt_success = fmt_success
504
505 if shorten := config.get(("output",), "shorten", True):
506 func = shorten_string_eaw if shorten == "eaw" else shorten_string
507 width = shutil.get_terminal_size().columns
508
509 self._fmt_skip = self._make_func(
510 func, fmt_skip, width - off_skip)
511 self._fmt_start = self._make_func(
512 func, fmt_start, width - off_start)
513 self._fmt_success = self._make_func(
514 func, fmt_success, width - off_success)
515 else:
516 self._fmt_skip = fmt_skip.format
517 self._fmt_start = fmt_start.format
518 self._fmt_success = fmt_success.format
519
520 self._fmt_progress = (options.get("progress") or
521 "\r{0:>7}B {1:>7}B/s ").format
522 self._fmt_progress_total = (options.get("progress-total") or
523 "\r{3:>3}% {0:>7}B {1:>7}B/s ").format
524
525 def _make_func(self, shorten, format_string, limit):
526 fmt = format_string.format
527 return lambda txt: fmt(shorten(txt, limit, CHAR_ELLIPSIES))
528
529 def start(self, path):
530 stdout_write_flush(self._fmt_start(path))
531
532 def skip(self, path):
533 stdout_write(self._fmt_skip(path))
534
535 def success(self, path):
536 stdout_write(self._fmt_success(path))
537
538 def progress(self, bytes_total, bytes_downloaded, bytes_per_second):
539 bdl = format_bytes(bytes_downloaded)
540 bps = format_bytes(bytes_per_second)
541 if bytes_total is None:
542 stderr_write(self._fmt_progress(bdl, bps))
543 else:
544 stderr_write(self._fmt_progress_total(
545 bdl, bps, format_bytes(bytes_total),
546 bytes_downloaded * 100 // bytes_total))
547
548
549 class EAWCache(dict):
550
551 def __missing__(self, key):
552 width = self[key] = \
553 2 if unicodedata.east_asian_width(key) in "WF" else 1
554 return width
555
556
557 def shorten_string(txt, limit, sep="…"):
558 """Limit width of 'txt'; assume all characters have a width of 1"""
559 if len(txt) <= limit:
560 return txt
561 limit -= len(sep)
562 return f"{txt[:limit // 2]}{sep}{txt[-((limit+1) // 2):]}"
563
564
565 def shorten_string_eaw(txt, limit, sep="…", cache=EAWCache()):
566 """Limit width of 'txt'; check for east-asian characters with width > 1"""
567 char_widths = [cache[c] for c in txt]
568 text_width = sum(char_widths)
569
570 if text_width <= limit:
571 # no shortening required
572 return txt
573
574 limit -= len(sep)
575 if text_width == len(txt):
576 # all characters have a width of 1
577 return f"{txt[:limit // 2]}{sep}{txt[-((limit+1) // 2):]}"
578
579 # wide characters
580 left = 0
581 lwidth = limit // 2
582 while True:
583 lwidth -= char_widths[left]
584 if lwidth < 0:
585 break
586 left += 1
587
588 right = -1
589 rwidth = (limit+1) // 2 + (lwidth + char_widths[left])
590 while True:
591 rwidth -= char_widths[right]
592 if rwidth < 0:
593 break
594 right -= 1
595
596 return f"{txt[:left]}{sep}{txt[right+1:]}"