Debian Codegraph @

gallery_dl/extractor/pixiv.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2014-2026 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 """Extractors for https://www.pixiv.net/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util, dt
13 import itertools
14 import hashlib
15
16 BASE_PATTERN = r"(?:https?://)?(?:www\.|touch\.)?ph?ixiv\.net"
17 USER_PATTERN = BASE_PATTERN + r"/(?:en/)?users/(\d+)"
18
19
20 class PixivExtractor(Extractor):
21 """Base class for pixiv extractors"""
22 category = "pixiv"
23 root = "https://www.pixiv.net"
24 directory_fmt = ("{category}", "{user[id]} {user[account]}")
25 filename_fmt = "{id}_p{num}.{extension}"
26 archive_fmt = "{id}{suffix}.{extension}"
27 cookies_domain = ".pixiv.net"
28 limit_url = "https://s.pximg.net/common/images/limit_"
29 # https://s.pximg.net/common/images/limit_sanity_level_360.png
30 # https://s.pximg.net/common/images/limit_unviewable_360.png
31 # https://s.pximg.net/common/images/limit_mypixiv_360.png
32 # https://s.pximg.net/common/images/limit_unknown_360.png
33
34 def _init(self):
35 self.api = PixivAppAPI(self)
36 self.load_ugoira = self.config("ugoira", True)
37 self.load_ugoira_original = (self.load_ugoira == "original")
38 self.max_posts = self.config("max-posts", 0)
39 self.sanity_workaround = self.config("sanity", True)
40 self.meta_user = self.config("metadata")
41 self.meta_bookmark = self.config("metadata-bookmark")
42 self.meta_comments = self.config("comments")
43 self.meta_captions = self.config("captions")
44
45 if self.sanity_workaround or self.meta_captions:
46 self.meta_captions_sub = text.re(
47 r'<a href="/jump\.php\?([^"]+)').sub
48
49 def items(self):
50 tags = self.config("tags", "japanese")
51 if tags == "original":
52 transform_tags = None
53 elif tags == "translated":
54 def transform_tags(work):
55 work["tags"] = list(dict.fromkeys(
56 tag["translated_name"] or tag["name"]
57 for tag in work["tags"]))
58 else:
59 def transform_tags(work):
60 work["tags"] = [tag["name"] for tag in work["tags"]]
61
62 ratings = {0: "General", 1: "R-18", 2: "R-18G"}
63 metadata = self.metadata()
64
65 works = self.works()
66 if self.max_posts:
67 works = itertools.islice(works, self.max_posts)
68 for work in works:
69 if not work["user"]["id"]:
70 continue
71
72 files = self._extract_files(work)
73
74 if self.meta_user:
75 work.update(self.api.user_detail(str(work["user"]["id"])))
76 if self.meta_comments:
77 if work.get("total_comments") and not work.get("_ajax"):
78 try:
79 work["comments"] = list(
80 self.api.illust_comments(work["id"]))
81 except Exception:
82 work["comments"] = ()
83 else:
84 work["comments"] = ()
85 if self.meta_bookmark and work["is_bookmarked"]:
86 detail = self.api.illust_bookmark_detail(work["id"])
87 work["tags_bookmark"] = [tag["name"] for tag in detail["tags"]
88 if tag["is_registered"]]
89 if self.meta_captions and not work.get("caption") and \
90 not work.get("_mypixiv") and not work.get("_ajax"):
91 if body := self._request_ajax("/illust/" + str(work["id"])):
92 work["caption"] = self._sanitize_ajax_caption(
93 body["illustComment"])
94
95 if transform_tags is not None:
96 transform_tags(work)
97 work["num"] = 0
98 work["date"] = dt.parse_iso(work["create_date"])
99 work["count"] = len(files)
100 work["rating"] = ratings.get(work["x_restrict"])
101 work["suffix"] = ""
102 work.update(metadata)
103
104 yield Message.Directory, "", work
105 for work["num"], file in enumerate(files):
106 url = file["url"]
107 work.update(file)
108 text.nameext_from_url(url, work)
109 work["date_url"] = self._date_from_url(url)
110 work["hash"] = (name[name.find("-")+1:name.rfind("_")]
111 if "-" in (name := work["filename"]) else "")
112 yield Message.Url, url, work
113
114 def _extract_files(self, work):
115 meta_single_page = work["meta_single_page"]
116 meta_pages = work["meta_pages"]
117 del work["meta_single_page"]
118 del work["image_urls"]
119 del work["meta_pages"]
120
121 if meta_pages:
122 return [
123 {
124 "url" : img["image_urls"]["original"],
125 "suffix": f"_p{num:02}",
126 "_fallback": self._fallback_image(img),
127 }
128 for num, img in enumerate(meta_pages)
129 ]
130
131 url = meta_single_page["original_image_url"]
132 if url.startswith(self.limit_url):
133 work_id = work["id"]
134 self.log.debug("%s: %s", work_id, url)
135
136 limit_type = url.rpartition("/")[2]
137 if limit_type in {
138 "limit_", # for '_extend_sanity()' inserts
139 "limit_unviewable_360.png",
140 "limit_sanity_level_360.png",
141 }:
142 work["_ajax"] = True
143 self.log.warning("%s: 'limit_sanity_level' warning", work_id)
144 if self.sanity_workaround:
145 body = self._request_ajax("/illust/" + str(work_id))
146 if work["type"] == "ugoira":
147 if not self.load_ugoira:
148 return ()
149 self.log.info("%s: Retrieving Ugoira AJAX metadata",
150 work["id"])
151 try:
152 self._extract_ajax(work, body)
153 return self._extract_ugoira(work, url)
154 except Exception as exc:
155 self.log.traceback(exc)
156 self.log.warning(
157 "%s: Unable to extract Ugoira URL. Provide "
158 "logged-in cookies to access it", work["id"])
159 else:
160 return self._extract_ajax(work, body)
161
162 elif limit_type == "limit_mypixiv_360.png":
163 work["_mypixiv"] = True
164 self.log.warning("%s: 'My pixiv' locked", work_id)
165
166 elif limit_type == "limit_unknown_360.png":
167 work["_mypixiv"] = True # stop further processing
168 self.log.warning("%s: Deleted", work_id)
169
170 else:
171 work["_mypixiv"] = True # stop further processing
172 self.log.error("%s: Unknown 'limit' URL type: %s",
173 work_id, limit_type)
174
175 elif work["type"] != "ugoira":
176 return ({
177 "url": url,
178 "_fallback": (work.get("_fallback") or
179 self._fallback_image(url)),
180 },)
181
182 elif self.load_ugoira:
183 try:
184 return self._extract_ugoira(work, url)
185 except Exception as exc:
186 self.log.warning(
187 "%s: Unable to retrieve Ugoira metatdata (%s - %s)",
188 work["id"], exc.__class__.__name__, exc)
189
190 return ()
191
192 def _extract_ugoira(self, work, img_url):
193 if work.get("_ajax"):
194 ugoira = self._request_ajax(
195 "/illust/" + str(work["id"]) + "/ugoira_meta")
196 img_url = ugoira["src"]
197 else:
198 ugoira = self.api.ugoira_metadata(work["id"])
199 work["_ugoira_frame_data"] = work["frames"] = frames = ugoira["frames"]
200 work["_ugoira_original"] = self.load_ugoira_original
201 work["_http_adjust_extension"] = False
202
203 if self.load_ugoira_original:
204 work["date_url"] = self._date_from_url(img_url)
205
206 base, sep, ext = img_url.rpartition("_ugoira0.")
207 if sep:
208 base += "_ugoira"
209 else:
210 base, sep, _ = img_url.rpartition("_ugoira")
211 base = base.replace(
212 "/img-zip-ugoira/", "/img-original/", 1) + sep
213
214 for ext in ("jpg", "png", "gif"):
215 try:
216 url = f"{base}0.{ext}"
217 self.request(url, method="HEAD")
218 break
219 except self.exc.HttpError:
220 pass
221 else:
222 self.log.warning(
223 "Unable to find Ugoira frame URLs (%s)", work["id"])
224
225 return [
226 {
227 "url": f"{base}{num}.{ext}",
228 "suffix": f"_p{num:02}",
229 "_ugoira_frame_index": num,
230 }
231 for num in range(len(frames))
232 ]
233
234 else:
235 if work.get("_ajax"):
236 zip_url = ugoira["originalSrc"]
237 else:
238 zip_url = ugoira["zip_urls"]["medium"]
239 work["date_url"] = self._date_from_url(zip_url)
240 url = zip_url.replace("_ugoira600x600", "_ugoira1920x1080", 1)
241 return ({"url": url},)
242
243 def _request_ajax(self, endpoint):
244 url = f"{self.root}/ajax{endpoint}"
245 try:
246 data = self.request_json(
247 url, headers=self.headers_web, fatal=False)
248 if not data.get("error"):
249 return data["body"]
250
251 self.log.debug("Server response: %s", util.json_dumps(data))
252 if (msg := data.get("message")) == "An unknown error occurred":
253 msg = "Invalid 'PHPSESSID' cookie"
254 else:
255 msg = f"'{msg or 'General Error'}'"
256 self.log.error("%s", msg)
257 except Exception:
258 pass
259
260 def _extract_ajax(self, work, body):
261 work["_ajax"] = True
262 url = self._extract_ajax_url(body)
263 if not url:
264 return ()
265
266 for key_app, key_ajax in (
267 ("title" , "illustTitle"),
268 ("image_urls" , "urls"),
269 ("create_date" , "createDate"),
270 ("width" , "width"),
271 ("height" , "height"),
272 ("sanity_level" , "sl"),
273 ("total_view" , "viewCount"),
274 ("total_comments" , "commentCount"),
275 ("total_bookmarks" , "bookmarkCount"),
276 ("restrict" , "restrict"),
277 ("x_restrict" , "xRestrict"),
278 ("illust_ai_type" , "aiType"),
279 ("illust_book_style", "bookStyle"),
280 ):
281 work[key_app] = body[key_ajax]
282
283 work["user"] = {
284 "account" : body["userAccount"],
285 "id" : int(body["userId"]),
286 "is_followed": False,
287 "name" : body["userName"],
288 "profile_image_urls": {},
289 }
290
291 if "is_bookmarked" not in work:
292 work["is_bookmarked"] = True if body.get("bookmarkData") else False
293
294 work["tags"] = tags = []
295 for tag in body["tags"]["tags"]:
296 name = tag["tag"]
297 try:
298 translated_name = tag["translation"]["en"]
299 except Exception:
300 translated_name = None
301 tags.append({"name": name, "translated_name": translated_name})
302
303 work["caption"] = self._sanitize_ajax_caption(body["illustComment"])
304 work["page_count"] = count = body["pageCount"]
305 if count == 1:
306 return ({"url": url},)
307
308 base, _, ext = url.rpartition("_p0.")
309 return [
310 {
311 "url" : f"{base}_p{num}.{ext}",
312 "suffix": f"_p{num:02}",
313 }
314 for num in range(count)
315 ]
316
317 def _extract_ajax_url(self, body):
318 try:
319 if original := body["urls"]["original"]:
320 return original
321 except Exception:
322 pass
323
324 try:
325 square1200 = body["userIllusts"][body["id"]]["url"]
326 except Exception:
327 return
328
329 parts = square1200.rpartition("_p0")[0].split("/")
330 if len(parts) < 6:
331 return self.log.warning(
332 "%s: %s", body["id"], square1200.rpartition("/")[2])
333
334 del parts[3:5]
335 parts[3] = "img-original"
336 base = "/".join(parts)
337
338 for ext in ("jpg", "png", "gif"):
339 try:
340 url = f"{base}_p0.{ext}"
341 self.request(url, method="HEAD")
342 return url
343 except self.exc.HttpError:
344 pass
345
346 def _sanitize_ajax_caption(self, caption):
347 if not caption:
348 return ""
349 return text.unescape(self.meta_captions_sub(
350 lambda m: '<a href="' + text.unquote(m[1]), caption))
351
352 def _fallback_image(self, src):
353 if isinstance(src, str):
354 urls = None
355 orig = src
356 else:
357 urls = src["image_urls"]
358 orig = urls["original"]
359
360 base = orig.rpartition(".")[0]
361 yield base.replace("-original/", "-master/", 1) + "_master1200.jpg"
362
363 if urls is None:
364 return
365
366 for fmt in ("large", "medium", "square_medium"):
367 if fmt in urls:
368 yield urls[fmt]
369
370 def _date_from_url(self, url, offset=dt.timedelta(hours=9)):
371 try:
372 _, _, _, _, _, y, m, d, H, M, S, _ = url.split("/")
373 return dt.datetime(
374 int(y), int(m), int(d), int(H), int(M), int(S)) - offset
375 except Exception:
376 return None
377
378 def _make_work(self, kind, url, user):
379 p = url.split("/")
380 return {
381 "create_date" : (f"{p[5]}-{p[6]}-{p[7]}T{p[8]}:{p[9]}:{p[10]}"
382 f"+09:00" if len(p) > 9 else None),
383 "height" : 0,
384 "id" : kind,
385 "image_urls" : None,
386 "meta_pages" : (),
387 "meta_single_page": {"original_image_url": url},
388 "page_count" : 1,
389 "sanity_level" : 0,
390 "total_comments" : 0,
391 "is_bookmarked" : False,
392 "tags" : (),
393 "title" : kind,
394 "type" : kind,
395 "user" : user,
396 "width" : 0,
397 "x_restrict" : 0,
398 }
399
400 def works(self):
401 """Return an iterable containing all relevant 'work' objects"""
402
403 def metadata(self):
404 """Collect metadata for extractor job"""
405 return {}
406
407
408 class PixivUserExtractor(Dispatch, PixivExtractor):
409 """Extractor for a pixiv user profile"""
410 pattern = (BASE_PATTERN + r"/(?:"
411 r"(?:en/)?u(?:sers)?/|member\.php\?id=|(?:mypage\.php)?#id="
412 r")(\d+)(?:$|[?#])")
413 example = "https://www.pixiv.net/en/users/12345"
414
415 def items(self):
416 if (inc := self.config("include")) and (
417 "sketch" in inc or inc == "all"):
418 Extractor.initialize(self)
419 user = PixivAppAPI(self).user_detail(self.groups[0])
420 sketch = "https://sketch.pixiv.net/@" + user["user"]["account"]
421 else:
422 sketch = ""
423
424 base = f"{self.root}/users/{self.groups[0]}/"
425 return self._dispatch_extractors((
426 (PixivAvatarExtractor , base + "avatar"),
427 (PixivBackgroundExtractor , base + "background"),
428 (PixivArtworksExtractor , base + "artworks"),
429 (PixivFavoriteExtractor , base + "bookmarks/artworks"),
430 (PixivNovelBookmarkExtractor, base + "bookmarks/novels"),
431 (PixivNovelUserExtractor , base + "novels"),
432 (PixivSketchExtractor , sketch),
433 ), ("artworks",), (
434 ("bookmark", "novel-bookmark", None),
435 ("user" , "novel-user" , None),
436 ))
437
438
439 class PixivArtworksExtractor(PixivExtractor):
440 """Extractor for artworks of a pixiv user"""
441 subcategory = "artworks"
442 pattern = (BASE_PATTERN + r"/(?:"
443 r"(?:en/)?users/(\d+)/(?:artworks|illustrations|manga)"
444 r"(?:/([^/?#]+))?/?(?:$|[?#])"
445 r"|member_illust\.php\?id=(\d+)(?:&([^#]+))?)")
446 example = "https://www.pixiv.net/en/users/12345/artworks"
447 _warn_phpsessid = True
448
449 def _init(self):
450 PixivExtractor._init(self)
451
452 u1, t1, u2, t2 = self.groups
453 if t1:
454 t1 = text.unquote(t1)
455 elif t2:
456 t2 = text.parse_query(t2).get("tag")
457 self.user_id = u1 or u2
458 self.tag = t1 or t2
459
460 if self.sanity_workaround and self._warn_phpsessid:
461 PixivArtworksExtractor._warn_phpsessid = False
462 if not self.cookies.get("PHPSESSID", domain=self.cookies_domain):
463 self.log.warning("No 'PHPSESSID' cookie set. Can detect only "
464 "non R-18 'limit_sanity_level' works.")
465
466 def metadata(self):
467 if self.config("metadata"):
468 self.api.user_detail(self.user_id)
469 return {}
470
471 def works(self):
472 works = self.api.user_illusts(self.user_id)
473
474 if self.sanity_workaround and (body := self._request_ajax(
475 f"/user/{self.user_id}/profile/all")):
476 try:
477 ajax_ids = list(map(int, body["illusts"]))
478 ajax_ids.extend(map(int, body["manga"]))
479 ajax_ids.sort()
480 except Exception as exc:
481 self.log.traceback(exc)
482 self.log.warning("u%s: Failed to collect artwork IDs "
483 "using AJAX API", self.user_id)
484 else:
485 works = self._extend_sanity(works, ajax_ids)
486
487 if self.tag:
488 tag = self.tag.lower()
489 works = (
490 work for work in works
491 if tag in [t["name"].lower() for t in work["tags"]]
492 )
493
494 return works
495
496 def _extend_sanity(self, works, ajax_ids):
497 user = {"id": 1}
498 index = len(ajax_ids) - 1
499
500 for work in works:
501 while index >= 0:
502 work_id = work["id"]
503 ajax_id = ajax_ids[index]
504
505 if ajax_id == work_id:
506 index -= 1
507 break
508
509 elif ajax_id > work_id:
510 index -= 1
511 self.log.debug("Inserting work %s", ajax_id)
512 yield self._make_work(ajax_id, self.limit_url, user)
513
514 else: # ajax_id < work_id
515 break
516
517 yield work
518
519 while index >= 0:
520 ajax_id = ajax_ids[index]
521 self.log.debug("Inserting work %s", ajax_id)
522 yield self._make_work(ajax_id, self.limit_url, user)
523 index -= 1
524
525
526 class PixivAvatarExtractor(PixivExtractor):
527 """Extractor for pixiv avatars"""
528 subcategory = "avatar"
529 filename_fmt = "avatar{date:?_//%Y-%m-%d}.{extension}"
530 archive_fmt = "avatar_{user[id]}_{date}"
531 pattern = USER_PATTERN + r"/avatar"
532 example = "https://www.pixiv.net/en/users/12345/avatar"
533
534 def _init(self):
535 PixivExtractor._init(self)
536 self.sanity_workaround = \
537 self.meta_bookmark = \
538 self.meta_comments = \
539 self.meta_captions = False
540
541 def works(self):
542 user = self.api.user_detail(self.groups[0])["user"]
543 url = user["profile_image_urls"]["medium"].replace("_170.", ".")
544 return (self._make_work("avatar", url, user),)
545
546
547 class PixivBackgroundExtractor(PixivExtractor):
548 """Extractor for pixiv background banners"""
549 subcategory = "background"
550 filename_fmt = "background{date:?_//%Y-%m-%d}.{extension}"
551 archive_fmt = "background_{user[id]}_{date}"
552 pattern = USER_PATTERN + "/background"
553 example = "https://www.pixiv.net/en/users/12345/background"
554
555 _init = PixivAvatarExtractor._init
556
557 def works(self):
558 detail = self.api.user_detail(self.groups[0])
559 url = detail["profile"]["background_image_url"]
560 if not url:
561 return ()
562 if "/c/" in url:
563 parts = url.split("/")
564 del parts[3:5]
565 url = "/".join(parts)
566 url = url.replace("_master1200.", ".")
567 work = self._make_work("background", url, detail["user"])
568 if url.endswith(".jpg"):
569 url = url[:-4]
570 work["_fallback"] = (url + ".png", url + ".gif")
571 return (work,)
572
573
574 class PixivMeExtractor(PixivExtractor):
575 """Extractor for pixiv.me URLs"""
576 subcategory = "me"
577 pattern = r"(?:https?://)?pixiv\.me/([^/?#]+)"
578 example = "https://pixiv.me/USER"
579
580 def items(self):
581 url = "https://pixiv.me/" + self.groups[0]
582 location = self.request_location(url, notfound="user")
583 yield Message.Queue, location, {"_extractor": PixivUserExtractor}
584
585
586 class PixivWorkExtractor(PixivExtractor):
587 """Extractor for a single pixiv work/illustration"""
588 subcategory = "work"
589 pattern = (r"(?:https?://)?(?:(?:www\.|touch\.)?ph?ixiv\.net"
590 r"/(?:(?:en/)?artworks/"
591 r"|member_illust\.php\?(?:[^&]+&)*illust_id=)(\d+)"
592 r"|(?:i(?:\d+\.pixiv|\.pximg)\.net"
593 r"/(?:(?:.*/)?img-[^/]+/img/\d{4}(?:/\d\d){5}|img\d+/img/[^/]+)"
594 r"|img\d*\.pixiv\.net/img/[^/]+|(?:www\.)?pixiv\.net/i)/(\d+))")
595 example = "https://www.pixiv.net/artworks/12345"
596
597 def __init__(self, match):
598 PixivExtractor.__init__(self, match)
599 self.illust_id = match[1] or match[2]
600
601 def works(self):
602 works = (self.api.illust_detail(self.illust_id),)
603 if self.config("related", False):
604 related = self.api.illust_related(self.illust_id)
605 works = itertools.chain(works, related)
606 return works
607
608
609 class PixivUnlistedExtractor(PixivExtractor):
610 """Extractor for a unlisted pixiv illustrations"""
611 subcategory = "unlisted"
612 pattern = BASE_PATTERN + r"/(?:en/)?artworks/unlisted/(\w+)"
613 example = "https://www.pixiv.net/en/artworks/unlisted/a1b2c3d4e5f6g7h8i9j0"
614
615 def _extract_files(self, work):
616 body = self._request_ajax("/illust/unlisted/" + work["id"])
617 work["id_unlisted"] = work["id"]
618 work["id"] = text.parse_int(body["illustId"])
619 return self._extract_ajax(work, body)
620
621 def works(self):
622 return ({"id": self.groups[0], "user": {"id": 1}},)
623
624
625 class PixivFavoriteExtractor(PixivExtractor):
626 """Extractor for all favorites/bookmarks of a pixiv user"""
627 subcategory = "favorite"
628 directory_fmt = ("{category}", "bookmarks",
629 "{user_bookmark[id]} {user_bookmark[account]}")
630 archive_fmt = "f_{user_bookmark[id]}_{id}{num}.{extension}"
631 pattern = (BASE_PATTERN + r"/(?:(?:en/)?"
632 r"users/(\d+)/(bookmarks/artworks|following)(?:/([^/?#]+))?"
633 r"|bookmark\.php)(?:\?([^#]*))?")
634 example = "https://www.pixiv.net/en/users/12345/bookmarks/artworks"
635
636 def __init__(self, match):
637 uid, kind, self.tag, query = match.groups()
638 query = text.parse_query(query)
639
640 if not uid:
641 uid = query.get("id")
642 if not uid:
643 self.subcategory = "bookmark"
644
645 if kind == "following" or query.get("type") == "user":
646 self.subcategory = "following"
647 self.items = self._items_following
648
649 PixivExtractor.__init__(self, match)
650 self.query = query
651 self.user_id = uid
652
653 def works(self):
654 tag = None
655 if "tag" in self.query:
656 tag = text.unquote(self.query["tag"])
657 elif self.tag:
658 tag = text.unquote(self.tag)
659
660 restrict = "public"
661 if self.query.get("rest") == "hide":
662 restrict = "private"
663
664 return self.api.user_bookmarks_illust(
665 self.user_id, tag, restrict, self.config("cursor"))
666
667 def metadata(self):
668 if self.user_id:
669 user = self.api.user_detail(self.user_id)["user"]
670 else:
671 self.api.login()
672 user = self.api.user
673
674 self.user_id = user["id"]
675 return {"user_bookmark": user}
676
677 def finalize(self, status):
678 if status and self.api.params and (
679 bid := self.api.params.get("max_bookmark_id")):
680 self.log.info("Use '-o cursor=%s' to continue downloading "
681 "from the current position", bid)
682
683 def _items_following(self):
684 restrict = "public"
685 if self.query.get("rest") == "hide":
686 restrict = "private"
687
688 for preview in self.api.user_following(self.user_id, restrict):
689 user = preview["user"]
690 user["_extractor"] = PixivUserExtractor
691 url = "https://www.pixiv.net/users/" + str(user["id"])
692 yield Message.Queue, url, user
693
694
695 class PixivRankingExtractor(PixivExtractor):
696 """Extractor for pixiv ranking pages"""
697 subcategory = "ranking"
698 archive_fmt = "r_{ranking[mode]}_{ranking[date]}_{id}{num}.{extension}"
699 directory_fmt = ("{category}", "rankings",
700 "{ranking[mode]}", "{ranking[date]}")
701 pattern = BASE_PATTERN + r"/ranking\.php(?:\?([^#]*))?"
702 example = "https://www.pixiv.net/ranking.php"
703
704 def __init__(self, match):
705 PixivExtractor.__init__(self, match)
706 self.query = match[1]
707 self.mode = self.date = None
708
709 def works(self):
710 ranking = self.ranking
711
712 works = self.api.illust_ranking(self.mode, self.date)
713 if self.type:
714 works = filter(lambda work, t=self.type: work["type"] == t, works)
715
716 for ranking["rank"], work in enumerate(works, 1):
717 yield work
718
719 def metadata(self):
720 query = text.parse_query(self.query)
721
722 mode = query.get("mode", "daily").lower()
723 mode_map = {
724 "daily": "day",
725 "daily_r18": "day_r18",
726 "daily_ai": "day_ai",
727 "daily_r18_ai": "day_r18_ai",
728 "weekly": "week",
729 "weekly_r18": "week_r18",
730 "monthly": "month",
731 "male": "day_male",
732 "male_r18": "day_male_r18",
733 "female": "day_female",
734 "female_r18": "day_female_r18",
735 "original": "week_original",
736 "rookie": "week_rookie",
737 "r18g": "week_r18g",
738 }
739 try:
740 self.mode = mode = mode_map[mode]
741 except KeyError:
742 raise self.exc.AbortExtraction(f"Invalid mode '{mode}'")
743
744 if date := query.get("date"):
745 if len(date) == 8 and date.isdecimal():
746 date = f"{date[0:4]}-{date[4:6]}-{date[6:8]}"
747 else:
748 self.log.warning("invalid date '%s'", date)
749 date = None
750 if not date:
751 date = (dt.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d")
752 self.date = date
753
754 self.type = type = query.get("content")
755
756 self.ranking = ranking = {
757 "mode": mode,
758 "date": self.date,
759 "rank": 0,
760 "type": type or "all",
761 }
762 return {"ranking": ranking}
763
764
765 class PixivSearchExtractor(PixivExtractor):
766 """Extractor for pixiv search results"""
767 subcategory = "search"
768 archive_fmt = "s_{search[word]}_{id}{num}.{extension}"
769 directory_fmt = ("{category}", "search", "{search[word]}")
770 pattern = (BASE_PATTERN + r"/(?:(?:en/)?tags/([^/?#]+)(?:/[^/?#]+)?/?"
771 r"|search(?:\.php)?)(?:\?([^#]+))?")
772 example = "https://www.pixiv.net/en/tags/TAG"
773
774 def __init__(self, match):
775 PixivExtractor.__init__(self, match)
776 self.word, self.query = match.groups()
777 self.sort = self.target = None
778
779 def works(self):
780 return self.api.search_illust(
781 self.word, self.sort, self.target,
782 date_start=self.date_start, date_end=self.date_end)
783
784 def metadata(self):
785 query = text.parse_query(self.query)
786
787 if self.word:
788 self.word = text.unquote(self.word)
789 else:
790 try:
791 self.word = query.get("q") or query["word"]
792 except KeyError:
793 raise self.exc.AbortExtraction("Missing search term")
794
795 sort = query.get("order", "date_d")
796 sort_map = {
797 "date": "date_asc",
798 "date_d": "date_desc",
799 "popular_d": "popular_desc",
800 "popular_male_d": "popular_male_desc",
801 "popular_female_d": "popular_female_desc",
802 }
803 try:
804 self.sort = sort = sort_map[sort]
805 except KeyError:
806 raise self.exc.AbortExtraction(f"Invalid search order '{sort}'")
807
808 target = query.get("s_mode", "s_tag_full")
809 target_map = {
810 "tag" : "partial_match_for_tags",
811 "s_tag": "partial_match_for_tags",
812 "tag_full" : "exact_match_for_tags",
813 "s_tag_full": "exact_match_for_tags",
814 "tc" : "title_and_caption",
815 "s_tc": "title_and_caption",
816 }
817 try:
818 self.target = target = target_map[target]
819 except KeyError:
820 raise self.exc.AbortExtraction(f"Invalid search mode '{target}'")
821
822 self.date_start = query.get("scd")
823 self.date_end = query.get("ecd")
824
825 return {"search": {
826 "word": self.word,
827 "sort": self.sort,
828 "target": self.target,
829 "date_start": self.date_start,
830 "date_end": self.date_end,
831 }}
832
833
834 class PixivFollowedExtractor(PixivExtractor):
835 """Extractor for new illustrations from your followed artists"""
836 subcategory = "followed"
837 archive_fmt = "F_{user_follow[id]}_{id}{num}.{extension}"
838 directory_fmt = ("{category}", "following")
839 pattern = BASE_PATTERN + r"/bookmark_new_illust\.php"
840 example = "https://www.pixiv.net/bookmark_new_illust.php"
841
842 def works(self):
843 return self.api.illust_follow()
844
845 def metadata(self):
846 self.api.login()
847 return {"user_follow": self.api.user}
848
849
850 class PixivPixivisionExtractor(PixivExtractor):
851 """Extractor for illustrations from a pixivision article"""
852 subcategory = "pixivision"
853 directory_fmt = ("{category}", "pixivision",
854 "{pixivision_id} {pixivision_title}")
855 archive_fmt = "V{pixivision_id}_{id}{suffix}.{extension}"
856 pattern = r"(?:https?://)?(?:www\.)?pixivision\.net/(?:en/)?a/(\d+)"
857 example = "https://www.pixivision.net/en/a/12345"
858
859 def __init__(self, match):
860 PixivExtractor.__init__(self, match)
861 self.pixivision_id = match[1]
862
863 def works(self):
864 return (
865 self.api.illust_detail(illust_id.partition("?")[0])
866 for illust_id in util.unique_sequence(text.extract_iter(
867 self.page, '<a href="https://www.pixiv.net/en/artworks/', '"'))
868 )
869
870 def metadata(self):
871 url = "https://www.pixivision.net/en/a/" + self.pixivision_id
872 headers = {"User-Agent": "Mozilla/5.0"}
873 self.page = self.request(url, headers=headers).text
874
875 title = text.extr(self.page, '<title>', '<')
876 return {
877 "pixivision_id" : self.pixivision_id,
878 "pixivision_title": text.unescape(title),
879 }
880
881
882 class PixivSeriesExtractor(PixivExtractor):
883 """Extractor for illustrations from a Pixiv series"""
884 subcategory = "series"
885 directory_fmt = ("{category}", "{user[id]} {user[account]}",
886 "{series[id]} {series[title]}")
887 filename_fmt = "{num_series:>03}_{id}_p{num}.{extension}"
888 pattern = BASE_PATTERN + r"/user/(\d+)/series/(\d+)"
889 example = "https://www.pixiv.net/user/12345/series/12345"
890
891 def __init__(self, match):
892 PixivExtractor.__init__(self, match)
893 self.user_id, self.series_id = match.groups()
894
895 def works(self):
896 series = None
897
898 for work in self.api.illust_series(self.series_id):
899 if series is None:
900 series = self.api.data
901 series["total"] = num_series = series.pop("series_work_count")
902 else:
903 num_series -= 1
904
905 work["num_series"] = num_series
906 work["series"] = series
907 yield work
908
909
910 class PixivSketchExtractor(Extractor):
911 """Extractor for user pages on sketch.pixiv.net"""
912 category = "pixiv"
913 subcategory = "sketch"
914 directory_fmt = ("{category}", "sketch", "{user[unique_name]}")
915 filename_fmt = "{post_id} {id}.{extension}"
916 archive_fmt = "S{user[id]}_{id}"
917 root = "https://sketch.pixiv.net"
918 cookies_domain = ".pixiv.net"
919 pattern = r"(?:https?://)?sketch\.pixiv\.net/@([^/?#]+)"
920 example = "https://sketch.pixiv.net/@USER"
921
922 def items(self):
923 self.username = self.groups[0]
924 headers = {"Referer": f"{self.root}/@{self.username}"}
925
926 for post in self.posts():
927 media = post["media"]
928 post["post_id"] = post["id"]
929 post["date"] = dt.parse_iso(post["created_at"])
930 util.delete_items(post, ("id", "media", "_links"))
931
932 yield Message.Directory, "", post
933 post["_http_headers"] = headers
934
935 for photo in media:
936 original = photo["photo"]["original"]
937 post["id"] = photo["id"]
938 post["width"] = original["width"]
939 post["height"] = original["height"]
940
941 url = original["url"]
942 text.nameext_from_url(url, post)
943 yield Message.Url, url, post
944
945 def posts(self):
946 url = f"{self.root}/api/walls/@{self.username}/posts/public.json"
947 headers = {
948 "Accept": "application/vnd.sketch-v4+json",
949 "Referer": self.root + "/",
950 "X-Requested-With": f"{self.root}/@{self.username}",
951 }
952
953 while True:
954 data = self.request_json(url, headers=headers)
955 yield from data["data"]["items"]
956
957 next_url = data["_links"].get("next")
958 if not next_url:
959 return
960 url = self.root + next_url["href"]
961
962
963 ###############################################################################
964 # Novels ######################################################################
965
966 class PixivNovelExtractor(PixivExtractor):
967 """Base class for pixiv novel extractors"""
968 category = "pixiv-novel"
969 request_interval = (0.5, 1.5)
970
971 def items(self):
972 self.novel_id = self.groups[0]
973
974 tags = self.config("tags", "japanese")
975 if tags == "original":
976 transform_tags = None
977 elif tags == "translated":
978 def transform_tags(work):
979 work["tags"] = list(dict.fromkeys(
980 tag["translated_name"] or tag["name"]
981 for tag in work["tags"]))
982 else:
983 def transform_tags(work):
984 work["tags"] = [tag["name"] for tag in work["tags"]]
985
986 ratings = {0: "General", 1: "R-18", 2: "R-18G"}
987 embeds = self.config("embeds")
988 covers = self.config("covers")
989
990 novels = self.novels()
991 if self.max_posts:
992 novels = itertools.islice(novels, self.max_posts)
993 for novel in novels:
994 if self.meta_user:
995 novel.update(self.api.user_detail(str(novel["user"]["id"])))
996 if self.meta_comments:
997 if novel.get("total_comments"):
998 novel["comments"] = list(
999 self.api.novel_comments(novel["id"]))
1000 else:
1001 novel["comments"] = ()
1002 if self.meta_bookmark and novel["is_bookmarked"]:
1003 detail = self.api.novel_bookmark_detail(novel["id"])
1004 novel["tags_bookmark"] = [tag["name"] for tag in detail["tags"]
1005 if tag["is_registered"]]
1006 if transform_tags:
1007 transform_tags(novel)
1008 novel["num"] = 0
1009 novel["date"] = dt.parse_iso(novel["create_date"])
1010 novel["rating"] = ratings.get(novel["x_restrict"])
1011 novel["suffix"] = ""
1012
1013 yield Message.Directory, "", novel
1014
1015 try:
1016 content = self.api.novel_webview(novel["id"])["text"]
1017 except Exception:
1018 self.log.warning("Unable to download novel %s", novel["id"])
1019 continue
1020
1021 novel["extension"] = "txt"
1022 yield Message.Url, "text:" + content, novel
1023
1024 if covers:
1025 path = novel["image_urls"]["large"].partition("/img/")[2]
1026 url = ("https://i.pximg.net/novel-cover-original/img/" +
1027 path.rpartition(".")[0].replace("_master1200", ""))
1028 novel["date_url"] = self._date_from_url(url)
1029 novel["num"] += 1
1030 novel["suffix"] = f"_p{novel['num']:02}"
1031 novel["_fallback"] = (url + ".png",)
1032 url_jpg = url + ".jpg"
1033 text.nameext_from_url(url_jpg, novel)
1034 yield Message.Url, url_jpg, novel
1035 del novel["_fallback"]
1036
1037 if embeds:
1038 desktop = False
1039 illusts = {}
1040
1041 for marker in text.extract_iter(content, "[", "]"):
1042 if marker.startswith("uploadedimage:"):
1043 desktop = True
1044 elif marker.startswith("pixivimage:"):
1045 illusts[marker[11:].partition("-")[0]] = None
1046
1047 if desktop:
1048 try:
1049 body = self._request_ajax("/novel/" + str(novel["id"]))
1050 images = body["textEmbeddedImages"].values()
1051 except Exception as exc:
1052 self.log.warning(
1053 "%s: Failed to get embedded novel images (%s: %s)",
1054 novel["id"], exc.__class__.__name__, exc)
1055 images = ()
1056
1057 for image in images:
1058 url = image.pop("urls")["original"]
1059 novel.update(image)
1060 novel["date_url"] = self._date_from_url(url)
1061 novel["num"] += 1
1062 novel["suffix"] = f"_p{novel['num']:02}"
1063 text.nameext_from_url(url, novel)
1064 yield Message.Url, url, novel
1065
1066 if illusts:
1067 novel["_extractor"] = PixivWorkExtractor
1068 novel["date_url"] = None
1069 for illust_id in illusts:
1070 novel["num"] += 1
1071 novel["suffix"] = f"_p{novel['num']:02}"
1072 url = f"{self.root}/artworks/{illust_id}"
1073 yield Message.Queue, url, novel
1074
1075
1076 class PixivNovelNovelExtractor(PixivNovelExtractor):
1077 """Extractor for pixiv novels"""
1078 subcategory = "novel"
1079 pattern = BASE_PATTERN + r"/n(?:ovel/show\.php\?id=|/)(\d+)"
1080 example = "https://www.pixiv.net/novel/show.php?id=12345"
1081
1082 def novels(self):
1083 novel = self.api.novel_detail(self.novel_id)
1084 if self.config("full-series") and novel["series"]:
1085 self.subcategory = PixivNovelSeriesExtractor.subcategory
1086 return self.api.novel_series(novel["series"]["id"])
1087 return (novel,)
1088
1089
1090 class PixivNovelUserExtractor(PixivNovelExtractor):
1091 """Extractor for pixiv users' novels"""
1092 subcategory = "user"
1093 pattern = USER_PATTERN + r"/novels"
1094 example = "https://www.pixiv.net/en/users/12345/novels"
1095
1096 def novels(self):
1097 return self.api.user_novels(self.novel_id)
1098
1099
1100 class PixivNovelSeriesExtractor(PixivNovelExtractor):
1101 """Extractor for pixiv novel series"""
1102 subcategory = "series"
1103 pattern = BASE_PATTERN + r"/novel/series/(\d+)"
1104 example = "https://www.pixiv.net/novel/series/12345"
1105
1106 def novels(self):
1107 return self.api.novel_series(self.novel_id)
1108
1109
1110 class PixivNovelBookmarkExtractor(PixivNovelExtractor):
1111 """Extractor for bookmarked pixiv novels"""
1112 subcategory = "bookmark"
1113 pattern = (USER_PATTERN + r"/bookmarks/novels"
1114 r"(?:/([^/?#]+))?(?:/?\?([^#]+))?")
1115 example = "https://www.pixiv.net/en/users/12345/bookmarks/novels"
1116
1117 def novels(self):
1118 user_id, tag, query = self.groups
1119 tag = text.unquote(tag) if tag else None
1120
1121 if text.parse_query(query).get("rest") == "hide":
1122 restrict = "private"
1123 else:
1124 restrict = "public"
1125
1126 return self.api.user_bookmarks_novel(
1127 user_id, tag, restrict, self.config("cursor"))
1128
1129 def finalize(self, status):
1130 if status and self.api.params and (
1131 bid := self.api.params.get("max_bookmark_id")):
1132 self.log.info("Use '-o cursor=%s' to continue downloading "
1133 "from the current position", bid)
1134
1135
1136 ###############################################################################
1137 # API #########################################################################
1138
1139 class PixivAppAPI():
1140 """Minimal interface for the Pixiv App API for mobile devices
1141
1142 For a more complete implementation or documentation, see
1143 - https://github.com/upbit/pixivpy
1144 - https://gist.github.com/ZipFile/3ba99b47162c23f8aea5d5942bb557b1
1145 """
1146 CLIENT_ID = "MOBrBDS8blbauoSck0ZfDbtuzpyT"
1147 CLIENT_SECRET = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"
1148 HASH_SECRET = ("28c1fdd170a5204386cb1313c7077b34"
1149 "f83e4aaf4aa829ce78c231e05b0bae2c")
1150
1151 def __init__(self, extractor):
1152 self.extractor = extractor
1153 self.log = extractor.log
1154 self.exc = extractor.exc
1155 self.username = extractor._get_auth_info()[0]
1156 self.user = None
1157 self.params = None
1158
1159 extractor.headers_web = extractor.session.headers.copy()
1160 extractor.session.headers.update({
1161 "App-OS" : "ios",
1162 "App-OS-Version": "16.7.2",
1163 "App-Version" : "7.19.1",
1164 "User-Agent" : "PixivIOSApp/7.19.1 (iOS 16.7.2; iPhone12,8)",
1165 "Referer" : "https://app-api.pixiv.net/",
1166 })
1167
1168 self.client_id = extractor.config(
1169 "client-id", self.CLIENT_ID)
1170 self.client_secret = extractor.config(
1171 "client-secret", self.CLIENT_SECRET)
1172
1173 token = extractor.config("refresh-token")
1174 if token is None or token == "cache":
1175 token = extractor.cache(
1176 _refresh_token_cache, self.username, _mem=False)
1177 self.refresh_token = token
1178
1179 def login(self):
1180 """Login and gain an access token"""
1181 self.user, auth = self.extractor.cache(
1182 self._login_impl, self.username, _exp=3600, _mem=False)
1183 self.extractor.session.headers["Authorization"] = auth
1184
1185 def _login_impl(self, username):
1186 if not self.refresh_token:
1187 raise self.exc.AuthenticationError(
1188 "'refresh-token' required.\n"
1189 "Run `gallery-dl oauth:pixiv` to get one.")
1190
1191 self.log.info("Refreshing access token")
1192 url = "https://oauth.secure.pixiv.net/auth/token"
1193 data = {
1194 "client_id" : self.client_id,
1195 "client_secret" : self.client_secret,
1196 "grant_type" : "refresh_token",
1197 "refresh_token" : self.refresh_token,
1198 "get_secure_url": "1",
1199 }
1200
1201 time = dt.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
1202 headers = {
1203 "X-Client-Time": time,
1204 "X-Client-Hash": hashlib.md5(
1205 (time + self.HASH_SECRET).encode()).hexdigest(),
1206 }
1207
1208 response = self.extractor.request(
1209 url, method="POST", headers=headers, data=data, fatal=False)
1210 if response.status_code >= 400:
1211 self.log.debug(response.text)
1212 raise self.exc.AuthenticationError("Invalid refresh token")
1213
1214 data = response.json()["response"]
1215 return data["user"], "Bearer " + data["access_token"]
1216
1217 def illust_detail(self, illust_id):
1218 params = {"illust_id": illust_id}
1219 return self._call("/v1/illust/detail", params)["illust"]
1220
1221 def illust_bookmark_detail(self, illust_id):
1222 params = {"illust_id": illust_id}
1223 return self._call(
1224 "/v2/illust/bookmark/detail", params)["bookmark_detail"]
1225
1226 def illust_comments(self, illust_id):
1227 params = {"illust_id": illust_id}
1228 return self._pagination("/v3/illust/comments", params, "comments")
1229
1230 def illust_follow(self, restrict="all"):
1231 params = {"restrict": restrict}
1232 return self._pagination("/v2/illust/follow", params)
1233
1234 def illust_ranking(self, mode="day", date=None):
1235 params = {"mode": mode, "date": date}
1236 return self._pagination("/v1/illust/ranking", params)
1237
1238 def illust_related(self, illust_id):
1239 params = {"illust_id": illust_id}
1240 return self._pagination("/v2/illust/related", params)
1241
1242 def illust_series(self, series_id, offset=0):
1243 params = {"illust_series_id": series_id, "offset": offset}
1244 return self._pagination("/v1/illust/series", params,
1245 key_data="illust_series_detail")
1246
1247 def novel_bookmark_detail(self, novel_id):
1248 params = {"novel_id": novel_id}
1249 return self._call(
1250 "/v2/novel/bookmark/detail", params)["bookmark_detail"]
1251
1252 def novel_comments(self, novel_id):
1253 params = {"novel_id": novel_id}
1254 return self._pagination("/v1/novel/comments", params, "comments")
1255
1256 def novel_detail(self, novel_id):
1257 params = {"novel_id": novel_id}
1258 return self._call("/v2/novel/detail", params)["novel"]
1259
1260 def novel_series(self, series_id):
1261 params = {"series_id": series_id}
1262 return self._pagination("/v1/novel/series", params, "novels")
1263
1264 def novel_text(self, novel_id):
1265 params = {"novel_id": novel_id}
1266 return self._call("/v1/novel/text", params)
1267
1268 def novel_webview(self, novel_id):
1269 params = {"id": novel_id, "viewer_version": "20221031_ai"}
1270 return self._call(
1271 "/webview/v2/novel", params, self._novel_webview_parse)
1272
1273 def _novel_webview_parse(self, response):
1274 return util.json_loads(text.extr(
1275 response.text, "novel: ", ",\n"))
1276
1277 def search_illust(self, word, sort=None, target=None, duration=None,
1278 date_start=None, date_end=None):
1279 params = {"word": word, "search_target": target,
1280 "sort": sort, "duration": duration,
1281 "start_date": date_start, "end_date": date_end}
1282 return self._pagination_search("/v1/search/illust", params)
1283
1284 def user_bookmarks_illust(self, user_id, tag=None, restrict="public",
1285 max_id=None):
1286 """Return illusts bookmarked by a user"""
1287 params = {"user_id": user_id, "tag": tag, "restrict": restrict,
1288 "max_bookmark_id": max_id}
1289 return self._pagination("/v1/user/bookmarks/illust", params)
1290
1291 def user_bookmarks_novel(self, user_id, tag=None, restrict="public",
1292 max_id=None):
1293 """Return novels bookmarked by a user"""
1294 params = {"user_id": user_id, "tag": tag, "restrict": restrict,
1295 "max_bookmark_id": max_id}
1296 return self._pagination("/v1/user/bookmarks/novel", params, "novels")
1297
1298 def user_bookmark_tags_illust(self, user_id, restrict="public"):
1299 """Return bookmark tags defined by a user"""
1300 params = {"user_id": user_id, "restrict": restrict}
1301 return self._pagination(
1302 "/v1/user/bookmark-tags/illust", params, "bookmark_tags")
1303
1304 def user_detail(self, user_id, fatal=True):
1305 return self.extractor.cache(self._user_detail_impl, user_id, fatal)
1306
1307 def _user_detail_impl(self, user_id, fatal):
1308 params = {"user_id": user_id}
1309 return self._call("/v1/user/detail", params, fatal=fatal)
1310
1311 def user_following(self, user_id, restrict="public"):
1312 params = {"user_id": user_id, "restrict": restrict}
1313 return self._pagination("/v1/user/following", params, "user_previews")
1314
1315 def user_illusts(self, user_id):
1316 params = {"user_id": user_id}
1317 return self._pagination("/v1/user/illusts", params, key_user="user")
1318
1319 def user_novels(self, user_id):
1320 params = {"user_id": user_id}
1321 return self._pagination("/v1/user/novels", params, "novels")
1322
1323 def ugoira_metadata(self, illust_id):
1324 params = {"illust_id": illust_id}
1325 return self._call("/v1/ugoira/metadata", params)["ugoira_metadata"]
1326
1327 def _call(self, endpoint, params=None, parse=None, fatal=True):
1328 url = "https://app-api.pixiv.net" + endpoint
1329
1330 while True:
1331 self.login()
1332 response = self.extractor.request(url, params=params, fatal=False)
1333
1334 if parse:
1335 data = parse(response)
1336 else:
1337 data = response.json()
1338
1339 if "error" not in data or not fatal:
1340 return data
1341
1342 self.log.debug(data)
1343
1344 if response.status_code == 404:
1345 raise self.exc.NotFoundError()
1346
1347 error = data["error"]
1348 if "rate limit" in (error.get("message") or "").lower():
1349 self.extractor.wait(seconds=300)
1350 continue
1351
1352 msg = (f"'{msg}'" if (msg := error.get("user_message")) else
1353 f"'{msg}'" if (msg := error.get("message")) else
1354 error)
1355 raise self.exc.AbortExtraction("API request failed: " + msg)
1356
1357 def _pagination(self, endpoint, params,
1358 key_items="illusts", key_data=None, key_user=None):
1359 data = self._call(endpoint, params)
1360
1361 if key_data is not None:
1362 self.data = data.get(key_data)
1363 if key_user is not None and not data[key_user].get("id"):
1364 user = self.user_detail(self.extractor.user_id, fatal=False)
1365 if user.get("error"):
1366 raise self.exc.NotFoundError("user")
1367 return
1368
1369 while True:
1370 yield from data[key_items]
1371
1372 if not data["next_url"]:
1373 return
1374 query = data["next_url"].rpartition("?")[2]
1375 self.params = text.parse_query(query)
1376 data = self._call(endpoint, self.params)
1377
1378 def _pagination_search(self, endpoint, params):
1379 sort = params["sort"]
1380 if sort == "date_desc":
1381 date_key = "end_date"
1382 date_off = dt.timedelta(days=1)
1383 date_cmp = lambda lhs, rhs: lhs >= rhs # noqa E731
1384 elif sort == "date_asc":
1385 date_key = "start_date"
1386 date_off = dt.timedelta(days=-1)
1387 date_cmp = lambda lhs, rhs: lhs <= rhs # noqa E731
1388 else:
1389 date_key = None
1390 date_last = None
1391
1392 while True:
1393 data = self._call(endpoint, params)
1394
1395 if date_last is None:
1396 yield from data["illusts"]
1397 else:
1398 works = data["illusts"]
1399 if date_cmp(date_last, works[-1]["create_date"]):
1400 for work in works:
1401 if date_last is None:
1402 yield work
1403 elif date_cmp(date_last, work["create_date"]):
1404 date_last = None
1405
1406 if not (next_url := data.get("next_url")):
1407 return
1408 query = next_url.rpartition("?")[2]
1409 params = text.parse_query(query)
1410
1411 if date_key and text.parse_int(params.get("offset")) >= 5000:
1412 date_last = data["illusts"][-1]["create_date"]
1413 date_val = (dt.parse_iso(date_last) + date_off).strftime(
1414 "%Y-%m-%d")
1415 self.log.info("Reached 'offset' >= 5000; "
1416 "Updating '%s' to '%s'", date_key, date_val)
1417 params[date_key] = date_val
1418 params.pop("offset", None)
1419
1420
1421 def _refresh_token_cache(username):
1422 return None