| 1 |
|
| 2 |
|
| 3 |
n |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
"""Extractors for https://mangadex.org/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text, util |
| 13 |
from collections import defaultdict |
| 14 |
|
| 15 |
BASE_PATTERN = r"(?:https?://)?(?:www\.)?mangadex\.(?:org|cc)" |
| 16 |
|
| 17 |
|
| 18 |
class MangadexExtractor(Extractor): |
| 19 |
"""Base class for mangadex extractors""" |
| 20 |
category = "mangadex" |
| 21 |
directory_fmt = ( |
| 22 |
"{category}", "{manga}", |
| 23 |
"{volume:?v/ />02}c{chapter:>03}{chapter_minor}{title:?: //}") |
| 24 |
filename_fmt = ( |
| 25 |
"{manga}_c{chapter:>03}{chapter_minor}_{page:>03}.{extension}") |
| 26 |
archive_fmt = "{chapter_id}_{page}" |
| 27 |
root = "https://mangadex.org" |
| 28 |
useragent = util.USERAGENT_GALLERYDL |
| 29 |
_cache = {} |
| 30 |
|
| 31 |
def _init(self): |
| 32 |
self.uuid = self.groups[0] |
| 33 |
self.api = MangadexAPI(self) |
| 34 |
|
| 35 |
def _items_chapters(self): |
| 36 |
for chapter in self.chapters(): |
| 37 |
uuid = chapter["id"] |
| 38 |
data = self._transform(chapter) |
| 39 |
data["_extractor"] = MangadexChapterExtractor |
| 40 |
self._cache[uuid] = data |
| 41 |
yield Message.Queue, f"{self.root}/chapter/{uuid}", data |
| 42 |
|
| 43 |
def _items_manga(self): |
| 44 |
data = {"_extractor": MangadexMangaExtractor} |
| 45 |
for manga in self.manga(): |
| 46 |
url = f"{self.root}/title/{manga['id']}" |
| 47 |
yield Message.Queue, url, data |
| 48 |
|
| 49 |
items = _items_chapters |
| 50 |
|
| 51 |
def _transform(self, chapter): |
| 52 |
relationships = defaultdict(list) |
| 53 |
for item in chapter["relationships"]: |
| 54 |
relationships[item["type"]].append(item) |
| 55 |
|
| 56 |
cattributes = chapter["attributes"] |
| 57 |
if lang := cattributes.get("translatedLanguage"): |
| 58 |
lang = lang.partition("-")[0] |
| 59 |
|
| 60 |
if cattributes["chapter"]: |
| 61 |
chnum, sep, minor = cattributes["chapter"].partition(".") |
| 62 |
else: |
| 63 |
chnum, sep, minor = 0, "", "" |
| 64 |
|
| 65 |
return { |
| 66 |
**self.cache(self._manga_info, relationships["manga"][0]["id"]), |
| 67 |
"title" : cattributes["title"], |
| 68 |
"volume" : text.parse_int(cattributes["volume"]), |
| 69 |
"chapter" : text.parse_int(chnum), |
| 70 |
"chapter_minor": sep + minor, |
| 71 |
"chapter_id": chapter["id"], |
| 72 |
"date" : self.parse_datetime_iso(cattributes["publishAt"]), |
| 73 |
"group" : [group["attributes"]["name"] |
| 74 |
for group in relationships["scanlation_group"] |
| 75 |
if group and "attributes" in group], |
| 76 |
"user" : [user["attributes"]["username"] |
| 77 |
for user in relationships["user"] |
| 78 |
if user and "attributes" in user], |
| 79 |
"lang" : lang, |
| 80 |
"count" : cattributes["pages"], |
| 81 |
"_external_url": cattributes.get("externalUrl"), |
| 82 |
} |
| 83 |
|
| 84 |
def _manga_info(self, uuid): |
| 85 |
manga = self.cache(self.api.manga, uuid) |
| 86 |
|
| 87 |
rel = defaultdict(list) |
| 88 |
for item in manga["relationships"]: |
| 89 |
rel[item["type"]].append(item) |
| 90 |
mattr = manga["attributes"] |
| 91 |
|
| 92 |
return { |
| 93 |
"manga" : (mattr["title"].get("en") or |
| 94 |
next(iter(mattr["title"].values()), "")), |
| 95 |
"manga_id": manga["id"], |
| 96 |
"manga_titles": [t.popitem()[1] |
| 97 |
for t in mattr.get("altTitles") or ()], |
| 98 |
"manga_date" : self.parse_datetime_iso(mattr.get("createdAt")), |
| 99 |
"description" : (mattr["description"].get("en") or |
| 100 |
next(iter(mattr["description"].values()), "")), |
| 101 |
"demographic": mattr.get("publicationDemographic"), |
| 102 |
"origin": mattr.get("originalLanguage"), |
| 103 |
"status": mattr.get("status"), |
| 104 |
"year" : mattr.get("year"), |
| 105 |
"rating": mattr.get("contentRating"), |
| 106 |
"links" : mattr.get("links"), |
| 107 |
"tags" : [t["attributes"]["name"]["en"] for t in mattr["tags"]], |
| 108 |
"artist": [a["attributes"]["name"] for a in rel["artist"]], |
| 109 |
"author": [a["attributes"]["name"] for a in rel["author"]], |
| 110 |
} |
| 111 |
|
| 112 |
|
| 113 |
class MangadexCoversExtractor(MangadexExtractor): |
| 114 |
"""Extractor for mangadex manga covers""" |
| 115 |
subcategory = "covers" |
| 116 |
directory_fmt = ("{category}", "{manga}", "Covers") |
| 117 |
filename_fmt = "{volume:>02}_{lang}.{extension}" |
| 118 |
archive_fmt = "c_{cover_id}" |
| 119 |
pattern = (BASE_PATTERN + r"/(?:title|manga)/(?!follows|feed$)([0-9a-f-]+)" |
| 120 |
r"(?:/[^/?#]+)?\?tab=art") |
| 121 |
example = ("https://mangadex.org/title" |
| 122 |
"/01234567-89ab-cdef-0123-456789abcdef?tab=art") |
| 123 |
|
| 124 |
def items(self): |
| 125 |
base = f"{self.root}/covers/{self.uuid}/" |
| 126 |
for cover in self.api.covers_manga(self.uuid): |
| 127 |
data = self._transform_cover(cover) |
| 128 |
name = data["cover"] |
| 129 |
text.nameext_from_url(name, data) |
| 130 |
data["cover_id"] = data["filename"] |
| 131 |
yield Message.Directory, "", data |
| 132 |
yield Message.Url, base + name, data |
| 133 |
|
| 134 |
def _transform_cover(self, cover): |
| 135 |
relationships = defaultdict(list) |
| 136 |
for item in cover["relationships"]: |
| 137 |
relationships[item["type"]].append(item) |
| 138 |
cattributes = cover["attributes"] |
| 139 |
|
| 140 |
return { |
| 141 |
**self.cache(self._manga_info, relationships["manga"][0]["id"]), |
| 142 |
"cover" : cattributes["fileName"], |
| 143 |
"lang" : cattributes.get("locale"), |
| 144 |
"volume" : text.parse_int(cattributes["volume"]), |
| 145 |
"date" : self.parse_datetime_iso(cattributes["createdAt"]), |
| 146 |
"date_updated": self.parse_datetime_iso(cattributes["updatedAt"]), |
| 147 |
} |
| 148 |
|
| 149 |
|
| 150 |
class MangadexChapterExtractor(MangadexExtractor): |
| 151 |
"""Extractor for manga-chapters from mangadex.org""" |
| 152 |
subcategory = "chapter" |
| 153 |
pattern = BASE_PATTERN + r"/chapter/([0-9a-f-]+)" |
| 154 |
example = ("https://mangadex.org/chapter" |
| 155 |
"/01234567-89ab-cdef-0123-456789abcdef") |
| 156 |
|
| 157 |
def items(self): |
| 158 |
try: |
| 159 |
data = self._cache.pop(self.uuid) |
| 160 |
except KeyError: |
| 161 |
chapter = self.api.chapter(self.uuid) |
| 162 |
data = self._transform(chapter) |
| 163 |
|
| 164 |
if data.get("_external_url") and not data["count"]: |
| 165 |
raise self.exc.AbortExtraction( |
| 166 |
f"Chapter {data['chapter']}{data['chapter_minor']} is not " |
| 167 |
f"available on MangaDex and can instead be read on the " |
| 168 |
f"official publisher's website at {data['_external_url']}.") |
| 169 |
|
| 170 |
yield Message.Directory, "", data |
| 171 |
|
| 172 |
if self.config("data-saver", False): |
| 173 |
path = "data-saver" |
| 174 |
key = "dataSaver" |
| 175 |
else: |
| 176 |
path = key = "data" |
| 177 |
|
| 178 |
server = self.api.athome_server(self.uuid) |
| 179 |
chapter = server["chapter"] |
| 180 |
base = f"{server['baseUrl']}/{path}/{chapter['hash']}/" |
| 181 |
|
| 182 |
enum = util.enumerate_reversed if self.config( |
| 183 |
"page-reverse") else enumerate |
| 184 |
for data["page"], path in enum(chapter[key], 1): |
| 185 |
text.nameext_from_url(path, data) |
| 186 |
yield Message.Url, base + path, data |
| 187 |
|
| 188 |
|
| 189 |
class MangadexMangaExtractor(MangadexExtractor): |
| 190 |
"""Extractor for manga from mangadex.org""" |
| 191 |
subcategory = "manga" |
| 192 |
pattern = BASE_PATTERN + r"/(?:title|manga)/(?!follows|feed$)([0-9a-f-]+)" |
| 193 |
example = ("https://mangadex.org/title" |
| 194 |
"/01234567-89ab-cdef-0123-456789abcdef") |
| 195 |
|
| 196 |
def items(self): |
| 197 |
items = self._items_chapters() |
| 198 |
if self.config("covers", False): |
| 199 |
import itertools |
| 200 |
url = f"{self.root}/title/{self.uuid}?tab=art" |
| 201 |
data = {"_extractor": MangadexCoversExtractor} |
| 202 |
items = itertools.chain(((Message.Queue, url, data),), items) |
| 203 |
return items |
| 204 |
|
| 205 |
def chapters(self): |
| 206 |
return self.api.manga_feed(self.uuid) |
| 207 |
|
| 208 |
|
| 209 |
class MangadexFeedExtractor(MangadexExtractor): |
| 210 |
"""Extractor for chapters from your Updates Feed""" |
| 211 |
subcategory = "feed" |
| 212 |
pattern = BASE_PATTERN + r"/titles?/feed$()" |
| 213 |
example = "https://mangadex.org/title/feed" |
| 214 |
|
| 215 |
def chapters(self): |
| 216 |
return self.api.user_follows_manga_feed() |
| 217 |
|
| 218 |
|
| 219 |
class MangadexFollowingExtractor(MangadexExtractor): |
| 220 |
"""Extractor for followed manga from your Library""" |
| 221 |
subcategory = "following" |
| 222 |
pattern = BASE_PATTERN + r"/titles?/follows(?:\?([^#]+))?$" |
| 223 |
example = "https://mangadex.org/title/follows" |
| 224 |
|
| 225 |
items = MangadexExtractor._items_manga |
| 226 |
|
| 227 |
def manga(self): |
| 228 |
return self.api.user_follows_manga() |
| 229 |
|
| 230 |
|
| 231 |
class MangadexListExtractor(MangadexExtractor): |
| 232 |
"""Extractor for mangadex MDLists""" |
| 233 |
subcategory = "list" |
| 234 |
pattern = (BASE_PATTERN + |
| 235 |
r"/list/([0-9a-f-]+)(?:/[^/?#]*)?(?:\?tab=(\w+))?") |
| 236 |
example = ("https://mangadex.org/list" |
| 237 |
"/01234567-89ab-cdef-0123-456789abcdef/NAME") |
| 238 |
|
| 239 |
def __init__(self, match): |
| 240 |
if match[2] == "feed": |
| 241 |
self.subcategory = "list-feed" |
| 242 |
else: |
| 243 |
self.items = self._items_manga |
| 244 |
MangadexExtractor.__init__(self, match) |
| 245 |
|
| 246 |
def chapters(self): |
| 247 |
return self.api.list_feed(self.uuid) |
| 248 |
|
| 249 |
def manga(self): |
| 250 |
return [ |
| 251 |
item |
| 252 |
for item in self.api.list(self.uuid)["relationships"] |
| 253 |
if item["type"] == "manga" |
| 254 |
] |
| 255 |
|
| 256 |
|
| 257 |
class MangadexAuthorExtractor(MangadexExtractor): |
| 258 |
"""Extractor for mangadex authors""" |
| 259 |
subcategory = "author" |
| 260 |
pattern = BASE_PATTERN + r"/author/([0-9a-f-]+)" |
| 261 |
example = ("https://mangadex.org/author" |
| 262 |
"/01234567-89ab-cdef-0123-456789abcdef/NAME") |
| 263 |
|
| 264 |
def items(self): |
| 265 |
for manga in self.api.manga_author(self.uuid): |
| 266 |
manga["_extractor"] = MangadexMangaExtractor |
| 267 |
url = f"{self.root}/title/{manga['id']}" |
| 268 |
yield Message.Queue, url, manga |
| 269 |
|
| 270 |
|
| 271 |
class MangadexAPI(): |
| 272 |
"""Interface for the MangaDex API v5 |
| 273 |
|
| 274 |
https://api.mangadex.org/docs/ |
| 275 |
""" |
| 276 |
|
| 277 |
def __init__(self, extr): |
| 278 |
self.extractor = extr |
| 279 |
self.headers = None |
| 280 |
self.headers_auth = {} |
| 281 |
|
| 282 |
self.username, self.password = extr._get_auth_info() |
| 283 |
if self.username: |
| 284 |
self.client_id = cid = extr.config("client-id") |
| 285 |
self.client_secret = extr.config("client-secret") |
| 286 |
if cid: |
| 287 |
self._authenticate_impl = self._authenticate_impl_client |
| 288 |
else: |
| 289 |
self._authenticate_impl = self._authenticate_impl_legacy |
| 290 |
else: |
| 291 |
self.authenticate = util.noop |
| 292 |
|
| 293 |
server = extr.config("api-server") |
| 294 |
self.root = ("https://api.mangadex.org" if server is None |
| 295 |
else text.ensure_http_scheme(server).rstrip("/")) |
| 296 |
|
| 297 |
def athome_server(self, uuid): |
| 298 |
return self._call("/at-home/server/" + uuid) |
| 299 |
|
| 300 |
def author(self, uuid, manga=False): |
| 301 |
params = {"includes[]": ("manga",)} if manga else None |
| 302 |
return self._call("/author/" + uuid, params)["data"] |
| 303 |
|
| 304 |
def chapter(self, uuid): |
| 305 |
params = {"includes[]": ("scanlation_group", "user")} |
| 306 |
return self._call("/chapter/" + uuid, params)["data"] |
| 307 |
|
| 308 |
def covers_manga(self, uuid): |
| 309 |
params = {"manga[]": uuid} |
| 310 |
return self._pagination_covers("/cover", params) |
| 311 |
|
| 312 |
def list(self, uuid): |
| 313 |
return self._call("/list/" + uuid, None, True)["data"] |
| 314 |
|
| 315 |
def list_feed(self, uuid): |
| 316 |
return self._pagination_chapters(f"/list/{uuid}/feed", None, True) |
| 317 |
|
| 318 |
def manga(self, uuid): |
| 319 |
params = {"includes[]": ("artist", "author")} |
| 320 |
return self._call("/manga/" + uuid, params)["data"] |
| 321 |
|
| 322 |
def manga_author(self, uuid_author): |
| 323 |
params = {"authorOrArtist": uuid_author} |
| 324 |
return self._pagination_manga("/manga", params) |
| 325 |
|
| 326 |
def manga_feed(self, uuid): |
| 327 |
order = "desc" if self.extractor.config("chapter-reverse") else "asc" |
| 328 |
params = { |
| 329 |
"order[volume]" : order, |
| 330 |
"order[chapter]": order, |
| 331 |
} |
| 332 |
return self._pagination_chapters(f"/manga/{uuid}/feed", params) |
| 333 |
|
| 334 |
def user_follows_manga(self): |
| 335 |
params = {"contentRating": None} |
| 336 |
return self._pagination_manga( |
| 337 |
"/user/follows/manga", params, True) |
| 338 |
|
| 339 |
def user_follows_manga_feed(self): |
| 340 |
params = {"order[publishAt]": "desc"} |
| 341 |
return self._pagination_chapters( |
| 342 |
"/user/follows/manga/feed", params, True) |
| 343 |
|
| 344 |
def authenticate(self): |
| 345 |
self.headers_auth["Authorization"] = self.extractor.cache( |
| 346 |
self._authenticate_impl, self.username, self.password, |
| 347 |
_exp=900, _mem=False) |
| 348 |
|
| 349 |
def _authenticate_impl_client(self, username, password): |
| 350 |
if refresh_token := self.extractor.cache( |
| 351 |
_refresh_token_cache, (username, "personal"), _mem=False): |
| 352 |
self.extractor.log.info("Refreshing access token") |
| 353 |
data = { |
| 354 |
"grant_type" : "refresh_token", |
| 355 |
"refresh_token": refresh_token, |
| 356 |
"client_id" : self.client_id, |
| 357 |
"client_secret": self.client_secret, |
| 358 |
} |
| 359 |
else: |
| 360 |
self.extractor.log.info("Logging in as %s", username) |
| 361 |
data = { |
| 362 |
"grant_type" : "password", |
| 363 |
"username" : self.username, |
| 364 |
"password" : self.password, |
| 365 |
"client_id" : self.client_id, |
| 366 |
"client_secret": self.client_secret, |
| 367 |
} |
| 368 |
|
| 369 |
self.extractor.log.debug("Using client-id '%s…'", self.client_id[:24]) |
| 370 |
url = ("https://auth.mangadex.org/realms/mangadex" |
| 371 |
"/protocol/openid-connect/token") |
| 372 |
data = self.extractor.request_json( |
| 373 |
url, method="POST", data=data, fatal=None) |
| 374 |
|
| 375 |
try: |
| 376 |
access_token = data["access_token"] |
| 377 |
except Exception: |
| 378 |
raise self.extractor.exc.AuthenticationError( |
| 379 |
data.get("error_description")) |
| 380 |
|
| 381 |
if refresh_token != data.get("refresh_token"): |
| 382 |
self.extractor.cache_update( |
| 383 |
_refresh_token_cache, |
| 384 |
(username, "personal"), data["refresh_token"], _exp=90*86400) |
| 385 |
|
| 386 |
return "Bearer " + access_token |
| 387 |
|
| 388 |
def _authenticate_impl_legacy(self, username, password): |
| 389 |
if refresh_token := self.extractor.cache( |
| 390 |
_refresh_token_cache, username, _mem=False): |
| 391 |
self.extractor.log.info("Refreshing access token") |
| 392 |
url = self.root + "/auth/refresh" |
| 393 |
json = {"token": refresh_token} |
| 394 |
else: |
| 395 |
self.extractor.log.info("Logging in as %s", username) |
| 396 |
url = self.root + "/auth/login" |
| 397 |
json = {"username": username, "password": password} |
| 398 |
|
| 399 |
self.extractor.log.debug("Using legacy login method") |
| 400 |
data = self.extractor.request_json( |
| 401 |
url, method="POST", json=json, fatal=None) |
| 402 |
if data.get("result") != "ok": |
| 403 |
raise self.extractor.exc.AuthenticationError() |
| 404 |
|
| 405 |
if refresh_token != data["token"]["refresh"]: |
| 406 |
self.extractor.cache_update( |
| 407 |
_refresh_token_cache, |
| 408 |
username, data["token"]["refresh"], _exp=90*86400) |
| 409 |
|
| 410 |
return "Bearer " + data["token"]["session"] |
| 411 |
|
| 412 |
def _call(self, endpoint, params=None, auth=False): |
| 413 |
url = self.root + endpoint |
| 414 |
headers = self.headers_auth if auth else self.headers |
| 415 |
|
| 416 |
while True: |
| 417 |
if auth: |
| 418 |
self.authenticate() |
| 419 |
response = self.extractor.request( |
| 420 |
url, params=params, headers=headers, fatal=None) |
| 421 |
|
| 422 |
if response.status_code < 400: |
| 423 |
return response.json() |
| 424 |
if response.status_code == 429: |
| 425 |
until = response.headers.get("X-RateLimit-Retry-After") |
| 426 |
self.extractor.wait(until=until) |
| 427 |
continue |
| 428 |
|
| 429 |
msg = ", ".join(f'{error["title"]}: "{error["detail"]}"' |
| 430 |
for error in response.json()["errors"]) |
| 431 |
raise self.extractor.exc.AbortExtraction( |
| 432 |
f"{response.status_code} {response.reason} ({msg})") |
| 433 |
|
| 434 |
def _pagination_chapters(self, endpoint, params=None, auth=False): |
| 435 |
if params is None: |
| 436 |
params = {} |
| 437 |
|
| 438 |
lang = self.extractor.config("lang") |
| 439 |
if isinstance(lang, str) and "," in lang: |
| 440 |
lang = lang.split(",") |
| 441 |
params["translatedLanguage[]"] = lang |
| 442 |
params["includes[]"] = ("scanlation_group", "user") |
| 443 |
|
| 444 |
return self._pagination(endpoint, params, auth) |
| 445 |
|
| 446 |
def _pagination_manga(self, endpoint, params=None, auth=False): |
| 447 |
if params is None: |
| 448 |
params = {} |
| 449 |
|
| 450 |
return self._pagination(endpoint, params, auth) |
| 451 |
|
| 452 |
def _pagination_covers(self, endpoint, params=None, auth=False): |
| 453 |
if params is None: |
| 454 |
params = {} |
| 455 |
|
| 456 |
lang = self.extractor.config("lang") |
| 457 |
if isinstance(lang, str) and "," in lang: |
| 458 |
lang = lang.split(",") |
| 459 |
params["locales[]"] = lang |
| 460 |
params["contentRating"] = None |
| 461 |
params["order[volume]"] = \ |
| 462 |
"desc" if self.extractor.config("chapter-reverse") else "asc" |
| 463 |
|
| 464 |
return self._pagination(endpoint, params, auth) |
| 465 |
|
| 466 |
def _pagination(self, endpoint, params, auth=False): |
| 467 |
config = self.extractor.config |
| 468 |
|
| 469 |
if "contentRating" not in params: |
| 470 |
ratings = config("ratings") |
| 471 |
if ratings is None: |
| 472 |
ratings = ("safe", "suggestive", "erotica", "pornographic") |
| 473 |
elif isinstance(ratings, str): |
| 474 |
ratings = ratings.split(",") |
| 475 |
params["contentRating[]"] = ratings |
| 476 |
params["offset"] = 0 |
| 477 |
|
| 478 |
if api_params := config("api-parameters"): |
| 479 |
for key in api_params: |
| 480 |
if key in params: |
| 481 |
del params[key] |
| 482 |
params.update(api_params) |
| 483 |
|
| 484 |
while True: |
| 485 |
data = self._call(endpoint, params, auth) |
| 486 |
yield from data["data"] |
| 487 |
|
| 488 |
params["offset"] = data["offset"] + data["limit"] |
| 489 |
if params["offset"] >= data["total"]: |
| 490 |
return |
| 491 |
|
| 492 |
|
| 493 |
def _refresh_token_cache(username): |
| 494 |
return None |