| 1 |
|
| 2 |
|
| 3 |
n |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import sys |
| 10 |
import errno |
| 11 |
import logging |
| 12 |
import functools |
| 13 |
import collections |
| 14 |
|
| 15 |
from . import ( |
| 16 |
extractor, |
| 17 |
downloader, |
| 18 |
postprocessor, |
| 19 |
archive, |
| 20 |
config, |
| 21 |
exception, |
| 22 |
formatter, |
| 23 |
output, |
| 24 |
path, |
| 25 |
text, |
| 26 |
util, |
| 27 |
dt, |
| 28 |
version, |
| 29 |
) |
| 30 |
from .extractor.message import Message |
| 31 |
stdout_write = output.stdout_write |
| 32 |
FLAGS = util.FLAGS |
| 33 |
|
| 34 |
|
| 35 |
class Job(): |
| 36 |
"""Base class for Job types""" |
| 37 |
ulog = None |
| 38 |
_logger_adapter = output.LoggerAdapter |
| 39 |
|
| 40 |
def __init__(self, extr, parent=None): |
| 41 |
if isinstance(extr, str): |
| 42 |
extr = extractor.find(extr) |
| 43 |
if not extr: |
| 44 |
raise exception.NoExtractorError() |
| 45 |
|
| 46 |
self.extractor = extr |
| 47 |
self.pathfmt = None |
| 48 |
self.status = 0 |
| 49 |
self.kwdict = {} |
| 50 |
self.kwdict_eval = False |
| 51 |
|
| 52 |
if cfgpath := self._build_config_path(parent): |
| 53 |
if isinstance(cfgpath, list): |
| 54 |
extr.config = extr._config_shared |
| 55 |
extr.config_accumulate = extr._config_shared_accumulate |
| 56 |
extr._cfgpath = cfgpath |
| 57 |
|
| 58 |
if actions := extr.config("actions"): |
| 59 |
from .actions import LoggerAdapter, parse_logging |
| 60 |
self._logger_adapter = LoggerAdapter |
| 61 |
self._logger_actions = parse_logging(actions) |
| 62 |
|
| 63 |
path_proxy = output.PathfmtProxy(self) |
| 64 |
self._logger_extra = { |
| 65 |
"job" : self, |
| 66 |
"extractor": extr, |
| 67 |
"path" : path_proxy, |
| 68 |
"keywords" : output.KwdictProxy(self), |
| 69 |
} |
| 70 |
extr.log = self._wrap_logger(extr.log) |
| 71 |
extr.log.debug("Using %s for '%s'", extr.__class__.__name__, extr.url) |
| 72 |
|
| 73 |
self.metadata_url = extr.config2( |
| 74 |
"metadata-url", "url-metadata", "_url") |
| 75 |
self.metadata_http = extr.config2( |
| 76 |
"metadata-http", "http-metadata") |
| 77 |
metadata_path = extr.config2( |
| 78 |
"metadata-path", "path-metadata", "_path") |
| 79 |
metadata_version = extr.config2( |
| 80 |
"metadata-version", "version-metadata") |
| 81 |
metadata_extractor = extr.config2( |
| 82 |
"metadata-extractor", "extractor-metadata", "_extr") |
| 83 |
|
| 84 |
if metadata_path: |
| 85 |
self.kwdict[metadata_path] = path_proxy |
| 86 |
if metadata_extractor: |
| 87 |
self.kwdict[metadata_extractor] = extr |
| 88 |
if metadata_version: |
| 89 |
self.kwdict[metadata_version] = { |
| 90 |
"version" : version.__version__, |
| 91 |
"is_executable" : util.EXECUTABLE, |
| 92 |
"current_git_head": util.git_head() |
| 93 |
} |
| 94 |
|
| 95 |
kwdict = extr.config("keywords") |
| 96 |
if kwdict_global := extr.config("keywords-global"): |
| 97 |
kwdict = {**kwdict_global, **kwdict} if kwdict else kwdict_global |
| 98 |
elif not kwdict: |
| 99 |
return |
| 100 |
|
| 101 |
if extr.config("keywords-eval"): |
| 102 |
self.kwdict_eval = [] |
| 103 |
for key, value in kwdict.items(): |
| 104 |
if isinstance(value, str): |
| 105 |
fmt = formatter.parse(value, None, util.identity) |
| 106 |
self.kwdict_eval.append((key, fmt.format_map)) |
| 107 |
else: |
| 108 |
self.kwdict[key] = value |
| 109 |
else: |
| 110 |
self.kwdict.update(kwdict) |
| 111 |
|
| 112 |
def _build_config_path(self, parent): |
| 113 |
extr = self.extractor |
| 114 |
cfgpath = [] |
| 115 |
|
| 116 |
if parent is None: |
| 117 |
self.parents = () |
| 118 |
else: |
| 119 |
pextr = parent.extractor |
| 120 |
if extr.category == pextr.category or \ |
| 121 |
extr.category in parent.parents: |
| 122 |
parents = parent.parents |
| 123 |
else: |
| 124 |
parents = parent.parents + (pextr.category,) |
| 125 |
self.parents = parents |
| 126 |
|
| 127 |
if pextr.config("category-transfer", pextr.categorytransfer): |
| 128 |
extr.category = pextr.category |
| 129 |
extr.subcategory = pextr.subcategory |
| 130 |
return pextr._cfgpath |
| 131 |
|
| 132 |
if parents: |
| 133 |
sub = extr.subcategory |
| 134 |
for category in parents: |
| 135 |
cat = f"{category}>{extr.category}" |
| 136 |
cfgpath.append((cat, sub)) |
| 137 |
cfgpath.append((category + ">*", sub)) |
| 138 |
cfgpath.append((extr.category, sub)) |
| 139 |
|
| 140 |
if extr.basecategory: |
| 141 |
if not cfgpath: |
| 142 |
cfgpath.append((extr.category, extr.subcategory)) |
| 143 |
if extr.basesubcategory: |
| 144 |
cfgpath.append((extr.basesubcategory, extr.subcategory)) |
| 145 |
cfgpath.append((extr.basecategory, extr.subcategory)) |
| 146 |
|
| 147 |
return cfgpath |
| 148 |
|
| 149 |
def run(self): |
| 150 |
"""Execute or run the job""" |
| 151 |
extractor = self.extractor |
| 152 |
log = extractor.log |
| 153 |
|
| 154 |
self._init() |
| 155 |
|
| 156 |
|
| 157 |
sleep = util.build_duration_func( |
| 158 |
extractor.config("sleep-extractor")) |
| 159 |
if sleep is not None: |
| 160 |
extractor.sleep(sleep(), "extractor") |
| 161 |
|
| 162 |
try: |
| 163 |
msg = self.dispatch(extractor) |
| 164 |
except exception.StopExtraction as exc: |
| 165 |
if exc.depth > 1 and exc.target != extractor.__class__.subcategory: |
| 166 |
exc.depth -= 1 |
| 167 |
raise |
| 168 |
pass |
| 169 |
except exception.AbortExtraction as exc: |
| 170 |
log.traceback(exc) |
| 171 |
log.error(exc.message) |
| 172 |
self.status |= exc.code |
| 173 |
except (exception.TerminateExtraction, exception.RestartExtraction): |
| 174 |
raise |
| 175 |
except exception.GalleryDLException as exc: |
| 176 |
log.error("%s: %s", exc.__class__.__name__, exc) |
| 177 |
log.traceback(exc) |
| 178 |
self.status |= exc.code |
| 179 |
except OSError as exc: |
| 180 |
log.traceback(exc) |
| 181 |
if (name := exc.__class__.__name__) == "JSONDecodeError": |
| 182 |
log.error("Failed to parse JSON data: %s: %s", name, exc) |
| 183 |
self.status |= 1 |
| 184 |
else: |
| 185 |
log.error("Unable to download data: %s: %s", name, exc) |
| 186 |
self.status |= 128 |
| 187 |
except Exception as exc: |
| 188 |
log.error(("An unexpected error occurred: %s - %s. " |
| 189 |
"Please run gallery-dl again with the --verbose flag, " |
| 190 |
"copy its output and report this issue on " |
| 191 |
"https://codeberg.org/mikf/gallery-dl/issues ."), |
| 192 |
exc.__class__.__name__, exc) |
| 193 |
log.traceback(exc) |
| 194 |
self.status |= 1 |
| 195 |
except BaseException: |
| 196 |
self.status |= 1 |
| 197 |
raise |
| 198 |
else: |
| 199 |
if msg is None: |
| 200 |
log.info("No results for %s", extractor.url) |
| 201 |
finally: |
| 202 |
if extractor.status: |
| 203 |
self.status |= extractor.status |
| 204 |
self.handle_finalize() |
| 205 |
if extractor.finalize is not None: |
| 206 |
extractor.finalize(self.status) |
| 207 |
|
| 208 |
return self.status |
| 209 |
|
| 210 |
def dispatch(self, messages): |
| 211 |
"""Call the appropriate message handler""" |
| 212 |
msg = None |
| 213 |
process = True |
| 214 |
metadata_url = self.metadata_url |
| 215 |
|
| 216 |
if follow := self.extractor.config("follow"): |
| 217 |
follow = self._follow_parse(follow) |
| 218 |
follow_urls = follow_kwdict = None |
| 219 |
else: |
| 220 |
follow = follow_urls = None |
| 221 |
|
| 222 |
for msg, url, kwdict in messages: |
| 223 |
|
| 224 |
if msg == Message.Directory: |
| 225 |
if follow_urls is not None: |
| 226 |
for furl in follow_urls: |
| 227 |
if metadata_url is not None: |
| 228 |
follow_kwdict[metadata_url] = furl |
| 229 |
if self.pred_queue(furl, follow_kwdict): |
| 230 |
self.handle_queue(furl, follow_kwdict) |
| 231 |
follow_urls = None |
| 232 |
|
| 233 |
self.update_kwdict(kwdict) |
| 234 |
if self.pred_post(url, kwdict): |
| 235 |
process = True |
| 236 |
self.handle_directory(kwdict) |
| 237 |
if follow is not None: |
| 238 |
follow_urls = self._follow_collect(follow(kwdict)) |
| 239 |
if follow_urls is not None: |
| 240 |
follow_kwdict = kwdict.copy() |
| 241 |
else: |
| 242 |
process = None |
| 243 |
if FLAGS.POST is not None: |
| 244 |
FLAGS.process("POST") |
| 245 |
|
| 246 |
elif process is None: |
| 247 |
continue |
| 248 |
elif FLAGS.POST is False: |
| 249 |
FLAGS.POST = process = None |
| 250 |
continue |
| 251 |
|
| 252 |
elif msg == Message.Url: |
| 253 |
if metadata_url is not None: |
| 254 |
kwdict[metadata_url] = url |
| 255 |
self.update_kwdict(kwdict) |
| 256 |
if self.pred_url(url, kwdict): |
| 257 |
if FLAGS.FILE is False: |
| 258 |
FLAGS.FILE = None |
| 259 |
continue |
| 260 |
self.handle_url(url, kwdict) |
| 261 |
if FLAGS.FILE is not None: |
| 262 |
FLAGS.process("FILE") |
| 263 |
|
| 264 |
elif msg == Message.Queue: |
| 265 |
self.update_kwdict(kwdict) |
| 266 |
if metadata_url is not None: |
| 267 |
kwdict[metadata_url] = url |
| 268 |
if self.pred_queue(url, kwdict): |
| 269 |
if FLAGS.CHILD is False: |
| 270 |
FLAGS.CHILD = None |
| 271 |
continue |
| 272 |
self.handle_queue(url, kwdict) |
| 273 |
if FLAGS.CHILD is not None: |
| 274 |
FLAGS.process("CHILD") |
| 275 |
|
| 276 |
if follow_urls is not None: |
| 277 |
for furl in follow_urls: |
| 278 |
if metadata_url is not None: |
| 279 |
follow_kwdict[metadata_url] = furl |
| 280 |
if self.pred_queue(furl, follow_kwdict): |
| 281 |
self.handle_queue(furl, follow_kwdict) |
| 282 |
|
| 283 |
return msg |
| 284 |
|
| 285 |
def handle_url(self, url, kwdict): |
| 286 |
"""Handle Message.Url""" |
| 287 |
|
| 288 |
def handle_directory(self, kwdict): |
| 289 |
"""Handle Message.Directory""" |
| 290 |
|
| 291 |
def handle_queue(self, url, kwdict): |
| 292 |
"""Handle Message.Queue""" |
| 293 |
|
| 294 |
def handle_finalize(self): |
| 295 |
"""Handle job finalization""" |
| 296 |
|
| 297 |
def update_kwdict(self, kwdict): |
| 298 |
"""Update 'kwdict' with additional metadata""" |
| 299 |
extr = self.extractor |
| 300 |
kwdict["category"] = extr.category |
| 301 |
kwdict["subcategory"] = extr.subcategory |
| 302 |
if self.metadata_http: |
| 303 |
kwdict.pop(self.metadata_http, None) |
| 304 |
if extr.kwdict: |
| 305 |
kwdict.update(extr.kwdict) |
| 306 |
if self.kwdict: |
| 307 |
kwdict.update(self.kwdict) |
| 308 |
if self.kwdict_eval: |
| 309 |
for key, valuegen in self.kwdict_eval: |
| 310 |
kwdict[key] = valuegen(kwdict) |
| 311 |
|
| 312 |
def initialize(self): |
| 313 |
pass |
| 314 |
|
| 315 |
def _init(self): |
| 316 |
extr = self.extractor |
| 317 |
|
| 318 |
extr.initialize() |
| 319 |
self.pred_url = self._prepare_predicates( |
| 320 |
"file", "image", extr.skip_files) |
| 321 |
self.pred_post = self._prepare_predicates( |
| 322 |
"post", None, extr.skip_posts) |
| 323 |
self.pred_queue = self._prepare_predicates( |
| 324 |
"child", "chapter", extr.skip_children) |
| 325 |
|
| 326 |
init = extr.config("init", False) |
| 327 |
if init and init != "lazy": |
| 328 |
self.initialize() |
| 329 |
|
| 330 |
def _follow_parse(self, follow): |
| 331 |
if isinstance(follow, str): |
| 332 |
return formatter.parse(follow, None, util.identity).format_map |
| 333 |
|
| 334 |
follow = [formatter.parse(f, None, util.identity).format_map |
| 335 |
for f in follow] |
| 336 |
self._follow_collect = self._follow_collect_many |
| 337 |
return lambda kwdict: [f(kwdict) for f in follow] |
| 338 |
|
| 339 |
def _follow_collect(self, source): |
| 340 |
if not source: |
| 341 |
return None |
| 342 |
if isinstance(source, list): |
| 343 |
return source |
| 344 |
if isinstance(source, str): |
| 345 |
if urls := text.extract_urls(source): |
| 346 |
return urls |
| 347 |
|
| 348 |
def _follow_collect_many(self, sources): |
| 349 |
urls = [] |
| 350 |
for source in sources: |
| 351 |
if not source: |
| 352 |
continue |
| 353 |
elif isinstance(source, list): |
| 354 |
urls.extend(source) |
| 355 |
elif isinstance(source, str): |
| 356 |
urls.extend(text.extract_urls(source)) |
| 357 |
return urls or None |
| 358 |
|
| 359 |
def _prepare_predicates(self, target, alt=None, skip=None): |
| 360 |
predicates = [] |
| 361 |
extr = self.extractor |
| 362 |
|
| 363 |
if extr.config(target + "-unique") or \ |
| 364 |
alt is not None and extr.config(alt + "-unique"): |
| 365 |
predicates.append(util.predicate_unique()) |
| 366 |
|
| 367 |
if (pfilter := extr.config(target + "-filter")) or \ |
| 368 |
alt is not None and (pfilter := extr.config(alt + "-filter")): |
| 369 |
try: |
| 370 |
predicates.append(util.predicate_filter(pfilter, target)) |
| 371 |
except (SyntaxError, ValueError, TypeError) as exc: |
| 372 |
extr.log.warning(exc) |
| 373 |
|
| 374 |
if target == "post": |
| 375 |
if dta := extr.config("date-after"): |
| 376 |
dta = dt.convert(dta) |
| 377 |
if dtb := extr.config("date-before"): |
| 378 |
dtb = dt.convert(dtb) |
| 379 |
if dta or dtb: |
| 380 |
predicates.append(util.predicate_date( |
| 381 |
dtb or None, dta or None, extr.skip_date)) |
| 382 |
|
| 383 |
if ((wl := extr.config2("whitelist-tags", "tags-whitelist")) or |
| 384 |
(bl := extr.config2("blacklist-tags", "tags-blacklist"))): |
| 385 |
tl = wl or bl |
| 386 |
if tl == "/import": |
| 387 |
if extr.import_blacklist is None: |
| 388 |
extr.log.warning("Blacklist import unsupported") |
| 389 |
else: |
| 390 |
extr.log.info("Importing account blacklist") |
| 391 |
try: |
| 392 |
tl = extr.import_blacklist() |
| 393 |
except Exception as exc: |
| 394 |
extr.log.error( |
| 395 |
"%s: %s", exc.__class__.__name__, exc) |
| 396 |
tl = () |
| 397 |
predicates.append(util.predicate_tags(tl, bool(wl))) |
| 398 |
|
| 399 |
if (prange := extr.config(target + "-range")) or \ |
| 400 |
alt is not None and (prange := extr.config(alt + "-range")): |
| 401 |
try: |
| 402 |
if pfilter: |
| 403 |
skip = None |
| 404 |
flag = target if alt is not None else None |
| 405 |
predicates.append(util.predicate_range(prange, skip, flag)) |
| 406 |
except ValueError as exc: |
| 407 |
extr.log.warning("invalid %s range: %s", target, exc) |
| 408 |
|
| 409 |
return util.predicate_build(predicates) |
| 410 |
|
| 411 |
def get_logger(self, name): |
| 412 |
return self._wrap_logger(logging.getLogger(name)) |
| 413 |
|
| 414 |
def _wrap_logger(self, logger): |
| 415 |
return self._logger_adapter(logger, self) |
| 416 |
|
| 417 |
def _write_unsupported(self, url): |
| 418 |
if self.ulog is not None: |
| 419 |
self.ulog.info(url) |
| 420 |
|
| 421 |
|
| 422 |
class DownloadJob(Job): |
| 423 |
"""Download images into appropriate directory/filename locations""" |
| 424 |
|
| 425 |
def __init__(self, url, parent=None): |
| 426 |
Job.__init__(self, url, parent) |
| 427 |
self.log = self.get_logger("download") |
| 428 |
self.fallback = None |
| 429 |
self.archive = None |
| 430 |
self.sleep = None |
| 431 |
self.hooks = () |
| 432 |
self.downloaders = {} |
| 433 |
self.out = output.select() |
| 434 |
self.visited = set() if parent is None else parent.visited |
| 435 |
self._extractor_filter = None |
| 436 |
self._skipcnt = 0 |
| 437 |
|
| 438 |
def handle_url(self, url, kwdict): |
| 439 |
"""Download the resource specified in 'url'""" |
| 440 |
hooks = self.hooks |
| 441 |
pathfmt = self.pathfmt |
| 442 |
archive = self.archive |
| 443 |
|
| 444 |
|
| 445 |
pathfmt.set_filename(kwdict) |
| 446 |
|
| 447 |
if "prepare" in hooks: |
| 448 |
for callback in hooks["prepare"]: |
| 449 |
callback(pathfmt) |
| 450 |
|
| 451 |
if archive is not None and archive.check(kwdict): |
| 452 |
pathfmt.fix_extension() |
| 453 |
self.handle_skip() |
| 454 |
return |
| 455 |
|
| 456 |
if pathfmt.extension and not self.metadata_http: |
| 457 |
pathfmt.build_path() |
| 458 |
|
| 459 |
if pathfmt.exists(): |
| 460 |
if archive is not None and self._archive_write_skip: |
| 461 |
archive.add(kwdict) |
| 462 |
self.handle_skip() |
| 463 |
return |
| 464 |
|
| 465 |
if "prepare-after" in hooks: |
| 466 |
for callback in hooks["prepare-after"]: |
| 467 |
callback(pathfmt) |
| 468 |
|
| 469 |
if kwdict.pop("_file_recheck", False) and pathfmt.exists(): |
| 470 |
if archive is not None and self._archive_write_skip: |
| 471 |
archive.add(kwdict) |
| 472 |
self.handle_skip() |
| 473 |
return |
| 474 |
|
| 475 |
if self.sleep is not None: |
| 476 |
self.extractor.sleep(self.sleep(), "download") |
| 477 |
|
| 478 |
|
| 479 |
failed = False |
| 480 |
try: |
| 481 |
if not self.download(url): |
| 482 |
|
| 483 |
fallback = kwdict.get("_fallback", ()) if self.fallback else () |
| 484 |
for num, url in enumerate(fallback, 1): |
| 485 |
util.remove_file(pathfmt.temppath) |
| 486 |
self.log.info("Trying fallback URL #%d", num) |
| 487 |
if self.download(url): |
| 488 |
break |
| 489 |
else: |
| 490 |
failed = True |
| 491 |
except exception.StopDownload: |
| 492 |
failed = True |
| 493 |
|
| 494 |
if failed: |
| 495 |
self.status |= 4 |
| 496 |
self.log.error("Failed to download %s", pathfmt.filename or url) |
| 497 |
if "error" in hooks: |
| 498 |
for callback in hooks["error"]: |
| 499 |
callback(pathfmt) |
| 500 |
return |
| 501 |
|
| 502 |
if not pathfmt.temppath: |
| 503 |
if archive is not None and self._archive_write_skip: |
| 504 |
archive.add(kwdict) |
| 505 |
self.handle_skip() |
| 506 |
return |
| 507 |
|
| 508 |
|
| 509 |
if "file" in hooks: |
| 510 |
for callback in hooks["file"]: |
| 511 |
callback(pathfmt) |
| 512 |
|
| 513 |
|
| 514 |
if FLAGS.DOWNLOAD is not None: |
| 515 |
FLAGS.DOWNLOAD = None |
| 516 |
self.status |= 4 |
| 517 |
self.log.error("Failed to download %s", pathfmt.filename or url) |
| 518 |
if "error" in hooks: |
| 519 |
for callback in hooks["error"]: |
| 520 |
callback(pathfmt) |
| 521 |
return |
| 522 |
|
| 523 |
|
| 524 |
pathfmt.finalize() |
| 525 |
self.out.success(pathfmt.path) |
| 526 |
self._skipcnt = 0 |
| 527 |
if archive is not None and self._archive_write_file: |
| 528 |
archive.add(kwdict) |
| 529 |
if "after" in hooks: |
| 530 |
for callback in hooks["after"]: |
| 531 |
callback(pathfmt) |
| 532 |
if archive is not None and self._archive_write_after: |
| 533 |
archive.add(kwdict) |
| 534 |
|
| 535 |
def handle_directory(self, kwdict): |
| 536 |
"""Set and create the target directory for downloads""" |
| 537 |
if self.pathfmt is None: |
| 538 |
self.initialize(kwdict) |
| 539 |
else: |
| 540 |
if "post-after" in self.hooks: |
| 541 |
for callback in self.hooks["post-after"]: |
| 542 |
callback(self.pathfmt) |
| 543 |
if FLAGS.POST is not None: |
| 544 |
FLAGS.process("POST") |
| 545 |
self.pathfmt.set_directory(kwdict) |
| 546 |
if "post" in self.hooks: |
| 547 |
for callback in self.hooks["post"]: |
| 548 |
callback(self.pathfmt) |
| 549 |
|
| 550 |
def handle_queue(self, url, kwdict): |
| 551 |
if url in self.visited: |
| 552 |
return |
| 553 |
self.visited.add(url) |
| 554 |
|
| 555 |
if "child" in self.hooks: |
| 556 |
pathfmt = self.pathfmt |
| 557 |
pathfmt.kwdict = kwdict |
| 558 |
for callback in self.hooks["child"]: |
| 559 |
callback(pathfmt) |
| 560 |
|
| 561 |
if cls := kwdict.get("_extractor"): |
| 562 |
extr = cls.from_url(url) |
| 563 |
else: |
| 564 |
if extr := extractor.find(url): |
| 565 |
if self._extractor_filter is None: |
| 566 |
self._extractor_filter = self._build_extractor_filter() |
| 567 |
if not self._extractor_filter(extr): |
| 568 |
extr = None |
| 569 |
|
| 570 |
if extr: |
| 571 |
job = self.__class__(extr, self) |
| 572 |
pfmt = self.pathfmt |
| 573 |
pextr = self.extractor |
| 574 |
parent = pextr.config("parent", pextr.parent) |
| 575 |
|
| 576 |
if pfmt and pextr.config("parent-directory", parent): |
| 577 |
extr._parentdir = pfmt.directory |
| 578 |
else: |
| 579 |
extr._parentdir = pextr._parentdir |
| 580 |
|
| 581 |
if pmeta := pextr.config2( |
| 582 |
"parent-metadata", "metadata-parent", parent or "_parent"): |
| 583 |
if isinstance(pmeta, str): |
| 584 |
data = self.kwdict.copy() |
| 585 |
if kwdict: |
| 586 |
data.update(kwdict) |
| 587 |
job.kwdict[pmeta] = data |
| 588 |
else: |
| 589 |
if self.kwdict: |
| 590 |
job.kwdict.update(self.kwdict) |
| 591 |
if kwdict: |
| 592 |
job.kwdict.update(kwdict) |
| 593 |
if "_extractor" in kwdict: |
| 594 |
del job.kwdict["_extractor"] |
| 595 |
|
| 596 |
if pextr.config("parent-session", parent): |
| 597 |
extr.session = pextr.session |
| 598 |
|
| 599 |
while True: |
| 600 |
try: |
| 601 |
if pextr.config("parent-skip", parent): |
| 602 |
job._skipcnt = self._skipcnt |
| 603 |
status = job.run() |
| 604 |
self._skipcnt = job._skipcnt |
| 605 |
else: |
| 606 |
status = job.run() |
| 607 |
|
| 608 |
if status: |
| 609 |
self.status |= status |
| 610 |
if (status & 95 and |
| 611 |
"_fallback" in kwdict and self.fallback): |
| 612 |
fallback = kwdict["_fallback"] = \ |
| 613 |
iter(kwdict["_fallback"]) |
| 614 |
try: |
| 615 |
url = next(fallback) |
| 616 |
except StopIteration: |
| 617 |
pass |
| 618 |
else: |
| 619 |
pextr.log.info("Downloading fallback URL") |
| 620 |
text.nameext_from_url(url, kwdict) |
| 621 |
if kwdict["filename"].startswith(( |
| 622 |
"HLS", "DASH")): |
| 623 |
kwdict["filename"] = url.rsplit("/", 2)[-2] |
| 624 |
if url.startswith("ytdl:"): |
| 625 |
kwdict["extension"] = "mp4" |
| 626 |
self.handle_url(url, kwdict) |
| 627 |
break |
| 628 |
except exception.RestartExtraction: |
| 629 |
pass |
| 630 |
|
| 631 |
else: |
| 632 |
self._write_unsupported(url) |
| 633 |
|
| 634 |
if "child-after" in self.hooks: |
| 635 |
pathfmt = self.pathfmt |
| 636 |
pathfmt.kwdict = kwdict |
| 637 |
for callback in self.hooks["child-after"]: |
| 638 |
callback(pathfmt) |
| 639 |
|
| 640 |
def handle_finalize(self): |
| 641 |
if self.archive is not None: |
| 642 |
if not self.status: |
| 643 |
self.archive.finalize() |
| 644 |
self.archive.close() |
| 645 |
|
| 646 |
if pathfmt := self.pathfmt: |
| 647 |
hooks = self.hooks |
| 648 |
if "post-after" in hooks: |
| 649 |
for callback in hooks["post-after"]: |
| 650 |
callback(pathfmt) |
| 651 |
|
| 652 |
self.extractor.cookies_store() |
| 653 |
|
| 654 |
if self.status: |
| 655 |
if "finalize-error" in hooks: |
| 656 |
for callback in hooks["finalize-error"]: |
| 657 |
callback(pathfmt) |
| 658 |
else: |
| 659 |
if "finalize-success" in hooks: |
| 660 |
for callback in hooks["finalize-success"]: |
| 661 |
callback(pathfmt) |
| 662 |
if "finalize" in hooks: |
| 663 |
for callback in hooks["finalize"]: |
| 664 |
callback(pathfmt) |
| 665 |
|
| 666 |
def handle_skip(self): |
| 667 |
pathfmt = self.pathfmt |
| 668 |
if "skip" in self.hooks: |
| 669 |
for callback in self.hooks["skip"]: |
| 670 |
callback(pathfmt) |
| 671 |
self.out.skip(pathfmt.path) |
| 672 |
|
| 673 |
if self._skipexc is not None: |
| 674 |
if self._skipftr is None or self._skipftr(pathfmt.kwdict): |
| 675 |
self._skipcnt += 1 |
| 676 |
if self._skipcnt >= self._skipmax: |
| 677 |
raise self._skipexc |
| 678 |
|
| 679 |
if self.sleep_skip is not None: |
| 680 |
self.extractor.sleep(self.sleep_skip(), "skip") |
| 681 |
|
| 682 |
def download(self, url): |
| 683 |
"""Download 'url'""" |
| 684 |
if downloader := self.get_downloader(url[:url.find(":")]): |
| 685 |
try: |
| 686 |
return downloader.download(url, self.pathfmt) |
| 687 |
except OSError as exc: |
| 688 |
if exc.errno == errno.ENOSPC: |
| 689 |
raise |
| 690 |
self.log.warning("%s: %s", exc.__class__.__name__, exc) |
| 691 |
return False |
| 692 |
self._write_unsupported(url) |
| 693 |
return False |
| 694 |
|
| 695 |
def get_downloader(self, scheme): |
| 696 |
"""Return a downloader suitable for 'scheme'""" |
| 697 |
try: |
| 698 |
return self.downloaders[scheme] |
| 699 |
except KeyError: |
| 700 |
pass |
| 701 |
|
| 702 |
cls = downloader.find(scheme) |
| 703 |
if cls and config.get(("downloader", cls.scheme), "enabled", True): |
| 704 |
instance = cls(self) |
| 705 |
else: |
| 706 |
instance = None |
| 707 |
self.log.error("'%s:' URLs are not supported/enabled", scheme) |
| 708 |
|
| 709 |
if cls and cls.scheme == "http": |
| 710 |
self.downloaders["http"] = self.downloaders["https"] = instance |
| 711 |
else: |
| 712 |
self.downloaders[scheme] = instance |
| 713 |
return instance |
| 714 |
|
| 715 |
def initialize(self, kwdict=None): |
| 716 |
"""initialize PathFormat, postprocessors, archive, options, etc""" |
| 717 |
extr = self.extractor |
| 718 |
cfg = extr.config |
| 719 |
|
| 720 |
pathfmt = self.pathfmt = path.PathFormat(extr) |
| 721 |
if kwdict is not None: |
| 722 |
pathfmt.set_directory(kwdict) |
| 723 |
|
| 724 |
self.sleep = util.build_duration_func( |
| 725 |
cfg("sleep", extr.download_interval)) |
| 726 |
self.sleep_skip = util.build_duration_func( |
| 727 |
cfg("sleep-skip")) |
| 728 |
self.fallback = cfg("fallback", True) |
| 729 |
if not cfg("download", True): |
| 730 |
|
| 731 |
self.download = pathfmt.fix_extension |
| 732 |
|
| 733 |
if archive_path := cfg("archive"): |
| 734 |
archive_table = cfg("archive-table") |
| 735 |
archive_prefix = cfg("archive-prefix") |
| 736 |
if archive_prefix is None: |
| 737 |
archive_prefix = extr.category if archive_table is None else "" |
| 738 |
|
| 739 |
archive_format = cfg("archive-format") |
| 740 |
if archive_format is None: |
| 741 |
archive_format = extr.archive_fmt |
| 742 |
|
| 743 |
try: |
| 744 |
self.archive = archive.connect( |
| 745 |
archive_path, |
| 746 |
archive_prefix, |
| 747 |
archive_format, |
| 748 |
archive_table, |
| 749 |
cfg("archive-mode"), |
| 750 |
cfg("archive-pragma"), |
| 751 |
pathfmt, |
| 752 |
) |
| 753 |
except Exception as exc: |
| 754 |
extr.log.warning( |
| 755 |
"Failed to open download archive at '%s' (%s: %s)", |
| 756 |
archive_path, exc.__class__.__name__, exc) |
| 757 |
else: |
| 758 |
extr.log.debug("Using download archive '%s'", archive_path) |
| 759 |
|
| 760 |
events = cfg("archive-event") |
| 761 |
if events is None: |
| 762 |
self._archive_write_file = True |
| 763 |
self._archive_write_skip = False |
| 764 |
self._archive_write_after = False |
| 765 |
else: |
| 766 |
if isinstance(events, str): |
| 767 |
events = events.split(",") |
| 768 |
self._archive_write_file = ("file" in events) |
| 769 |
self._archive_write_skip = ("skip" in events) |
| 770 |
self._archive_write_after = ("after" in events) |
| 771 |
|
| 772 |
if skip := cfg("skip", True): |
| 773 |
self._skipexc = None |
| 774 |
if skip == "enumerate": |
| 775 |
pathfmt.check_file = pathfmt._enum_file |
| 776 |
elif isinstance(skip, str): |
| 777 |
skip, _, smax = skip.partition(":") |
| 778 |
if skip == "abort": |
| 779 |
smax, _, sarg = smax.partition(":") |
| 780 |
self._skipexc = exception.StopExtraction(sarg or None) |
| 781 |
elif skip == "terminate": |
| 782 |
self._skipexc = exception.TerminateExtraction |
| 783 |
elif skip == "exit": |
| 784 |
self._skipexc = SystemExit |
| 785 |
self._skipmax = text.parse_int(smax) |
| 786 |
|
| 787 |
if skip_filter := cfg("skip-filter"): |
| 788 |
self._skipftr = util.compile_filter(skip_filter) |
| 789 |
else: |
| 790 |
self._skipftr = None |
| 791 |
else: |
| 792 |
|
| 793 |
pathfmt.exists = lambda x=None: False |
| 794 |
if self.archive is not None: |
| 795 |
self.archive.check = pathfmt.exists |
| 796 |
|
| 797 |
if not cfg("postprocess", True): |
| 798 |
return |
| 799 |
|
| 800 |
if postprocessors := extr.config_accumulate("postprocessors"): |
| 801 |
self.hooks = collections.defaultdict(list) |
| 802 |
|
| 803 |
pp_log = self.get_logger("postprocessor") |
| 804 |
pp_conf = config.get((), "postprocessor") or {} |
| 805 |
pp_opts = cfg("postprocessor-options") |
| 806 |
pp_list = [] |
| 807 |
|
| 808 |
for pp_dict in postprocessors: |
| 809 |
if isinstance(pp_dict, str): |
| 810 |
pp_dict = pp_conf.get(pp_dict) or {"name": pp_dict} |
| 811 |
elif "type" in pp_dict: |
| 812 |
pp_type = pp_dict["type"] |
| 813 |
if pp_type in pp_conf: |
| 814 |
pp_dict = {**pp_conf[pp_type], **pp_dict} |
| 815 |
if "name" not in pp_dict: |
| 816 |
pp_dict["name"] = pp_type |
| 817 |
if pp_opts: |
| 818 |
pp_dict = {**pp_dict, **pp_opts} |
| 819 |
|
| 820 |
clist = pp_dict.get("whitelist") |
| 821 |
if clist is not None: |
| 822 |
negate = False |
| 823 |
else: |
| 824 |
clist = pp_dict.get("blacklist") |
| 825 |
negate = True |
| 826 |
if clist and not util.build_extractor_filter( |
| 827 |
clist, negate)(extr): |
| 828 |
continue |
| 829 |
|
| 830 |
name = pp_dict.get("name", "") |
| 831 |
if "__init__" not in pp_dict: |
| 832 |
name, sep, event = name.rpartition("@") |
| 833 |
if sep: |
| 834 |
pp_dict["name"] = name |
| 835 |
if "event" not in pp_dict: |
| 836 |
pp_dict["event"] = event |
| 837 |
else: |
| 838 |
name = event |
| 839 |
|
| 840 |
name, sep, mode = name.rpartition("/") |
| 841 |
if sep: |
| 842 |
pp_dict["name"] = name |
| 843 |
if "mode" not in pp_dict: |
| 844 |
pp_dict["mode"] = mode |
| 845 |
else: |
| 846 |
name = mode |
| 847 |
|
| 848 |
pp_dict["__init__"] = None |
| 849 |
|
| 850 |
pp_cls = postprocessor.find(name) |
| 851 |
if pp_cls is None: |
| 852 |
pp_log.warning("module '%s' not found", name) |
| 853 |
continue |
| 854 |
try: |
| 855 |
pp_obj = pp_cls(self, pp_dict) |
| 856 |
except Exception as exc: |
| 857 |
pp_log.traceback(exc) |
| 858 |
pp_log.error("'%s' initialization failed: %s: %s", |
| 859 |
name, exc.__class__.__name__, exc) |
| 860 |
else: |
| 861 |
pp_list.append(pp_obj) |
| 862 |
|
| 863 |
if pp_list: |
| 864 |
extr.log.debug("Active postprocessor modules: %s", pp_list) |
| 865 |
if "init" in self.hooks: |
| 866 |
for callback in self.hooks["init"]: |
| 867 |
callback(pathfmt) |
| 868 |
|
| 869 |
def register_hooks(self, hooks, options=None): |
| 870 |
expr = options.get("filter") if options else None |
| 871 |
|
| 872 |
if expr: |
| 873 |
condition = util.compile_filter(expr) |
| 874 |
for hook, callback in hooks.items(): |
| 875 |
self.hooks[hook].append(functools.partial( |
| 876 |
_call_hook_condition, callback, condition)) |
| 877 |
else: |
| 878 |
for hook, callback in hooks.items(): |
| 879 |
self.hooks[hook].append(callback) |
| 880 |
|
| 881 |
def _build_extractor_filter(self): |
| 882 |
clist = self.extractor.config("whitelist") |
| 883 |
if clist is not None: |
| 884 |
negate = False |
| 885 |
special = None |
| 886 |
else: |
| 887 |
clist = self.extractor.config("blacklist") |
| 888 |
negate = True |
| 889 |
special = util.SPECIAL_EXTRACTORS |
| 890 |
if clist is None: |
| 891 |
clist = (self.extractor.category,) |
| 892 |
|
| 893 |
return util.build_extractor_filter(clist, negate, special) |
| 894 |
|
| 895 |
|
| 896 |
def _call_hook_condition(callback, condition, pathfmt): |
| 897 |
if condition(pathfmt.kwdict): |
| 898 |
callback(pathfmt) |
| 899 |
|
| 900 |
|
| 901 |
class SimulationJob(DownloadJob): |
| 902 |
"""Simulate the extraction process without downloading anything""" |
| 903 |
|
| 904 |
def handle_url(self, url, kwdict): |
| 905 |
ext = kwdict["extension"] or "jpg" |
| 906 |
kwdict["extension"] = self.pathfmt.extension_map(ext, ext) |
| 907 |
if self.sleep is not None: |
| 908 |
self.extractor.sleep(self.sleep(), "download") |
| 909 |
if self.archive is not None and self._archive_write_skip: |
| 910 |
self.archive.add(kwdict) |
| 911 |
self.out.skip(self.pathfmt.build_filename(kwdict)) |
| 912 |
|
| 913 |
def handle_directory(self, kwdict): |
| 914 |
if self.pathfmt is None: |
| 915 |
self.initialize() |
| 916 |
|
| 917 |
|
| 918 |
class KeywordJob(Job): |
| 919 |
"""Print available keywords""" |
| 920 |
|
| 921 |
def __init__(self, url, parent=None): |
| 922 |
Job.__init__(self, url, parent) |
| 923 |
self.private = config.get(("output",), "private") |
| 924 |
|
| 925 |
def handle_url(self, url, kwdict): |
| 926 |
stdout_write("\nKeywords for filenames and --filter:\n" |
| 927 |
"------------------------------------\n") |
| 928 |
|
| 929 |
if self.metadata_http and url.startswith("http"): |
| 930 |
kwdict[self.metadata_http] = util.extract_headers( |
| 931 |
self.extractor.request(url, method="HEAD")) |
| 932 |
|
| 933 |
self.print_kwdict(kwdict) |
| 934 |
raise exception.StopExtraction() |
| 935 |
|
| 936 |
def handle_directory(self, kwdict): |
| 937 |
stdout_write("Keywords for directory names:\n" |
| 938 |
"-----------------------------\n") |
| 939 |
self.print_kwdict(kwdict) |
| 940 |
|
| 941 |
def handle_queue(self, url, kwdict): |
| 942 |
extr = None |
| 943 |
if "_extractor" in kwdict: |
| 944 |
extr = kwdict["_extractor"].from_url(url) |
| 945 |
|
| 946 |
if not util.filter_dict(kwdict): |
| 947 |
self.extractor.log.info( |
| 948 |
"This extractor only spawns other extractors " |
| 949 |
"and does not provide any metadata on its own.") |
| 950 |
|
| 951 |
if extr: |
| 952 |
self.extractor.log.info( |
| 953 |
"Showing results for '%s' instead:\n", url) |
| 954 |
KeywordJob(extr, self).run() |
| 955 |
else: |
| 956 |
self.extractor.log.info( |
| 957 |
"Try 'gallery-dl -K \"%s\"' instead.", url) |
| 958 |
else: |
| 959 |
stdout_write("Keywords for --child-filter:\n" |
| 960 |
"----------------------------\n") |
| 961 |
self.print_kwdict(kwdict) |
| 962 |
if extr or self.extractor.categorytransfer: |
| 963 |
stdout_write("\n") |
| 964 |
KeywordJob(extr or url, self).run() |
| 965 |
raise exception.StopExtraction() |
| 966 |
|
| 967 |
def print_kwdict(self, kwdict, prefix="", markers=None): |
| 968 |
"""Print key-value pairs in 'kwdict' with formatting""" |
| 969 |
write = sys.stdout.write |
| 970 |
suffix = "']" if prefix else "" |
| 971 |
|
| 972 |
markerid = id(kwdict) |
| 973 |
if markers is None: |
| 974 |
markers = {markerid} |
| 975 |
elif markerid in markers: |
| 976 |
write(f"{prefix[:-2]}\n <circular reference>\n") |
| 977 |
return |
| 978 |
else: |
| 979 |
markers.add(markerid) |
| 980 |
|
| 981 |
for key, value in sorted(kwdict.items()): |
| 982 |
if key[0] == "_" and not self.private: |
| 983 |
continue |
| 984 |
key = prefix + key + suffix |
| 985 |
|
| 986 |
if isinstance(value, dict): |
| 987 |
self.print_kwdict(value, key + "['", markers) |
| 988 |
|
| 989 |
elif isinstance(value, list): |
| 990 |
if not value: |
| 991 |
pass |
| 992 |
elif isinstance(value[0], dict): |
| 993 |
self.print_kwdict(value[0], key + "[N]['", markers) |
| 994 |
else: |
| 995 |
fmt = (" {:>%s} {}\n" % len(str(len(value)))).format |
| 996 |
write(key + "[N]\n") |
| 997 |
for idx, val in enumerate(value, 0): |
| 998 |
write(fmt(idx, val)) |
| 999 |
|
| 1000 |
else: |
| 1001 |
|
| 1002 |
write(f"{key}\n {value}\n") |
| 1003 |
|
| 1004 |
markers.remove(markerid) |
| 1005 |
|
| 1006 |
|
| 1007 |
class UrlJob(Job): |
| 1008 |
"""Print download urls""" |
| 1009 |
maxdepth = 1 |
| 1010 |
|
| 1011 |
def __init__(self, url, parent=None, depth=1): |
| 1012 |
Job.__init__(self, url, parent) |
| 1013 |
self.depth = depth |
| 1014 |
if depth >= self.maxdepth: |
| 1015 |
self.handle_queue = self.handle_url |
| 1016 |
|
| 1017 |
def handle_url(self, url, _): |
| 1018 |
stdout_write(url + "\n") |
| 1019 |
|
| 1020 |
def handle_url_fallback(self, url, kwdict): |
| 1021 |
stdout_write(url + "\n") |
| 1022 |
if "_fallback" in kwdict: |
| 1023 |
for url in kwdict["_fallback"]: |
| 1024 |
stdout_write(f"| {url}\n") |
| 1025 |
|
| 1026 |
def handle_queue(self, url, kwdict): |
| 1027 |
if cls := kwdict.get("_extractor"): |
| 1028 |
extr = cls.from_url(url) |
| 1029 |
else: |
| 1030 |
extr = extractor.find(url) |
| 1031 |
|
| 1032 |
if extr: |
| 1033 |
self.status |= self.__class__(extr, self, self.depth + 1).run() |
| 1034 |
else: |
| 1035 |
self._write_unsupported(url) |
| 1036 |
|
| 1037 |
|
| 1038 |
class InfoJob(Job): |
| 1039 |
"""Print extractor defaults and settings""" |
| 1040 |
|
| 1041 |
def run(self): |
| 1042 |
ex = self.extractor |
| 1043 |
pm = self._print_multi |
| 1044 |
pc = self._print_config |
| 1045 |
|
| 1046 |
if ex.basecategory: |
| 1047 |
pm("Category / Subcategory / Basecategory", |
| 1048 |
ex.category, ex.subcategory, ex.basecategory) |
| 1049 |
else: |
| 1050 |
pm("Category / Subcategory", ex.category, ex.subcategory) |
| 1051 |
|
| 1052 |
pc("Filename format", "filename", ex.filename_fmt) |
| 1053 |
pc("Directory format", "directory", ex.directory_fmt) |
| 1054 |
pc("Archive format", "archive-format", ex.archive_fmt) |
| 1055 |
pc("Request interval", "sleep-request", ex.request_interval) |
| 1056 |
|
| 1057 |
return 0 |
| 1058 |
|
| 1059 |
def _print_multi(self, title, *values): |
| 1060 |
stdout_write( |
| 1061 |
f"{title}\n {' / '.join(map(util.json_dumps, values))}\n\n") |
| 1062 |
|
| 1063 |
def _print_config(self, title, optname, value): |
| 1064 |
optval = self.extractor.config(optname, util.SENTINEL) |
| 1065 |
if optval is not util.SENTINEL: |
| 1066 |
stdout_write( |
| 1067 |
f"{title} (custom):\n {util.json_dumps(optval)}\n" |
| 1068 |
f"{title} (default):\n {util.json_dumps(value)}\n\n") |
| 1069 |
elif value: |
| 1070 |
stdout_write( |
| 1071 |
f"{title} (default):\n {util.json_dumps(value)}\n\n") |
| 1072 |
|
| 1073 |
|
| 1074 |
class DataJob(Job): |
| 1075 |
"""Collect extractor results and dump them""" |
| 1076 |
resolve = False |
| 1077 |
|
| 1078 |
def __init__(self, url, parent=None, file=sys.stdout, ensure_ascii=True, |
| 1079 |
resolve=False): |
| 1080 |
Job.__init__(self, url, parent) |
| 1081 |
self.file = file |
| 1082 |
self.data = [] |
| 1083 |
self.data_urls = [] |
| 1084 |
self.data_post = [] |
| 1085 |
self.data_meta = [] |
| 1086 |
self.exception = None |
| 1087 |
self.ascii = config.get(("output",), "ascii", ensure_ascii) |
| 1088 |
self.jsonl = config.get(("output",), "jsonl", False) |
| 1089 |
self.resolve = 128 if resolve is True else (resolve or self.resolve) |
| 1090 |
|
| 1091 |
private = config.get(("output",), "private") |
| 1092 |
self.filter = dict.copy if private else util.filter_dict |
| 1093 |
|
| 1094 |
if self.resolve > 0: |
| 1095 |
self.handle_queue = self.handle_queue_resolve |
| 1096 |
if not self.jsonl: |
| 1097 |
self.out = util.noop |
| 1098 |
|
| 1099 |
def run(self): |
| 1100 |
self._init() |
| 1101 |
|
| 1102 |
extractor = self.extractor |
| 1103 |
sleep = util.build_duration_func( |
| 1104 |
extractor.config("sleep-extractor")) |
| 1105 |
if sleep is not None: |
| 1106 |
extractor.sleep(sleep(), "extractor") |
| 1107 |
|
| 1108 |
|
| 1109 |
try: |
| 1110 |
self.dispatch(extractor) |
| 1111 |
except exception.StopExtraction: |
| 1112 |
pass |
| 1113 |
except Exception as exc: |
| 1114 |
self.exception = exc |
| 1115 |
self.data.append((-1, { |
| 1116 |
"error" : exc.__class__.__name__, |
| 1117 |
"message": str(exc), |
| 1118 |
})) |
| 1119 |
except BaseException: |
| 1120 |
pass |
| 1121 |
|
| 1122 |
|
| 1123 |
if config.get(("output",), "num-to-str", False): |
| 1124 |
for msg in self.data: |
| 1125 |
util.transform_dict(msg[-1], util.number_to_string) |
| 1126 |
|
| 1127 |
if self.file and not self.jsonl: |
| 1128 |
|
| 1129 |
try: |
| 1130 |
util.dump_json(self.data, self.file, self.ascii, 2) |
| 1131 |
self.file.flush() |
| 1132 |
except Exception: |
| 1133 |
pass |
| 1134 |
|
| 1135 |
return 0 |
| 1136 |
|
| 1137 |
def out(self, msg): |
| 1138 |
self.file.write(util.json_dumps(msg)) |
| 1139 |
self.file.write("\n") |
| 1140 |
self.file.flush() |
| 1141 |
|
| 1142 |
def handle_url(self, url, kwdict): |
| 1143 |
kwdict = self.filter(kwdict) |
| 1144 |
self.out(msg := (Message.Url, url, kwdict)) |
| 1145 |
self.data_urls.append(url) |
| 1146 |
self.data_meta.append(kwdict) |
| 1147 |
self.data.append(msg) |
| 1148 |
|
| 1149 |
def handle_directory(self, kwdict): |
| 1150 |
kwdict = self.filter(kwdict) |
| 1151 |
self.out(msg := (Message.Directory, kwdict)) |
| 1152 |
self.data_post.append(kwdict) |
| 1153 |
self.data.append(msg) |
| 1154 |
|
| 1155 |
def handle_queue(self, url, kwdict): |
| 1156 |
kwdict = self.filter(kwdict) |
| 1157 |
self.out(msg := (Message.Queue, url, kwdict)) |
| 1158 |
self.data_urls.append(url) |
| 1159 |
self.data_meta.append(kwdict) |
| 1160 |
self.data.append(msg) |
| 1161 |
|
| 1162 |
def handle_queue_resolve(self, url, kwdict): |
| 1163 |
if cls := kwdict.get("_extractor"): |
| 1164 |
extr = cls.from_url(url) |
| 1165 |
else: |
| 1166 |
extr = extractor.find(url) |
| 1167 |
|
| 1168 |
if not extr: |
| 1169 |
kwdict = self.filter(kwdict) |
| 1170 |
self.out(msg := (Message.Queue, url, kwdict)) |
| 1171 |
self.data_urls.append(url) |
| 1172 |
self.data_meta.append(kwdict) |
| 1173 |
return self.data.append(msg) |
| 1174 |
|
| 1175 |
job = self.__class__(extr, self, None, self.ascii, self.resolve-1) |
| 1176 |
job.data = self.data |
| 1177 |
job.data_urls = self.data_urls |
| 1178 |
job.data_post = self.data_post |
| 1179 |
job.data_meta = self.data_meta |
| 1180 |
job.run() |