| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
n |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
"""Extractors for Wikimedia sites""" |
| 11 |
|
| 12 |
from .common import BaseExtractor, Message |
| 13 |
from .. import text, util |
| 14 |
|
| 15 |
|
| 16 |
class WikimediaExtractor(BaseExtractor): |
| 17 |
"""Base class for wikimedia extractors""" |
| 18 |
basecategory = "wikimedia" |
| 19 |
filename_fmt = "{filename} ({sha1[:8]}).{extension}" |
| 20 |
archive_fmt = "{sha1}" |
| 21 |
useragent = util.USERAGENT_GALLERYDL |
| 22 |
request_interval = (1.0, 2.0) |
| 23 |
|
| 24 |
def __init__(self, match): |
| 25 |
self._init_category(match) |
| 26 |
|
| 27 |
self.format = False |
| 28 |
if self.category == "wikimedia": |
| 29 |
labels = self.root.split(".") |
| 30 |
self.lang = labels[-3][-2:] |
| 31 |
self.category = labels[-2] |
| 32 |
elif self.category in {"fandom", "wikigg"}: |
| 33 |
self.lang = "en" |
| 34 |
self.format = "original" |
| 35 |
self.basesubcategory = self.category |
| 36 |
self.category = ( |
| 37 |
f"{self.category}-" |
| 38 |
f"{self.root.partition('.')[0].rpartition('/')[2]}") |
| 39 |
else: |
| 40 |
self.lang = "" |
| 41 |
|
| 42 |
if useragent := self.config_instance("useragent"): |
| 43 |
self.useragent = useragent |
| 44 |
|
| 45 |
BaseExtractor.__init__(self, match) |
| 46 |
|
| 47 |
def _init(self): |
| 48 |
if api_path := self.config_instance("api-path"): |
| 49 |
if api_path[0] == "/": |
| 50 |
self.api_url = self.root + api_path |
| 51 |
else: |
| 52 |
self.api_url = api_path |
| 53 |
else: |
| 54 |
self.api_url = None |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
self.image_revisions = self.config("image-revisions", 1) |
| 61 |
self.format = self.config("format", self.format) |
| 62 |
self.per_page = self.config("limit", 50) |
| 63 |
self.subcategories = False |
| 64 |
|
| 65 |
def _search_api_path(self, root): |
| 66 |
self.log.debug("Probing possible API endpoints") |
| 67 |
for path in ("/api.php", "/w/api.php", "/wiki/api.php"): |
| 68 |
url = root + path |
| 69 |
response = self.request(url, method="HEAD", fatal=None) |
| 70 |
if response.status_code < 400: |
| 71 |
return url |
| 72 |
raise self.exc.AbortExtraction("Unable to find API endpoint") |
| 73 |
|
| 74 |
def prepare_info(self, info): |
| 75 |
"""Adjust the content of an image info object""" |
| 76 |
|
| 77 |
def prepare_image(self, image): |
| 78 |
"""Adjust the content of an image object""" |
| 79 |
image["metadata"] = { |
| 80 |
m["name"]: m["value"] |
| 81 |
for m in image["metadata"] or ()} |
| 82 |
image["commonmetadata"] = { |
| 83 |
m["name"]: m["value"] |
| 84 |
for m in image["commonmetadata"] or ()} |
| 85 |
|
| 86 |
text.nameext_from_name( |
| 87 |
image["canonicaltitle"].partition(":")[2], image) |
| 88 |
image["date"] = self.parse_datetime_iso(image["timestamp"]) |
| 89 |
|
| 90 |
if self.format: |
| 91 |
url = image["url"] |
| 92 |
image["url"] = (f"{url}{'&' if '?' in url else '?'}" |
| 93 |
f"format={self.format}") |
| 94 |
|
| 95 |
def items(self): |
| 96 |
params = self.params() |
| 97 |
|
| 98 |
for info in self._pagination(params): |
| 99 |
try: |
| 100 |
images = info.pop("imageinfo") |
| 101 |
except KeyError: |
| 102 |
self.log.debug("Missing 'imageinfo' for %s", info) |
| 103 |
images = () |
| 104 |
|
| 105 |
info["count"] = len(images) |
| 106 |
self.prepare_info(info) |
| 107 |
yield Message.Directory, "", info |
| 108 |
|
| 109 |
num = 0 |
| 110 |
for image in images: |
| 111 |
|
| 112 |
if "filemissing" in image: |
| 113 |
self.log.warning( |
| 114 |
"File %s (or its revision) is missing", |
| 115 |
image["canonicaltitle"].partition(":")[2]) |
| 116 |
continue |
| 117 |
num += 1 |
| 118 |
image["num"] = num |
| 119 |
self.prepare_image(image) |
| 120 |
image.update(info) |
| 121 |
yield Message.Url, image["url"], image |
| 122 |
|
| 123 |
if self.subcategories: |
| 124 |
base = self.root + "/wiki/" |
| 125 |
params["gcmtype"] = "subcat" |
| 126 |
for subcat in self._pagination(params): |
| 127 |
url = base + subcat["title"].replace(" ", "_") |
| 128 |
subcat["_extractor"] = WikimediaArticleExtractor |
| 129 |
yield Message.Queue, url, subcat |
| 130 |
|
| 131 |
def _pagination(self, params): |
| 132 |
""" |
| 133 |
https://www.mediawiki.org/wiki/API:Query |
| 134 |
https://opendata.stackexchange.com/questions/13381 |
| 135 |
""" |
| 136 |
|
| 137 |
url = self.api_url or \ |
| 138 |
self.cache(self._search_api_path, self.root, _mem=False) |
| 139 |
|
| 140 |
params["action"] = "query" |
| 141 |
params["format"] = "json" |
| 142 |
params["prop"] = "imageinfo" |
| 143 |
params["iiprop"] = ( |
| 144 |
"timestamp|user|userid|comment|canonicaltitle|url|size|" |
| 145 |
"sha1|mime|metadata|commonmetadata|extmetadata|bitdepth" |
| 146 |
) |
| 147 |
params["iilimit"] = self.image_revisions |
| 148 |
|
| 149 |
while True: |
| 150 |
data = self.request_json(url, params=params) |
| 151 |
|
| 152 |
|
| 153 |
if error := data.get("error"): |
| 154 |
self.log.error("%s: %s", error["code"], error["info"]) |
| 155 |
return |
| 156 |
|
| 157 |
|
| 158 |
if warnings := data.get("warnings"): |
| 159 |
self.log.debug("MediaWiki returned warnings: %s", warnings) |
| 160 |
|
| 161 |
try: |
| 162 |
pages = data["query"]["pages"] |
| 163 |
except KeyError: |
| 164 |
pass |
| 165 |
else: |
| 166 |
yield from pages.values() |
| 167 |
|
| 168 |
try: |
| 169 |
continuation = data["continue"] |
| 170 |
except KeyError: |
| 171 |
break |
| 172 |
params.update(continuation) |
| 173 |
|
| 174 |
|
| 175 |
BASE_PATTERN = WikimediaExtractor.update({ |
| 176 |
"wikimedia": { |
| 177 |
"root": None, |
| 178 |
"pattern": r"[a-z]{2,}\." |
| 179 |
r"wik(?:i(?:pedia|quote|books|source|news|versity|data" |
| 180 |
r"|voyage)|tionary)" |
| 181 |
r"\.org", |
| 182 |
"api-path": "/w/api.php", |
| 183 |
}, |
| 184 |
"wikispecies": { |
| 185 |
"root": "https://species.wikimedia.org", |
| 186 |
"pattern": r"species\.wikimedia\.org", |
| 187 |
"api-path": "/w/api.php", |
| 188 |
}, |
| 189 |
"wikimediacommons": { |
| 190 |
"root": "https://commons.wikimedia.org", |
| 191 |
"pattern": r"commons\.wikimedia\.org", |
| 192 |
"api-path": "/w/api.php", |
| 193 |
}, |
| 194 |
"mediawiki": { |
| 195 |
"root": "https://www.mediawiki.org", |
| 196 |
"pattern": r"(?:www\.)?mediawiki\.org", |
| 197 |
"api-path": "/w/api.php", |
| 198 |
}, |
| 199 |
"fandom": { |
| 200 |
"root": None, |
| 201 |
"pattern": r"[\w-]+\.fandom\.com", |
| 202 |
"api-path": "/api.php", |
| 203 |
}, |
| 204 |
"wikigg": { |
| 205 |
"root": None, |
| 206 |
"pattern": r"\w+\.wiki\.gg", |
| 207 |
"api-path": "/api.php", |
| 208 |
}, |
| 209 |
"mariowiki": { |
| 210 |
"root": "https://www.mariowiki.com", |
| 211 |
"pattern": r"(?:www\.)?mariowiki\.com", |
| 212 |
"api-path": "/api.php", |
| 213 |
}, |
| 214 |
"bulbapedia": { |
| 215 |
"root": "https://bulbapedia.bulbagarden.net", |
| 216 |
"pattern": r"(?:bulbapedia|archives)\.bulbagarden\.net", |
| 217 |
"api-path": "/w/api.php", |
| 218 |
}, |
| 219 |
"pidgiwiki": { |
| 220 |
"root": "https://www.pidgi.net", |
| 221 |
"pattern": r"(?:www\.)?pidgi\.net", |
| 222 |
"api-path": "/wiki/api.php", |
| 223 |
}, |
| 224 |
"azurlanewiki": { |
| 225 |
"root": "https://azurlane.koumakan.jp", |
| 226 |
"pattern": r"azurlane\.koumakan\.jp", |
| 227 |
"api-path": "/w/api.php", |
| 228 |
"useragent": "Googlebot-Image/1.0", |
| 229 |
}, |
| 230 |
"mgewiki": { |
| 231 |
"root": "https://mgewiki.moe", |
| 232 |
"pattern": r"(?:www\.)?mgewiki\.moe", |
| 233 |
"api-path": "/api.php", |
| 234 |
}, |
| 235 |
}) |
| 236 |
|
| 237 |
|
| 238 |
class WikimediaArticleExtractor(WikimediaExtractor): |
| 239 |
"""Extractor for wikimedia articles""" |
| 240 |
subcategory = "article" |
| 241 |
directory_fmt = ("{category}", "{page}") |
| 242 |
pattern = BASE_PATTERN + r"/(?!static/)([^?#]+)" |
| 243 |
example = "https://en.wikipedia.org/wiki/TITLE" |
| 244 |
|
| 245 |
def __init__(self, match): |
| 246 |
WikimediaExtractor.__init__(self, match) |
| 247 |
|
| 248 |
path = self.groups[-1] |
| 249 |
if path[2] == "/": |
| 250 |
self.lang = lang = path[:2] |
| 251 |
self.root = f"{self.root}/{lang}" |
| 252 |
path = path[3:] |
| 253 |
if path.startswith("wiki/"): |
| 254 |
path = path[5:] |
| 255 |
elif path.startswith("index.php/"): |
| 256 |
path = path[10:] |
| 257 |
self.path = text.unquote(path) |
| 258 |
|
| 259 |
pre, sep, _ = path.partition(":") |
| 260 |
self.prefix = prefix = pre.lower() if sep else None |
| 261 |
if prefix is not None: |
| 262 |
self.subcategory = prefix |
| 263 |
|
| 264 |
def params(self): |
| 265 |
if self.prefix == "category": |
| 266 |
if self.config("subcategories", True): |
| 267 |
self.subcategories = True |
| 268 |
return { |
| 269 |
"generator": "categorymembers", |
| 270 |
"gcmtitle" : self.path, |
| 271 |
"gcmtype" : "file", |
| 272 |
"gcmlimit" : self.per_page, |
| 273 |
} |
| 274 |
|
| 275 |
if self.prefix == "file": |
| 276 |
return { |
| 277 |
"titles": self.path, |
| 278 |
} |
| 279 |
|
| 280 |
return { |
| 281 |
"generator": "images", |
| 282 |
"gimlimit" : self.per_page, |
| 283 |
"titles" : self.path, |
| 284 |
} |
| 285 |
|
| 286 |
def prepare_info(self, info): |
| 287 |
info["page"] = self.path |
| 288 |
info["lang"] = self.lang |
| 289 |
|
| 290 |
|
| 291 |
class WikimediaWikiExtractor(WikimediaExtractor): |
| 292 |
"""Extractor for all files on a MediaWiki instance""" |
| 293 |
subcategory = "wiki" |
| 294 |
pattern = BASE_PATTERN + r"/?$" |
| 295 |
example = "https://en.wikipedia.org/" |
| 296 |
|
| 297 |
def params(self): |
| 298 |
|
| 299 |
return { |
| 300 |
"generator" : "allpages", |
| 301 |
"gapnamespace": 6, |
| 302 |
"gaplimit" : self.per_page, |
| 303 |
} |