Debian Codegraph @

gallery_dl/extractor/directlink.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017-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 """Direct link handling"""
10
11 from .common import Extractor, Message
12 from .. import text
13
14
15 class DirectlinkExtractor(Extractor):
16 """Extractor for direct links to images and other media files"""
17 category = "directlink"
18 filename_fmt = "{domain}/{path}/{filename}.{extension}"
19 archive_fmt = filename_fmt
20 pattern = (r"(?i)https?://(?P<domain>[^/?#]+)/(?P<path>[^?#]+\."
21 r"(?:jpe?g|jpe|png|gif|bmp|svg|web[mp]|avif|heic|psd"
22 r"|mp4|m4v|mov|mkv|og[gmv]|wav|mp3|opus|zip|rar|7z|pdf|swf))"
23 r"(?:\?(?P<query>[^#]*))?(?:#(?P<fragment>.*))?$")
24 example = "https://en.wikipedia.org/static/images/project-logos/enwiki.png"
25
26 def __init__(self, match):
27 self.data = data = match.groupdict()
28 self.subcategory = ".".join(data["domain"].rsplit(".", 2)[-2:])
29 Extractor.__init__(self, match)
30
31 def items(self):
32 url = self.url
33
34 if trfm := self.config("transform"):
35 if isinstance(trfm, dict):
36 trfm = trfm.items()
37 for pattern, sub in trfm:
38 url = text.re(pattern).sub(sub, url)
39 if url != self.url and (match := self.pattern.match(url)):
40 self.data = match.groupdict()
41
42 data = self.data
43 for key, value in data.items():
44 if value:
45 data[key] = text.unquote(value)
46
47 data["path"], _, name = data["path"].rpartition("/")
48 data["filename"], _, ext = name.rpartition(".")
49 data["extension"] = ext.lower()
50 data["_http_headers"] = {"Referer": url.encode("latin-1", "ignore")}
51
52 yield Message.Directory, "", data
53 yield Message.Url, url, data