2015-12-01 21:21:39 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2021-05-04 18:07:08 +02:00
|
|
|
# Copyright 2015-2021 Mike Fährmann
|
2015-12-01 21:21:39 +01:00
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License version 2 as
|
|
|
|
# published by the Free Software Foundation.
|
|
|
|
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import shutil
|
2019-02-13 17:39:43 +01:00
|
|
|
import logging
|
2021-09-13 21:29:38 +02:00
|
|
|
import unicodedata
|
2021-09-27 02:37:04 +02:00
|
|
|
from . import config, util, formatter
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2017-01-30 19:40:15 +01:00
|
|
|
|
2019-02-13 17:39:43 +01:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Logging
|
|
|
|
|
|
|
|
LOG_FORMAT = "[{name}][{levelname}] {message}"
|
|
|
|
LOG_FORMAT_DATE = "%Y-%m-%d %H:%M:%S"
|
|
|
|
LOG_LEVEL = logging.INFO
|
|
|
|
|
|
|
|
|
|
|
|
class Logger(logging.Logger):
|
2020-05-18 01:35:53 +02:00
|
|
|
"""Custom logger that includes extra info in log records"""
|
2019-02-13 17:39:43 +01:00
|
|
|
|
|
|
|
def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
|
|
|
|
func=None, extra=None, sinfo=None,
|
|
|
|
factory=logging._logRecordFactory):
|
|
|
|
rv = factory(name, level, fn, lno, msg, args, exc_info, func, sinfo)
|
2020-05-18 01:35:53 +02:00
|
|
|
if extra:
|
|
|
|
rv.__dict__.update(extra)
|
2019-02-13 17:39:43 +01:00
|
|
|
return rv
|
|
|
|
|
|
|
|
|
2020-05-18 01:35:53 +02:00
|
|
|
class LoggerAdapter():
|
|
|
|
"""Trimmed-down version of logging.LoggingAdapter"""
|
|
|
|
__slots__ = ("logger", "extra")
|
|
|
|
|
|
|
|
def __init__(self, logger, extra):
|
|
|
|
self.logger = logger
|
|
|
|
self.extra = extra
|
|
|
|
|
|
|
|
def debug(self, msg, *args, **kwargs):
|
|
|
|
if self.logger.isEnabledFor(logging.DEBUG):
|
|
|
|
kwargs["extra"] = self.extra
|
|
|
|
self.logger._log(logging.DEBUG, msg, args, **kwargs)
|
|
|
|
|
|
|
|
def info(self, msg, *args, **kwargs):
|
|
|
|
if self.logger.isEnabledFor(logging.INFO):
|
|
|
|
kwargs["extra"] = self.extra
|
|
|
|
self.logger._log(logging.INFO, msg, args, **kwargs)
|
|
|
|
|
|
|
|
def warning(self, msg, *args, **kwargs):
|
|
|
|
if self.logger.isEnabledFor(logging.WARNING):
|
|
|
|
kwargs["extra"] = self.extra
|
|
|
|
self.logger._log(logging.WARNING, msg, args, **kwargs)
|
|
|
|
|
|
|
|
def error(self, msg, *args, **kwargs):
|
|
|
|
if self.logger.isEnabledFor(logging.ERROR):
|
|
|
|
kwargs["extra"] = self.extra
|
|
|
|
self.logger._log(logging.ERROR, msg, args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class PathfmtProxy():
|
|
|
|
__slots__ = ("job",)
|
|
|
|
|
|
|
|
def __init__(self, job):
|
|
|
|
self.job = job
|
|
|
|
|
|
|
|
def __getattribute__(self, name):
|
|
|
|
pathfmt = object.__getattribute__(self, "job").pathfmt
|
|
|
|
return pathfmt.__dict__.get(name) if pathfmt else None
|
|
|
|
|
|
|
|
|
|
|
|
class KwdictProxy():
|
|
|
|
__slots__ = ("job",)
|
|
|
|
|
|
|
|
def __init__(self, job):
|
|
|
|
self.job = job
|
|
|
|
|
|
|
|
def __getattribute__(self, name):
|
|
|
|
pathfmt = object.__getattribute__(self, "job").pathfmt
|
|
|
|
return pathfmt.kwdict.get(name) if pathfmt else None
|
|
|
|
|
|
|
|
|
2019-06-21 19:56:09 +02:00
|
|
|
class Formatter(logging.Formatter):
|
|
|
|
"""Custom formatter that supports different formats per loglevel"""
|
|
|
|
|
|
|
|
def __init__(self, fmt, datefmt):
|
2020-03-18 22:41:08 +01:00
|
|
|
if isinstance(fmt, dict):
|
|
|
|
for key in ("debug", "info", "warning", "error"):
|
|
|
|
value = fmt[key] if key in fmt else LOG_FORMAT
|
2021-09-27 02:37:04 +02:00
|
|
|
fmt[key] = (formatter.parse(value).format_map,
|
2020-03-18 22:41:08 +01:00
|
|
|
"{asctime" in value)
|
|
|
|
else:
|
|
|
|
if fmt == LOG_FORMAT:
|
|
|
|
fmt = (fmt.format_map, False)
|
|
|
|
else:
|
2021-09-27 02:37:04 +02:00
|
|
|
fmt = (formatter.parse(fmt).format_map, "{asctime" in fmt)
|
2019-06-21 19:56:09 +02:00
|
|
|
fmt = {"debug": fmt, "info": fmt, "warning": fmt, "error": fmt}
|
2020-03-18 22:41:08 +01:00
|
|
|
|
2019-06-21 19:56:09 +02:00
|
|
|
self.formats = fmt
|
|
|
|
self.datefmt = datefmt
|
|
|
|
|
|
|
|
def format(self, record):
|
|
|
|
record.message = record.getMessage()
|
2020-03-18 22:41:08 +01:00
|
|
|
fmt, asctime = self.formats[record.levelname]
|
|
|
|
if asctime:
|
2019-06-21 19:56:09 +02:00
|
|
|
record.asctime = self.formatTime(record, self.datefmt)
|
2020-03-18 22:41:08 +01:00
|
|
|
msg = fmt(record.__dict__)
|
2019-06-21 19:56:09 +02:00
|
|
|
if record.exc_info and not record.exc_text:
|
|
|
|
record.exc_text = self.formatException(record.exc_info)
|
|
|
|
if record.exc_text:
|
|
|
|
msg = msg + "\n" + record.exc_text
|
|
|
|
if record.stack_info:
|
|
|
|
msg = msg + "\n" + record.stack_info
|
|
|
|
return msg
|
|
|
|
|
|
|
|
|
2019-02-13 17:39:43 +01:00
|
|
|
def initialize_logging(loglevel):
|
|
|
|
"""Setup basic logging functionality before configfiles have been loaded"""
|
|
|
|
# convert levelnames to lowercase
|
|
|
|
for level in (10, 20, 30, 40, 50):
|
|
|
|
name = logging.getLevelName(level)
|
|
|
|
logging.addLevelName(level, name.lower())
|
|
|
|
|
|
|
|
# register custom Logging class
|
|
|
|
logging.Logger.manager.setLoggerClass(Logger)
|
|
|
|
|
|
|
|
# setup basic logging to stderr
|
2019-06-21 19:56:09 +02:00
|
|
|
formatter = Formatter(LOG_FORMAT, LOG_FORMAT_DATE)
|
2019-02-13 17:39:43 +01:00
|
|
|
handler = logging.StreamHandler()
|
|
|
|
handler.setFormatter(formatter)
|
|
|
|
handler.setLevel(loglevel)
|
|
|
|
root = logging.getLogger()
|
|
|
|
root.setLevel(logging.NOTSET)
|
|
|
|
root.addHandler(handler)
|
|
|
|
|
|
|
|
return logging.getLogger("gallery-dl")
|
|
|
|
|
|
|
|
|
2020-01-30 15:11:02 +01:00
|
|
|
def configure_logging(loglevel):
|
|
|
|
root = logging.getLogger()
|
2020-02-16 23:24:56 +01:00
|
|
|
minlevel = loglevel
|
2020-01-30 15:11:02 +01:00
|
|
|
|
|
|
|
# stream logging handler
|
|
|
|
handler = root.handlers[0]
|
|
|
|
opts = config.interpolate(("output",), "log")
|
|
|
|
if opts:
|
|
|
|
if isinstance(opts, str):
|
|
|
|
opts = {"format": opts}
|
|
|
|
if handler.level == LOG_LEVEL and "level" in opts:
|
|
|
|
handler.setLevel(opts["level"])
|
|
|
|
if "format" in opts or "format-date" in opts:
|
|
|
|
handler.setFormatter(Formatter(
|
|
|
|
opts.get("format", LOG_FORMAT),
|
|
|
|
opts.get("format-date", LOG_FORMAT_DATE),
|
|
|
|
))
|
|
|
|
if minlevel > handler.level:
|
|
|
|
minlevel = handler.level
|
|
|
|
|
|
|
|
# file logging handler
|
|
|
|
handler = setup_logging_handler("logfile", lvl=loglevel)
|
|
|
|
if handler:
|
|
|
|
root.addHandler(handler)
|
|
|
|
if minlevel > handler.level:
|
|
|
|
minlevel = handler.level
|
|
|
|
|
|
|
|
root.setLevel(minlevel)
|
|
|
|
|
|
|
|
|
2019-02-13 17:39:43 +01:00
|
|
|
def setup_logging_handler(key, fmt=LOG_FORMAT, lvl=LOG_LEVEL):
|
|
|
|
"""Setup a new logging handler"""
|
2019-11-23 23:50:16 +01:00
|
|
|
opts = config.interpolate(("output",), key)
|
2019-02-13 17:39:43 +01:00
|
|
|
if not opts:
|
|
|
|
return None
|
|
|
|
if not isinstance(opts, dict):
|
|
|
|
opts = {"path": opts}
|
|
|
|
|
|
|
|
path = opts.get("path")
|
|
|
|
mode = opts.get("mode", "w")
|
|
|
|
encoding = opts.get("encoding", "utf-8")
|
|
|
|
try:
|
|
|
|
path = util.expand_path(path)
|
|
|
|
handler = logging.FileHandler(path, mode, encoding)
|
|
|
|
except (OSError, ValueError) as exc:
|
|
|
|
logging.getLogger("gallery-dl").warning(
|
|
|
|
"%s: %s", key, exc)
|
|
|
|
return None
|
|
|
|
except TypeError as exc:
|
|
|
|
logging.getLogger("gallery-dl").warning(
|
|
|
|
"%s: missing or invalid path (%s)", key, exc)
|
|
|
|
return None
|
|
|
|
|
2019-06-21 19:56:09 +02:00
|
|
|
handler.setLevel(opts.get("level", lvl))
|
|
|
|
handler.setFormatter(Formatter(
|
|
|
|
opts.get("format", fmt),
|
|
|
|
opts.get("format-date", LOG_FORMAT_DATE),
|
|
|
|
))
|
2019-02-13 17:39:43 +01:00
|
|
|
return handler
|
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Utility functions
|
|
|
|
|
|
|
|
def replace_std_streams(errors="replace"):
|
|
|
|
"""Replace standard streams and set their error handlers to 'errors'"""
|
|
|
|
for name in ("stdout", "stdin", "stderr"):
|
|
|
|
stream = getattr(sys, name)
|
2020-03-23 23:38:55 +01:00
|
|
|
if stream:
|
|
|
|
setattr(sys, name, stream.__class__(
|
|
|
|
stream.buffer,
|
|
|
|
errors=errors,
|
|
|
|
newline=stream.newlines,
|
|
|
|
line_buffering=stream.line_buffering,
|
|
|
|
))
|
2019-02-13 17:39:43 +01:00
|
|
|
|
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# Downloader output
|
|
|
|
|
2015-12-01 21:21:39 +01:00
|
|
|
def select():
|
2017-04-26 11:33:19 +02:00
|
|
|
"""Automatically select a suitable output class"""
|
2015-12-02 18:47:42 +01:00
|
|
|
pdict = {
|
2017-04-26 11:33:19 +02:00
|
|
|
"default": PipeOutput,
|
|
|
|
"pipe": PipeOutput,
|
|
|
|
"term": TerminalOutput,
|
|
|
|
"terminal": TerminalOutput,
|
|
|
|
"color": ColorOutput,
|
|
|
|
"null": NullOutput,
|
2015-12-02 18:47:42 +01:00
|
|
|
}
|
2019-11-23 23:50:16 +01:00
|
|
|
omode = config.get(("output",), "mode", "auto").lower()
|
2015-12-02 18:47:42 +01:00
|
|
|
if omode in pdict:
|
2021-05-04 18:07:08 +02:00
|
|
|
output = pdict[omode]()
|
2015-12-02 18:47:42 +01:00
|
|
|
elif omode == "auto":
|
|
|
|
if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
|
2021-05-04 18:07:08 +02:00
|
|
|
output = ColorOutput() if ANSI else TerminalOutput()
|
2015-12-02 18:47:42 +01:00
|
|
|
else:
|
2021-05-04 18:07:08 +02:00
|
|
|
output = PipeOutput()
|
2015-12-01 21:21:39 +01:00
|
|
|
else:
|
2015-12-02 18:47:42 +01:00
|
|
|
raise Exception("invalid output mode: " + omode)
|
2015-12-02 16:21:15 +01:00
|
|
|
|
2021-05-04 18:07:08 +02:00
|
|
|
if not config.get(("output",), "skip", True):
|
|
|
|
output.skip = util.identity
|
|
|
|
return output
|
|
|
|
|
2017-01-30 19:40:15 +01:00
|
|
|
|
2017-04-26 11:33:19 +02:00
|
|
|
class NullOutput():
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def start(self, path):
|
2015-12-01 21:21:39 +01:00
|
|
|
"""Print a message indicating the start of a download"""
|
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def skip(self, path):
|
2015-12-01 21:21:39 +01:00
|
|
|
"""Print a message indicating that a download has been skipped"""
|
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def success(self, path, tries):
|
2015-12-01 21:21:39 +01:00
|
|
|
"""Print a message indicating the completion of a download"""
|
|
|
|
|
2021-09-28 22:37:11 +02:00
|
|
|
def progress(self, bytes_total, bytes_downloaded, bytes_per_second):
|
|
|
|
"""Display download progress"""
|
|
|
|
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2017-04-26 11:33:19 +02:00
|
|
|
class PipeOutput(NullOutput):
|
|
|
|
|
|
|
|
def skip(self, path):
|
2021-11-28 23:57:07 +01:00
|
|
|
stdout = sys.stdout
|
|
|
|
stdout.write(CHAR_SKIP + path + "\n")
|
|
|
|
stdout.flush()
|
2017-04-26 11:33:19 +02:00
|
|
|
|
|
|
|
def success(self, path, tries):
|
2021-11-28 23:57:07 +01:00
|
|
|
stdout = sys.stdout
|
|
|
|
stdout.write(path + "\n")
|
|
|
|
stdout.flush()
|
2017-04-26 11:33:19 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TerminalOutput(NullOutput):
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def __init__(self):
|
2021-09-13 21:29:38 +02:00
|
|
|
shorten = config.get(("output",), "shorten", True)
|
|
|
|
if shorten:
|
|
|
|
func = shorten_string_eaw if shorten == "eaw" else shorten_string
|
|
|
|
limit = shutil.get_terminal_size().columns - OFFSET
|
|
|
|
sep = CHAR_ELLIPSIES
|
|
|
|
self.shorten = lambda txt: func(txt, limit, sep)
|
|
|
|
else:
|
|
|
|
self.shorten = util.identity
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def start(self, path):
|
2021-11-28 23:57:07 +01:00
|
|
|
stdout = sys.stdout
|
|
|
|
stdout.write(self.shorten(" " + path))
|
|
|
|
stdout.flush()
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def skip(self, path):
|
2021-11-28 23:57:07 +01:00
|
|
|
sys.stdout.write(self.shorten(CHAR_SKIP + path) + "\n")
|
2015-12-02 16:21:15 +01:00
|
|
|
|
|
|
|
def success(self, path, tries):
|
2021-11-28 23:57:07 +01:00
|
|
|
sys.stdout.write("\r" + self.shorten(CHAR_SUCCESS + path) + "\n")
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2021-09-28 22:37:11 +02:00
|
|
|
def progress(self, bytes_total, bytes_downloaded, bytes_per_second):
|
2021-09-29 18:38:45 +02:00
|
|
|
bdl = util.format_value(bytes_downloaded)
|
|
|
|
bps = util.format_value(bytes_per_second)
|
2021-09-28 22:37:11 +02:00
|
|
|
if bytes_total is None:
|
2021-11-28 22:11:16 +01:00
|
|
|
sys.stderr.write("\r{:>7}B {:>7}B/s ".format(bdl, bps))
|
2021-09-28 22:37:11 +02:00
|
|
|
else:
|
2021-11-28 22:11:16 +01:00
|
|
|
sys.stderr.write("\r{:>3}% {:>7}B {:>7}B/s ".format(
|
|
|
|
bytes_downloaded * 100 // bytes_total, bdl, bps))
|
2021-09-28 22:37:11 +02:00
|
|
|
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2017-04-26 11:33:19 +02:00
|
|
|
class ColorOutput(TerminalOutput):
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def start(self, path):
|
2021-11-28 23:57:07 +01:00
|
|
|
stdout = sys.stdout
|
|
|
|
stdout.write(self.shorten(path))
|
|
|
|
stdout.flush()
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def skip(self, path):
|
2021-11-28 23:57:07 +01:00
|
|
|
sys.stdout.write("\033[2m" + self.shorten(path) + "\033[0m\n")
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2015-12-02 16:21:15 +01:00
|
|
|
def success(self, path, tries):
|
2021-11-28 23:57:07 +01:00
|
|
|
sys.stdout.write("\r\033[1;32m" + self.shorten(path) + "\033[0m\n")
|
2015-12-02 16:21:15 +01:00
|
|
|
|
2015-12-01 21:21:39 +01:00
|
|
|
|
2021-09-13 21:29:38 +02:00
|
|
|
class EAWCache(dict):
|
|
|
|
|
|
|
|
def __missing__(self, key):
|
|
|
|
width = self[key] = \
|
|
|
|
2 if unicodedata.east_asian_width(key) in "WF" else 1
|
|
|
|
return width
|
|
|
|
|
|
|
|
|
|
|
|
def shorten_string(txt, limit, sep="…"):
|
|
|
|
"""Limit width of 'txt'; assume all characters have a width of 1"""
|
|
|
|
if len(txt) <= limit:
|
|
|
|
return txt
|
|
|
|
limit -= len(sep)
|
|
|
|
return txt[:limit // 2] + sep + txt[-((limit+1) // 2):]
|
|
|
|
|
|
|
|
|
|
|
|
def shorten_string_eaw(txt, limit, sep="…", cache=EAWCache()):
|
|
|
|
"""Limit width of 'txt'; check for east-asian characters with width > 1"""
|
|
|
|
char_widths = [cache[c] for c in txt]
|
|
|
|
text_width = sum(char_widths)
|
|
|
|
|
|
|
|
if text_width <= limit:
|
|
|
|
# no shortening required
|
|
|
|
return txt
|
|
|
|
|
|
|
|
limit -= len(sep)
|
|
|
|
if text_width == len(txt):
|
|
|
|
# all characters have a width of 1
|
|
|
|
return txt[:limit // 2] + sep + txt[-((limit+1) // 2):]
|
|
|
|
|
|
|
|
# wide characters
|
|
|
|
left = 0
|
|
|
|
lwidth = limit // 2
|
|
|
|
while True:
|
|
|
|
lwidth -= char_widths[left]
|
|
|
|
if lwidth < 0:
|
|
|
|
break
|
|
|
|
left += 1
|
|
|
|
|
|
|
|
right = -1
|
|
|
|
rwidth = (limit+1) // 2 + (lwidth + char_widths[left])
|
|
|
|
while True:
|
|
|
|
rwidth -= char_widths[right]
|
|
|
|
if rwidth < 0:
|
|
|
|
break
|
|
|
|
right -= 1
|
|
|
|
|
|
|
|
return txt[:left] + sep + txt[right+1:]
|
|
|
|
|
|
|
|
|
2020-05-19 21:42:11 +02:00
|
|
|
if util.WINDOWS:
|
2015-12-01 23:54:57 +01:00
|
|
|
ANSI = os.environ.get("TERM") == "ANSI"
|
|
|
|
OFFSET = 1
|
2015-12-02 18:49:49 +01:00
|
|
|
CHAR_SKIP = "# "
|
|
|
|
CHAR_SUCCESS = "* "
|
2015-12-01 23:54:57 +01:00
|
|
|
CHAR_ELLIPSIES = "..."
|
|
|
|
else:
|
|
|
|
ANSI = True
|
|
|
|
OFFSET = 0
|
2015-12-02 18:49:49 +01:00
|
|
|
CHAR_SKIP = "# "
|
|
|
|
CHAR_SUCCESS = "✔ "
|
2015-12-01 23:54:57 +01:00
|
|
|
CHAR_ELLIPSIES = "…"
|