Debian Codegraph @

gallery_dl/extractor/deviantart.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2015-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.deviantart.com/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util, dt
13 import collections
14 import mimetypes
15 import time
16
17 BASE_PATTERN = (
18 r"(?:https?://)?(?:"
19 r"(?:www\.)?(?:fx)?deviantart\.com/(?!watch/)([\w-]+)|"
20 r"(?!www\.)([\w-]+)\.(?:fx)?deviantart\.com)"
21 )
22 DEFAULT_AVATAR = "https://a.deviantart.net/avatars/default.gif"
23
24
25 class DeviantartExtractor(Extractor):
26 """Base class for deviantart extractors"""
27 category = "deviantart"
28 root = "https://www.deviantart.com"
29 directory_fmt = ("{category}", "{username}")
30 filename_fmt = "{category}_{index}_{title}.{extension}"
31 cookies_domain = ".deviantart.com"
32 cookies_names = ("auth", "auth_secure", "userinfo")
33 _last_request = 0
34
35 def __init__(self, match):
36 Extractor.__init__(self, match)
37 self.user = (match[1] or match[2] or "").lower()
38 self.offset = 0
39
40 def _init(self):
41 self.jwt = self.config("jwt", False)
42 self.flat = self.config("flat", True)
43 self.extra = self.config("extra", False)
44 self.quality = self.config("quality", "100")
45 self.original = self.config("original", False)
46 self.previews = self.config("previews", False)
47 self.intermediary = self.config("intermediary", True)
48 self.comments_avatars = self.config("comments-avatars", False)
49 self.comments = self.comments_avatars or self.config("comments", False)
50
51 self.api = DeviantartOAuthAPI(self)
52 self.eclipse_api = None
53 self.group = False
54 self._premium_cache = {}
55
56 if self.config("auto-unwatch"):
57 self.unwatch = []
58 self.finalize = self._unwatch_premium
59 else:
60 self.unwatch = None
61
62 if self.quality:
63 if self.quality == "png":
64 self.quality = "-fullview.png?"
65 self.quality_sub = text.re(r"-fullview\.[a-z0-9]+\?").sub
66 else:
67 self.quality = ",q_" + str(self.quality)
68 self.quality_sub = text.re(r",q_\d+").sub
69
70 if self.intermediary:
71 self.intermediary_subn = text.re(r"(/f/[^/]+/[^/]+)/v\d+/.*").subn
72 self.blur_sub = text.re(r",blur_\d+").sub
73
74 if isinstance(self.original, str) and \
75 self.original.lower().startswith("image"):
76 self.original = True
77 self._update_content = self._update_content_image
78 else:
79 self._update_content = self._update_content_default
80
81 if self.previews == "all":
82 self.previews_images = self.previews = True
83 else:
84 self.previews_images = False
85
86 journals = self.config("journals", "html")
87 if journals == "html":
88 self.commit_journal = self._commit_journal_html
89 elif journals == "text":
90 self.commit_journal = self._commit_journal_text
91 else:
92 self.commit_journal = None
93
94 def request(self, url, **kwargs):
95 if "fatal" not in kwargs:
96 kwargs["fatal"] = False
97 while True:
98 response = Extractor.request(self, url, **kwargs)
99 if response.status_code != 403 or \
100 b"Request blocked." not in response.content:
101 return response
102 self.wait(seconds=300, reason="CloudFront block")
103
104 def skip_files(self, num):
105 self.offset += num
106 return num
107
108 def login(self):
109 if self.cookies_check(self.cookies_names):
110 return True
111
112 username, password = self._get_auth_info()
113 if username:
114 self.cookies_update(self.cache(
115 self._login_impl, username, password,
116 _exp=28*86400, _mem=False))
117 return True
118
119 def _login_impl(self, username, password):
120 self.log.info("Logging in as %s", username)
121
122 url = "https://www.deviantart.com/users/login"
123 page = self.request(url).text
124
125 def _hidden_inputs(html):
126 data = {}
127
128 for item in text.extract_iter(
129 html, '<input type="hidden" name="', '"/>'):
130 name, _, value = item.partition('" value="')
131 data[name] = text.unescape(value)
132
133 challenge = data.get("challenge")
134 if challenge and challenge != "0":
135 self.log.warning("Login requires solving a CAPTCHA")
136 self.log.debug(challenge)
137
138 return data
139
140 # username
141 data = _hidden_inputs(page)
142 data["username"] = username
143 data["password"] = ""
144 data["remember"] = "on"
145
146 self.sleep(2.0, "login (username)")
147 url = "https://www.deviantart.com/_sisu/do/step2"
148 response = self.request(url, method="POST", data=data)
149 if "st_err=user" in response.url:
150 raise self.exc.AuthorizationError()
151
152 # password
153 data = _hidden_inputs(response.text)
154 data["username"] = ""
155 data["password"] = password
156 data["remember"] = "on"
157
158 self.sleep(2.0, "login (password)")
159 url = "https://www.deviantart.com/_sisu/do/signin"
160 response = self.request(url, method="POST", data=data)
161
162 if not response.history:
163 if b"<title>Access to this page has been deni" in response.content:
164 raise self.exc.AuthorizationError("CAPTCHA required")
165 raise self.exc.AuthenticationError()
166
167 return {cookie.name: cookie.value
168 for cookie in self.cookies}
169
170 def items(self):
171 if self.user:
172 if group := self.config("group", True):
173 if user := self.cache(self._user_details, self.user):
174 self.user = user["username"]
175 self.group = False
176 elif group == "skip":
177 self.log.info("Skipping group '%s'", self.user)
178 raise self.exc.AbortExtraction()
179 else:
180 self.subcategory = "group-" + self.subcategory
181 self.group = True
182
183 for deviation in self.deviations():
184 if isinstance(deviation, tuple):
185 url, data = deviation
186 yield Message.Queue, url, data
187 continue
188
189 if deviation["is_deleted"]:
190 # prevent crashing in case the deviation really is
191 # deleted
192 self.log.debug(
193 "Skipping %s (deleted)", deviation["deviationid"])
194 continue
195
196 tier_access = deviation.get("tier_access")
197 if tier_access == "locked":
198 self.log.debug(
199 "Skipping %s (access locked)", deviation["deviationid"])
200 continue
201
202 if "premium_folder_data" in deviation:
203 data = self._fetch_premium(deviation)
204 if not data:
205 continue
206 deviation.update(data)
207
208 self.prepare(deviation)
209 yield Message.Directory, "", deviation
210
211 if "content" in deviation:
212 content = self._extract_content(deviation)
213 yield self.commit(deviation, content)
214
215 elif self.original and deviation["is_downloadable"]:
216 content = self.api.deviation_download(deviation)
217 deviation["is_original"] = True
218 yield self.commit(deviation, content)
219
220 if "videos" in deviation and deviation["videos"]:
221 video = max(deviation["videos"],
222 key=lambda x: text.parse_int(x["quality"][:-1]))
223 deviation["is_original"] = False
224 yield self.commit(deviation, video)
225
226 if "flash" in deviation:
227 deviation["is_original"] = True
228 yield self.commit(deviation, deviation["flash"])
229
230 if self.commit_journal:
231 if journal := self._extract_journal(deviation):
232 if self.extra:
233 deviation["_journal"] = journal["html"]
234 deviation["is_original"] = True
235 yield self.commit_journal(deviation, journal)
236
237 if self.comments_avatars:
238 for comment in deviation["comments"]:
239 user = comment["user"]
240 name = user["username"].lower()
241 if user["usericon"] == DEFAULT_AVATAR:
242 self.log.debug(
243 "Skipping avatar of '%s' (default)", name)
244 continue
245 self.cache_update(
246 self._user_details, name, user, _mem=True)
247
248 url = f"{self.root}/{name}/avatar/"
249 comment["_extractor"] = DeviantartAvatarExtractor
250 yield Message.Queue, url, comment
251
252 if self.previews and "preview" in deviation:
253 preview = deviation["preview"]
254 deviation["is_preview"] = True
255 if self.previews_images:
256 yield self.commit(deviation, preview)
257 else:
258 mtype = mimetypes.guess_type(
259 "a." + (deviation.get("extension") or ""), False)[0]
260 if mtype and not mtype.startswith("image/"):
261 yield self.commit(deviation, preview)
262 del deviation["is_preview"]
263
264 if not self.extra:
265 continue
266
267 # ref: https://www.deviantart.com
268 # /developers/http/v1/20210526/object/editor_text
269 # the value of "features" is a JSON string with forward
270 # slashes escaped
271 text_content = \
272 deviation["text_content"]["body"]["features"].replace(
273 "\\/", "/") if "text_content" in deviation else None
274 for txt in (text_content, deviation.get("description"),
275 deviation.get("_journal")):
276 if txt is None:
277 continue
278 for match in DeviantartStashExtractor.pattern.finditer(txt):
279 url = text.ensure_http_scheme(match[0])
280 deviation["_extractor"] = DeviantartStashExtractor
281 yield Message.Queue, url, deviation
282
283 def deviations(self):
284 """Return an iterable containing all relevant Deviation-objects"""
285
286 def prepare(self, deviation):
287 """Adjust the contents of a Deviation-object"""
288 if "index" not in deviation:
289 try:
290 if deviation["url"].startswith((
291 "https://www.deviantart.com/stash/", "https://sta.sh",
292 )):
293 filename = deviation["content"]["src"].split("/")[5]
294 deviation["index_base36"] = filename.partition("-")[0][1:]
295 deviation["index"] = util.b36decode(
296 deviation["index_base36"])
297 else:
298 deviation["index"] = text.parse_int(
299 deviation["url"].rpartition("-")[2])
300 except KeyError:
301 deviation["index"] = 0
302 deviation["index_base36"] = "0"
303 if "index_base36" not in deviation:
304 deviation["index_base36"] = util.b36encode(deviation["index"])
305
306 if self.user:
307 deviation["username"] = self.user
308 deviation["_username"] = self.user.lower()
309 else:
310 deviation["username"] = deviation["author"]["username"]
311 deviation["_username"] = deviation["username"].lower()
312
313 deviation["published_time"] = text.parse_int(
314 deviation["published_time"])
315 deviation["date"] = self.parse_timestamp(
316 deviation["published_time"])
317
318 if self.comments:
319 deviation["comments"] = (
320 self._extract_comments(deviation["deviationid"], "deviation")
321 if deviation["stats"]["comments"] else ()
322 )
323
324 # filename metadata
325 sub = text.re(r"\W").sub
326 deviation["filename"] = (
327 f"{sub('_', deviation['title'].lower())}_by_"
328 f"{sub('_', deviation['author']['username'].lower())}_d"
329 f"{deviation['index_base36']}")
330
331 def commit(self, deviation, target):
332 url = target["src"]
333 name = target.get("filename") or url
334 target = target.copy()
335 target["filename"] = deviation["filename"]
336 deviation["target"] = target
337 deviation["extension"] = target["extension"] = text.ext_from_url(name)
338 if "is_original" not in deviation:
339 deviation["is_original"] = ("/v1/" not in url)
340 return Message.Url, url, deviation
341
342 def _commit_journal_html(self, deviation, journal):
343 title = text.escape(deviation["title"])
344 url = deviation["url"]
345 thumbs = deviation.get("thumbs") or deviation.get("files")
346 html = journal["html"]
347 tmpl = self.utils("journal")
348 shadow = tmpl.SHADOW.format_map(thumbs[0]) if thumbs else ""
349
350 if not html:
351 self.log.warning("%s: Empty journal content", deviation["index"])
352
353 if "css" in journal:
354 css, cls = journal["css"], "withskin"
355 elif html.startswith("<style"):
356 css, _, html = html.partition("</style>")
357 css = css.partition(">")[2]
358 cls = "withskin"
359 else:
360 css, cls = "", "journal-green"
361
362 if html.find('<div class="boxtop journaltop">', 0, 250) != -1:
363 needle = '<div class="boxtop journaltop">'
364 header = tmpl.HEADER_CUSTOM.format(
365 title=title, url=url, date=deviation["date"],
366 )
367 else:
368 needle = '<div usr class="gr">'
369 username = deviation["author"]["username"]
370 urlname = deviation.get("username") or username.lower()
371 header = tmpl.HEADER.format(
372 title=title,
373 url=url,
374 userurl=f"{self.root}/{urlname}/",
375 username=username,
376 date=deviation["date"],
377 )
378
379 if needle in html:
380 html = html.replace(needle, header, 1)
381 else:
382 html = tmpl.HTML_EXTRA.format(header, html)
383
384 html = tmpl.HTML.format(
385 title=title, html=html, shadow=shadow, css=css, cls=cls)
386
387 deviation["extension"] = "htm"
388 return Message.Url, html, deviation
389
390 def _commit_journal_text(self, deviation, journal):
391 html = journal["html"]
392 if not html:
393 self.log.warning("%s: Empty journal content", deviation["index"])
394 elif html.startswith("<style"):
395 html = html.partition("</style>")[2]
396 head, _, tail = html.rpartition("<script")
397 content = "\n".join(
398 text.unescape(text.remove_html(txt))
399 for txt in (head or tail).split("<br />")
400 )
401 txt = self.utils("journal").TEXT.format(
402 title=deviation["title"],
403 username=deviation["author"]["username"],
404 date=deviation["date"],
405 content=content,
406 )
407
408 deviation["extension"] = "txt"
409 return Message.Url, txt, deviation
410
411 def _extract_journal(self, deviation):
412 if "excerpt" in deviation:
413 # # empty 'html'
414 # return self.api.deviation_content(deviation["deviationid"])
415
416 if "_page" in deviation:
417 page = deviation["_page"]
418 del deviation["_page"]
419 else:
420 page = self._limited_request(deviation["url"]).text
421
422 # extract journal html from webpage
423 html = text.extr(
424 page,
425 "<h2>Literature Text</h2></span><div>",
426 "</div></section></div></div>")
427 if html:
428 return {"html": html}
429
430 self.log.debug("%s: Failed to extract journal HTML from webpage. "
431 "Falling back to __INITIAL_STATE__ markup.",
432 deviation["index"])
433
434 # parse __INITIAL_STATE__ as fallback
435 state = util.json_loads(text.extr(
436 page, 'window.__INITIAL_STATE__ = JSON.parse("', '");\n')
437 .replace("\\\\", "\\").replace("\\'", "'").replace('\\"', '"'))
438 deviations = state["@@entities"]["deviation"]
439 content = deviations.popitem()[1]["textContent"]
440
441 if html := self._textcontent_to_html(deviation, content):
442 return {"html": html}
443 return {"html": content["excerpt"].replace("\n", "<br />")}
444
445 if "body" in deviation:
446 return {"html": deviation.pop("body")}
447 return None
448
449 def _textcontent_to_html(self, deviation, content):
450 html = content["html"]
451 markup = html.get("markup")
452
453 if not markup or markup[0] != "{":
454 return markup
455
456 if html["type"] == "tiptap":
457 try:
458 return self.utils("tiptap").to_html(markup)
459 except Exception as exc:
460 self.log.traceback(exc)
461 self.log.error("%s: '%s: %s'", deviation["index"],
462 exc.__class__.__name__, exc)
463
464 self.log.warning("%s: Unsupported '%s' markup.",
465 deviation["index"], html["type"])
466
467 def _extract_content(self, deviation):
468 content = deviation["content"]
469
470 if self.original and deviation["is_downloadable"]:
471 self._update_content(deviation, content)
472 return content
473
474 if self.jwt:
475 self._update_token(deviation, content)
476 return content
477
478 if content["src"].startswith("https://images-wixmp-"):
479 if self.intermediary and deviation["index"] <= 790677560:
480 # https://github.com/r888888888/danbooru/issues/4069
481 intermediary, count = self.intermediary_subn(
482 r"/intermediary\1", content["src"], 1)
483 if count:
484 deviation["is_original"] = False
485 deviation["_fallback"] = (content["src"],)
486 content["src"] = intermediary
487 if self.quality:
488 content["src"] = self.quality_sub(
489 self.quality, content["src"], 1)
490 content["src"] = self.blur_sub("", content["src"], 1)
491
492 return content
493
494 def _find_folder(self, folders, name, uuid):
495 if uuid.isdecimal():
496 match = text.re(
497 "(?i)" + name.replace("-", "[^a-z0-9]+") + "$").match
498 for folder in folders:
499 if match(folder["name"]):
500 return folder
501 elif folder.get("has_subfolders"):
502 for subfolder in folder["subfolders"]:
503 if match(subfolder["name"]):
504 return subfolder
505 else:
506 for folder in folders:
507 if folder["folderid"] == uuid:
508 return folder
509 elif folder.get("has_subfolders"):
510 for subfolder in folder["subfolders"]:
511 if subfolder["folderid"] == uuid:
512 return subfolder
513 raise self.exc.NotFoundError("folder")
514
515 def _folder_urls(self, folders, category, extractor):
516 base = f"{self.root}/{self.user}/{category}/"
517 for folder in folders:
518 folder["_extractor"] = extractor
519 url = f"{base}{folder['folderid']}/{folder['name']}"
520 yield url, folder
521
522 def _update_content_default(self, deviation, content):
523 if "premium_folder_data" in deviation or \
524 "tier_access" in deviation or \
525 deviation.get("is_mature"):
526 public = False
527 else:
528 public = None
529
530 data = self.api.deviation_download(deviation, public)
531 content.update(data)
532 deviation["is_original"] = True
533
534 def _update_content_image(self, deviation, content):
535 data = self.api.deviation_download(deviation)
536 url = data["src"].partition("?")[0]
537 mtype = mimetypes.guess_type(url, False)[0]
538 if mtype and mtype.startswith("image/"):
539 content.update(data)
540 deviation["is_original"] = True
541
542 def _update_token(self, deviation, content):
543 """Replace JWT to be able to remove width/height limits
544
545 All credit goes to @Ironchest337
546 for discovering and implementing this method
547 """
548 url, sep, _ = content["src"].partition("/v1/")
549 if not sep:
550 return
551
552 # 'images-wixmp' returns 401 errors, but just 'wixmp' still works
553 url = url.replace("//images-wixmp", "//wixmp", 1)
554
555 # header = b'{"typ":"JWT","alg":"none"}'
556 payload = (
557 b'{"sub":"urn:app:","iss":"urn:app:","obj":[[{"path":"/f/' +
558 url.partition("/f/")[2].encode() +
559 b'"}]],"aud":["urn:service:file.download"]}'
560 )
561
562 deviation["_fallback"] = (content["src"],)
563 deviation["is_original"] = True
564 pl = util.b64encode(payload)
565 content["src"] = (
566 # base64 of 'header' is precomputed as 'eyJ0eX...'
567 f"{url}?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.{pl}.")
568
569 def _extract_comments(self, target_id, target_type="deviation"):
570 results = None
571 comment_ids = [None]
572
573 while comment_ids:
574 comments = self.api.comments(
575 target_id, target_type, comment_ids.pop())
576
577 if results:
578 results.extend(comments)
579 else:
580 results = comments
581
582 # parent comments, i.e. nodes with at least one child
583 parents = {c["parentid"] for c in comments}
584 # comments with more than one reply
585 replies = {c["commentid"] for c in comments if c["replies"]}
586 # add comment UUIDs with replies that are not parent to any node
587 comment_ids.extend(replies - parents)
588
589 return results
590
591 def _limited_request(self, url, **kwargs):
592 """Limits HTTP requests to one every 2 seconds"""
593 diff = time.time() - DeviantartExtractor._last_request
594 if diff < 2.0:
595 self.sleep(2.0 - diff, "request")
596 response = self.request(url, **kwargs)
597 DeviantartExtractor._last_request = time.time()
598 return response
599
600 def _fetch_premium(self, deviation):
601 try:
602 return self._premium_cache[deviation["deviationid"]]
603 except KeyError:
604 pass
605
606 if not self.api.refresh_token_key:
607 self.log.warning(
608 "Unable to access premium content (no refresh-token)")
609 self._fetch_premium = lambda _: None
610 return None
611
612 dev = self.api.deviation(deviation["deviationid"], False)
613 folder = deviation["premium_folder_data"]
614 username = dev["author"]["username"]
615
616 # premium_folder_data is no longer present when user has access (#5063)
617 has_access = ("premium_folder_data" not in dev) or folder["has_access"]
618
619 if not has_access and folder["type"] == "watchers" and \
620 self.config("auto-watch"):
621 if self.unwatch is not None:
622 self.unwatch.append(username)
623 if self.api.user_friends_watch(username):
624 has_access = True
625 self.log.info(
626 "Watching %s for premium folder access", username)
627 else:
628 self.log.warning(
629 "Error when trying to watch %s. "
630 "Try again with a new refresh-token", username)
631
632 if has_access:
633 self.log.info("Fetching premium folder data")
634 else:
635 self.log.warning("Unable to access premium content (type: %s)",
636 folder["type"])
637
638 cache = self._premium_cache
639 for dev in self.api.gallery(
640 username, folder["gallery_id"], public=False):
641 cache[dev["deviationid"]] = dev if has_access else None
642
643 return cache.get(deviation["deviationid"])
644
645 def _unwatch_premium(self, _=None):
646 for username in self.unwatch:
647 self.log.info("Unwatching %s", username)
648 self.api.user_friends_unwatch(username)
649
650 def _eclipse_to_oauth(self, eclipse_api, deviations):
651 for obj in deviations:
652 deviation = obj["deviation"] if "deviation" in obj else obj
653 deviation_uuid = eclipse_api.deviation_extended_fetch(
654 deviation["deviationId"],
655 deviation["author"]["username"],
656 "journal" if deviation["isJournal"] else "art",
657 )["deviation"]["extended"]["deviationUuid"]
658 yield self.api.deviation(deviation_uuid)
659
660 def _unescape_json(self, json):
661 return json.replace('\\"', '"') \
662 .replace("\\'", "'") \
663 .replace("\\\\", "\\")
664
665 def _user_details(self, name):
666 try:
667 return self.cache(self.api.user_profile, name)["user"]
668 except Exception:
669 return None
670
671
672 class DeviantartUserExtractor(Dispatch, DeviantartExtractor):
673 """Extractor for an artist's user profile"""
674 pattern = BASE_PATTERN + r"/?$"
675 example = "https://www.deviantart.com/USER"
676
677 def items(self):
678 base = f"{self.root}/{self.user}/"
679 return self._dispatch_extractors((
680 (DeviantartAvatarExtractor , base + "avatar"),
681 (DeviantartBackgroundExtractor, base + "banner"),
682 (DeviantartGalleryExtractor , base + "gallery"),
683 (DeviantartScrapsExtractor , base + "gallery/scraps"),
684 (DeviantartJournalExtractor , base + "posts"),
685 (DeviantartStatusExtractor , base + "posts/statuses"),
686 (DeviantartFavoriteExtractor , base + "favourites"),
687 ), ("gallery",))
688
689
690 ###############################################################################
691 # OAuth #######################################################################
692
693 class DeviantartGalleryExtractor(DeviantartExtractor):
694 """Extractor for all deviations from an artist's gallery"""
695 subcategory = "gallery"
696 archive_fmt = "g_{_username}_{index}.{extension}"
697 pattern = (BASE_PATTERN + r"/gallery"
698 r"(?:/all|/recommended-for-you)?"
699 r"/?(\?(?!q=|catpath=scraps).*)?$")
700 example = "https://www.deviantart.com/USER/gallery/"
701
702 def deviations(self):
703 if self.flat and not self.group:
704 return self.api.gallery_all(self.user, self.offset)
705 folders = self.cache(self.api.gallery_folders, self.user)
706 return self._folder_urls(folders, "gallery", DeviantartFolderExtractor)
707
708
709 class DeviantartAvatarExtractor(DeviantartExtractor):
710 """Extractor for an artist's avatar"""
711 subcategory = "avatar"
712 archive_fmt = "a_{_username}_{index}"
713 pattern = BASE_PATTERN + r"/avatar"
714 example = "https://www.deviantart.com/USER/avatar/"
715
716 def deviations(self):
717 name = self.user.lower()
718 user = self.cache(self._user_details, name)
719 if not user:
720 return ()
721
722 icon = user["usericon"]
723 if icon == DEFAULT_AVATAR:
724 self.log.debug("Skipping avatar of '%s' (default)", name)
725 return ()
726
727 _, sep, index = icon.rpartition("?")
728 if not sep:
729 index = "0"
730
731 formats = self.config("formats")
732 if not formats:
733 url = icon.replace("/avatars/", "/avatars-big/", 1)
734 return (self._make_deviation(url, user, index, ""),)
735
736 if isinstance(formats, str):
737 formats = formats.replace(" ", "").split(",")
738
739 results = []
740 for fmt in formats:
741 fmt, _, ext = fmt.rpartition(".")
742 if fmt:
743 fmt = "-" + fmt
744 url = (f"https://a.deviantart.net/avatars{fmt}"
745 f"/{name[0]}/{name[1]}/{name}.{ext}?{index}")
746 results.append(self._make_deviation(url, user, index, fmt))
747 return results
748
749 def _make_deviation(self, url, user, index, fmt):
750 return {
751 "author" : user,
752 "da_category" : "avatar",
753 "index" : text.parse_int(index),
754 "is_deleted" : False,
755 "is_downloadable": False,
756 "published_time" : 0,
757 "title" : "avatar" + fmt,
758 "stats" : {"comments": 0},
759 "content" : {"src": url},
760 }
761
762
763 class DeviantartBackgroundExtractor(DeviantartExtractor):
764 """Extractor for an artist's banner"""
765 subcategory = "background"
766 archive_fmt = "b_{index}"
767 pattern = BASE_PATTERN + r"/ba(?:nner|ckground)"
768 example = "https://www.deviantart.com/USER/banner/"
769
770 def deviations(self):
771 try:
772 return (self.cache(self.api.user_profile, self.user.lower())
773 ["cover_deviation"]["cover_deviation"],)
774 except Exception:
775 return ()
776
777
778 class DeviantartFolderExtractor(DeviantartExtractor):
779 """Extractor for deviations inside an artist's gallery folder"""
780 subcategory = "folder"
781 directory_fmt = ("{category}", "{username}", "{folder[title]}")
782 archive_fmt = "F_{folder[uuid]}_{index}.{extension}"
783 pattern = BASE_PATTERN + r"/gallery/([^/?#]+)/([^/?#]+)"
784 example = "https://www.deviantart.com/USER/gallery/12345/TITLE"
785
786 def __init__(self, match):
787 DeviantartExtractor.__init__(self, match)
788 self.folder = None
789 self.folder_id = match[3]
790 self.folder_name = match[4]
791
792 def deviations(self):
793 folders = self.cache(self.api.gallery_folders, self.user)
794 folder = self._find_folder(folders, self.folder_name, self.folder_id)
795
796 # Leaving this here for backwards compatibility
797 self.folder = {
798 "title": folder["name"],
799 "uuid" : folder["folderid"],
800 "index": self.folder_id,
801 "owner": self.user,
802 "parent_uuid": folder["parent"],
803 }
804
805 if folder.get("subfolder"):
806 self.folder["parent_folder"] = folder["parent_folder"]
807 self.archive_fmt = "F_{folder[parent_uuid]}_{index}.{extension}"
808
809 if self.flat:
810 self.directory_fmt = ("{category}", "{username}",
811 "{folder[parent_folder]}")
812 else:
813 self.directory_fmt = ("{category}", "{username}",
814 "{folder[parent_folder]}",
815 "{folder[title]}")
816
817 if folder.get("has_subfolders") and self.config("subfolders", True):
818 for subfolder in folder["subfolders"]:
819 subfolder["parent_folder"] = folder["name"]
820 subfolder["subfolder"] = True
821 yield from self._folder_urls(
822 folder["subfolders"], "gallery", DeviantartFolderExtractor)
823
824 yield from self.api.gallery(self.user, folder["folderid"], self.offset)
825
826 def prepare(self, deviation):
827 DeviantartExtractor.prepare(self, deviation)
828 deviation["folder"] = self.folder
829
830
831 class DeviantartStashExtractor(DeviantartExtractor):
832 """Extractor for sta.sh-ed deviations"""
833 subcategory = "stash"
834 archive_fmt = "{index}.{extension}"
835 skip_files = None
836 pattern = (r"(?:https?://)?(?:(?:www\.)?deviantart\.com/stash|sta\.s(h))"
837 r"/([a-z0-9]+)")
838 example = "https://www.deviantart.com/stash/abcde"
839
840 def __init__(self, match):
841 DeviantartExtractor.__init__(self, match)
842 self.user = ""
843
844 def deviations(self, stash_id=None, stash_data=None):
845 if stash_id is None:
846 legacy_url, stash_id = self.groups
847 else:
848 legacy_url = False
849
850 if legacy_url and stash_id[0] == "2":
851 url = "https://sta.sh/" + stash_id
852 response = self._limited_request(url)
853 stash_id = response.url.rpartition("/")[2]
854 page = response.text
855 else:
856 url = "https://www.deviantart.com/stash/" + stash_id
857 page = self._limited_request(url).text
858
859 if stash_id[0] == "0":
860 if uuid := text.extr(page, '//deviation/', '"'):
861 deviation = self.api.deviation(uuid)
862 deviation["_page"] = page
863 deviation["index"] = text.parse_int(text.extr(
864 page, '\\"deviationId\\":', ','))
865
866 deviation["stash_id"] = stash_id
867 if stash_data:
868 folder = stash_data["folder"]
869 deviation["stash_name"] = folder["name"]
870 deviation["stash_folder"] = folder["folderId"]
871 deviation["stash_parent"] = folder["parentId"] or 0
872 deviation["stash_description"] = \
873 folder["richDescription"]["excerpt"]
874 else:
875 deviation["stash_name"] = ""
876 deviation["stash_description"] = ""
877 deviation["stash_folder"] = 0
878 deviation["stash_parent"] = 0
879
880 yield deviation
881 return
882
883 if stash_data := text.extr(page, ',\\"stash\\":', ',\\"@@'):
884 if stash_data.endswith(":{}"):
885 stash_data = stash_data[:stash_data.rfind("}", None, -2)+1]
886 stash_data = util.json_loads(self._unescape_json(stash_data))
887
888 for sid in text.extract_iter(
889 page, 'href="https://www.deviantart.com/stash/', '"'):
890 if sid == stash_id or sid.endswith("#comments"):
891 continue
892 yield from self.deviations(sid, stash_data)
893
894
895 class DeviantartFavoriteExtractor(DeviantartExtractor):
896 """Extractor for an artist's favorites"""
897 subcategory = "favorite"
898 directory_fmt = ("{category}", "{username}", "Favourites")
899 archive_fmt = "f_{_username}_{index}.{extension}"
900 pattern = BASE_PATTERN + r"/favourites(?:/all|/?\?catpath=)?/?$"
901 example = "https://www.deviantart.com/USER/favourites/"
902
903 def deviations(self):
904 if self.flat:
905 return self.api.collections_all(self.user, self.offset)
906 folders = self.cache(self.api.collections_folders, self.user)
907 return self._folder_urls(
908 folders, "favourites", DeviantartCollectionExtractor)
909
910
911 class DeviantartCollectionExtractor(DeviantartExtractor):
912 """Extractor for a single favorite collection"""
913 subcategory = "collection"
914 directory_fmt = ("{category}", "{username}", "Favourites",
915 "{collection[title]}")
916 archive_fmt = "C_{collection[uuid]}_{index}.{extension}"
917 pattern = BASE_PATTERN + r"/favourites/([^/?#]+)/([^/?#]+)"
918 example = "https://www.deviantart.com/USER/favourites/12345/TITLE"
919
920 def __init__(self, match):
921 DeviantartExtractor.__init__(self, match)
922 self.collection = None
923 self.collection_id = match[3]
924 self.collection_name = match[4]
925
926 def deviations(self):
927 folders = self.cache(self.api.collections_folders, self.user)
928 folder = self._find_folder(
929 folders, self.collection_name, self.collection_id)
930 self.collection = {
931 "title": folder["name"],
932 "uuid" : folder["folderid"],
933 "index": self.collection_id,
934 "owner": self.user,
935 }
936 return self.api.collections(self.user, folder["folderid"], self.offset)
937
938 def prepare(self, deviation):
939 DeviantartExtractor.prepare(self, deviation)
940 deviation["collection"] = self.collection
941
942
943 class DeviantartJournalExtractor(DeviantartExtractor):
944 """Extractor for an artist's journals"""
945 subcategory = "journal"
946 directory_fmt = ("{category}", "{username}", "Journal")
947 archive_fmt = "j_{_username}_{index}.{extension}"
948 pattern = BASE_PATTERN + r"/(?:posts(?:/journals)?|journal)/?(?:\?.*)?$"
949 example = "https://www.deviantart.com/USER/posts/journals/"
950
951 def deviations(self):
952 return self.api.browse_user_journals(self.user, self.offset)
953
954
955 class DeviantartStatusExtractor(DeviantartExtractor):
956 """Extractor for an artist's status updates"""
957 subcategory = "status"
958 directory_fmt = ("{category}", "{username}", "Status")
959 filename_fmt = "{category}_{index}_{title}_{date}.{extension}"
960 archive_fmt = "S_{_username}_{index}.{extension}"
961 pattern = BASE_PATTERN + r"/posts/statuses"
962 example = "https://www.deviantart.com/USER/posts/statuses/"
963
964 def deviations(self):
965 for status in self.api.user_statuses(self.user, self.offset):
966 yield from self.process_status(status)
967
968 def process_status(self, status):
969 for item in status.get("items") or (): # do not trust is_share
970 # shared deviations/statuses
971 if "deviation" in item:
972 yield item["deviation"].copy()
973 if "status" in item:
974 yield from self.process_status(item["status"].copy())
975 # assume is_deleted == true means necessary fields are missing
976 if status["is_deleted"]:
977 self.log.warning(
978 "Skipping status %s (deleted)", status.get("statusid"))
979 return
980 yield status
981
982 def prepare(self, deviation):
983 if "deviationid" in deviation:
984 return DeviantartExtractor.prepare(self, deviation)
985
986 try:
987 path = deviation["url"].split("/")
988 deviation["index"] = text.parse_int(path[-1] or path[-2])
989 except KeyError:
990 deviation["index"] = 0
991
992 if self.user:
993 deviation["username"] = self.user
994 deviation["_username"] = self.user.lower()
995 else:
996 deviation["username"] = deviation["author"]["username"]
997 deviation["_username"] = deviation["username"].lower()
998
999 deviation["date"] = d = self.parse_datetime_iso(deviation["ts"])
1000 deviation["published_time"] = int(dt.to_ts(d))
1001
1002 deviation["da_category"] = "Status"
1003 deviation["category_path"] = "status"
1004 deviation["is_downloadable"] = False
1005 deviation["title"] = "Status Update"
1006
1007 comments_count = deviation.pop("comments_count", 0)
1008 deviation["stats"] = {"comments": comments_count}
1009 if self.comments:
1010 deviation["comments"] = (
1011 self._extract_comments(deviation["statusid"], "status")
1012 if comments_count else ()
1013 )
1014
1015
1016 class DeviantartTagExtractor(DeviantartExtractor):
1017 """Extractor for deviations from tag searches"""
1018 subcategory = "tag"
1019 directory_fmt = ("{category}", "Tags", "{search_tags}")
1020 archive_fmt = "T_{search_tags}_{index}.{extension}"
1021 pattern = r"(?:https?://)?www\.deviantart\.com/tag/([^/?#]+)"
1022 example = "https://www.deviantart.com/tag/TAG"
1023
1024 def __init__(self, match):
1025 DeviantartExtractor.__init__(self, match)
1026 self.tag = text.unquote(match[1])
1027 self.user = ""
1028
1029 def deviations(self):
1030 return self.api.browse_tags(self.tag, self.offset)
1031
1032 def prepare(self, deviation):
1033 DeviantartExtractor.prepare(self, deviation)
1034 deviation["search_tags"] = self.tag
1035
1036
1037 class DeviantartWatchExtractor(DeviantartExtractor):
1038 """Extractor for Deviations from watched users"""
1039 subcategory = "watch"
1040 pattern = (r"(?:https?://)?(?:www\.)?deviantart\.com"
1041 r"/(?:watch/deviations|notifications/watch)()()")
1042 example = "https://www.deviantart.com/watch/deviations"
1043
1044 def deviations(self):
1045 return self.api.browse_deviantsyouwatch()
1046
1047
1048 class DeviantartWatchPostsExtractor(DeviantartExtractor):
1049 """Extractor for Posts from watched users"""
1050 subcategory = "watch-posts"
1051 pattern = r"(?:https?://)?(?:www\.)?deviantart\.com/watch/posts()()"
1052 example = "https://www.deviantart.com/watch/posts"
1053
1054 def deviations(self):
1055 return self.api.browse_posts_deviantsyouwatch()
1056
1057
1058 ###############################################################################
1059 # Eclipse #####################################################################
1060
1061 class DeviantartDeviationExtractor(DeviantartExtractor):
1062 """Extractor for single deviations"""
1063 subcategory = "deviation"
1064 archive_fmt = "g_{_username}_{index}.{extension}"
1065 skip_files = None
1066 pattern = (BASE_PATTERN + r"/(art|journal)/(?:[^/?#]+-)?(\d+)"
1067 r"|(?:https?://)?(?:www\.)?(?:fx)?deviantart\.com/"
1068 r"(?:view/|deviation/|view(?:-full)?\.php/*\?(?:[^#]+&)?id=)"
1069 r"(\d+)" # bare deviation ID without slug
1070 r"|(?:https?://)?fav\.me/d([0-9a-z]+)") # base36
1071 example = "https://www.deviantart.com/UsER/art/TITLE-12345"
1072
1073 def deviations(self):
1074 _, _, type, did1, did2, did3 = self.groups
1075 deviation_id = did1 or did2 or util.b36decode(did3)
1076
1077 if self.user:
1078 url = (f"{self.root}/{self.user}"
1079 f"/{type or 'art'}/{deviation_id}")
1080 else:
1081 url = f"{self.root}/view/{deviation_id}/"
1082
1083 self.login()
1084 page = self._limited_request(url, notfound=True).text
1085 uuid = text.extr(page, '"deviationUuid\\":\\"', '\\')
1086 if not uuid:
1087 raise self.exc.NotFoundError("deviation")
1088
1089 deviation = self.api.deviation(uuid)
1090 deviation["_page"] = page
1091 deviation["index_file"] = 0
1092 deviation["num"] = deviation["count"] = 1
1093
1094 additional_media = text.extr(page, ',\\"additionalMedia\\":', '}],\\"')
1095 if not additional_media:
1096 yield deviation
1097 return
1098
1099 self.filename_fmt = ("{category}_{index}_{index_file}_{title}_"
1100 "{num:>02}.{extension}")
1101 self.archive_fmt = ("g_{_username}_{index}{index_file:?_//}."
1102 "{extension}")
1103
1104 if additional_media := util.json_loads(self._unescape_json(
1105 additional_media) + "}]"):
1106 for post in additional_media:
1107 if post.get("type") == "video":
1108 medias = DeviantartEclipseAPI(
1109 self).deviation_media(deviation_id)
1110 break
1111 else:
1112 medias = {}
1113 deviation["count"] = 1 + len(additional_media)
1114 dev_orig = deviation.copy()
1115 dev_orig.pop("content", None)
1116 dev_orig.pop("videos", None)
1117 dev_orig.pop("flash", None)
1118 else:
1119 deviation["count"] = 1
1120
1121 yield deviation
1122
1123 for index, post in enumerate(additional_media, 2):
1124 dev = dev_orig.copy()
1125 dev["num"] = index
1126 dev["index_file"] = post["fileId"]
1127 dev["is_downloadable"] = False
1128
1129 media = medias.get(post["fileId"]) or post["media"]
1130 if videos := [fmt for fmt in (media.get("types") or ())
1131 if fmt.get("t") == "video"]:
1132 dev["videos"] = [{
1133 "src" : fmt["b"],
1134 "quality" : fmt.get("q") or str(fmt.get("h", 0)) + "p",
1135 "duration": fmt.get("d"),
1136 "filesize": fmt.get("f"),
1137 } for fmt in videos]
1138 else:
1139 dev["content"] = {"src": eclipse_media(
1140 post["media"], "fullview")[0]}
1141 if post.get("type") == "video":
1142 self.log.warning(
1143 "%s: Unable to extract video URL of file %s; falling "
1144 "back to preview image. Provide login credentials or "
1145 "session cookies to be able to access it.",
1146 deviation_id, post.get("filename") or post["fileId"])
1147 yield dev
1148
1149
1150 class DeviantartScrapsExtractor(DeviantartExtractor):
1151 """Extractor for an artist's scraps"""
1152 subcategory = "scraps"
1153 directory_fmt = ("{category}", "{username}", "Scraps")
1154 archive_fmt = "s_{_username}_{index}.{extension}"
1155 pattern = BASE_PATTERN + r"/gallery/(?:\?catpath=)?scraps\b"
1156 example = "https://www.deviantart.com/USER/gallery/scraps"
1157
1158 def deviations(self):
1159 self.login()
1160
1161 eclipse_api = DeviantartEclipseAPI(self)
1162 return self._eclipse_to_oauth(
1163 eclipse_api, eclipse_api.gallery_scraps(self.user, self.offset))
1164
1165
1166 class DeviantartSearchExtractor(DeviantartExtractor):
1167 """Extractor for deviantart search results"""
1168 subcategory = "search"
1169 directory_fmt = ("{category}", "Search", "{search_tags}")
1170 archive_fmt = "Q_{search_tags}_{index}.{extension}"
1171 skip_files = None
1172 pattern = (r"(?:https?://)?www\.deviantart\.com"
1173 r"/search(?:/deviations)?/?\?([^#]+)")
1174 example = "https://www.deviantart.com/search?q=QUERY"
1175
1176 def __init__(self, match):
1177 DeviantartExtractor.__init__(self, match)
1178 self.query = text.parse_query(self.user)
1179 self.search = self.query.get("q", "")
1180 self.user = ""
1181
1182 def deviations(self):
1183 logged_in = self.login()
1184
1185 eclipse_api = DeviantartEclipseAPI(self)
1186 search = (eclipse_api.search_deviations
1187 if logged_in else self._search_html)
1188 return self._eclipse_to_oauth(eclipse_api, search(self.query))
1189
1190 def prepare(self, deviation):
1191 DeviantartExtractor.prepare(self, deviation)
1192 deviation["search_tags"] = self.search
1193
1194 def _search_html(self, params):
1195 url = self.root + "/search"
1196 find = text.re(r'''href="https://www.deviantart.com/([^/?#]+)'''
1197 r'''/(art|journal)/(?:[^"]+-)?(\d+)''').findall
1198 while True:
1199 response = self.request(url, params=params)
1200
1201 if response.history and "/users/login" in response.url:
1202 raise self.exc.AbortExtraction("HTTP redirect to login page")
1203 page = response.text
1204
1205 for user, type, did in find(page)[:-3:3]:
1206 yield {
1207 "deviationId": did,
1208 "author": {"username": user},
1209 "isJournal": type == "journal",
1210 }
1211
1212 cursor = text.extr(page, r'\"cursor\":\"', '\\',)
1213 if not cursor:
1214 return
1215 params["cursor"] = cursor
1216
1217
1218 class DeviantartGallerySearchExtractor(DeviantartExtractor):
1219 """Extractor for deviantart gallery searches"""
1220 subcategory = "gallery-search"
1221 archive_fmt = "g_{_username}_{index}.{extension}"
1222 pattern = BASE_PATTERN + r"/gallery/?\?(q=[^#]+)"
1223 example = "https://www.deviantart.com/USER/gallery?q=QUERY"
1224
1225 def __init__(self, match):
1226 DeviantartExtractor.__init__(self, match)
1227 self.query = match[3]
1228
1229 def deviations(self):
1230 self.login()
1231
1232 eclipse_api = DeviantartEclipseAPI(self)
1233 query = text.parse_query(self.query)
1234 self.search = query["q"]
1235
1236 return self._eclipse_to_oauth(
1237 eclipse_api, eclipse_api.galleries_search(
1238 self.user,
1239 self.search,
1240 self.offset,
1241 query.get("sort", "most-recent"),
1242 ))
1243
1244 def prepare(self, deviation):
1245 DeviantartExtractor.prepare(self, deviation)
1246 deviation["search_tags"] = self.search
1247
1248
1249 class DeviantartFollowingExtractor(DeviantartExtractor):
1250 """Extractor for user's watched users"""
1251 subcategory = "following"
1252 pattern = BASE_PATTERN + "/(?:about#)?watching"
1253 example = "https://www.deviantart.com/USER/about#watching"
1254
1255 def items(self):
1256 api = DeviantartOAuthAPI(self)
1257
1258 for user in api.user_friends(self.user):
1259 url = f"{self.root}/{user['user']['username']}"
1260 user["_extractor"] = DeviantartUserExtractor
1261 yield Message.Queue, url, user
1262
1263
1264 ###############################################################################
1265 # API Interfaces ##############################################################
1266
1267 class DeviantartOAuthAPI():
1268 """Interface for the DeviantArt OAuth API
1269
1270 https://www.deviantart.com/developers/http/v1/20160316
1271 """
1272 CLIENT_ID = "5388"
1273 CLIENT_SECRET = "76b08c69cfb27f26d6161f9ab6d061a1"
1274
1275 def __init__(self, extractor):
1276 self.extractor = extractor
1277 self.log = extractor.log
1278 self.exc = extractor.exc
1279 self.headers = {"dA-minor-version": "20210526"}
1280 self._warn_429 = True
1281
1282 self.delay = extractor.config("wait-min", 0)
1283 self.delay_min = max(2, self.delay)
1284
1285 self.mature = extractor.config("mature", "true")
1286 if not isinstance(self.mature, str):
1287 self.mature = "true" if self.mature else "false"
1288
1289 self.strategy = extractor.config("pagination")
1290 self.folders = extractor.config("folders", False)
1291 self.public = extractor.config("public", True)
1292
1293 if client_id := extractor.config("client-id"):
1294 self.client_id = str(client_id)
1295 self.client_secret = extractor.config("client-secret")
1296 else:
1297 self.client_id = self.CLIENT_ID
1298 self.client_secret = self.CLIENT_SECRET
1299
1300 token = extractor.config("refresh-token")
1301 if token is None or token == "cache":
1302 token = "#" + self.client_id
1303 if not extractor.cache(_refresh_token_cache, token, _mem=False):
1304 token = None
1305 self.refresh_token_key = token
1306
1307 metadata = extractor.config("metadata", False)
1308 if not metadata:
1309 metadata = True if extractor.extra else False
1310 if metadata:
1311 self.metadata = True
1312
1313 if isinstance(metadata, str):
1314 if metadata == "all":
1315 metadata = ("submission", "camera", "stats",
1316 "collection", "gallery")
1317 else:
1318 metadata = metadata.replace(" ", "").split(",")
1319 elif not isinstance(metadata, (list, tuple)):
1320 metadata = ()
1321
1322 self._metadata_params = {"mature_content": self.mature}
1323 self._metadata_public = None
1324 if metadata:
1325 # extended metadata
1326 self.limit = 10
1327 for param in metadata:
1328 self._metadata_params["ext_" + param] = "1"
1329 if "ext_collection" in self._metadata_params or \
1330 "ext_gallery" in self._metadata_params:
1331 if token:
1332 self._metadata_public = False
1333 else:
1334 self.log.error("'collection' and 'gallery' metadata "
1335 "require a refresh token")
1336 else:
1337 # base metadata
1338 self.limit = 50
1339 else:
1340 self.metadata = False
1341 self.limit = None
1342
1343 self.log.debug(
1344 "Using %s API credentials (client-id %s)",
1345 "default" if self.client_id == self.CLIENT_ID else "custom",
1346 self.client_id,
1347 )
1348
1349 def browse_deviantsyouwatch(self, offset=0):
1350 """Yield deviations from users you watch"""
1351 endpoint = "/browse/deviantsyouwatch"
1352 params = {"limit": 50, "offset": offset,
1353 "mature_content": self.mature}
1354 return self._pagination(endpoint, params, public=False)
1355
1356 def browse_posts_deviantsyouwatch(self, offset=0):
1357 """Yield posts from users you watch"""
1358 endpoint = "/browse/posts/deviantsyouwatch"
1359 params = {"limit": 50, "offset": offset,
1360 "mature_content": self.mature}
1361 return self._pagination(endpoint, params, public=False, unpack=True)
1362
1363 def browse_tags(self, tag, offset=0):
1364 """ Browse a tag """
1365 endpoint = "/browse/tags"
1366 params = {
1367 "tag" : tag,
1368 "offset" : offset,
1369 "limit" : 50,
1370 "mature_content": self.mature,
1371 }
1372 return self._pagination(endpoint, params)
1373
1374 def browse_user_journals(self, username, offset=0):
1375 journals = filter(
1376 lambda post: "/journal/" in post["url"],
1377 self.user_profile_posts(username))
1378 if offset:
1379 journals = util.advance(journals, offset)
1380 return journals
1381
1382 def collections(self, username, folder_id, offset=0):
1383 """Yield all Deviation-objects contained in a collection folder"""
1384 endpoint = "/collections/" + folder_id
1385 params = {"username": username, "offset": offset, "limit": 24,
1386 "mature_content": self.mature}
1387 return self._pagination(endpoint, params)
1388
1389 def collections_all(self, username, offset=0):
1390 """Yield all deviations in a user's collection"""
1391 endpoint = "/collections/all"
1392 params = {"username": username, "offset": offset, "limit": 24,
1393 "mature_content": self.mature}
1394 return self._pagination(endpoint, params)
1395
1396 def collections_folders(self, username, offset=0):
1397 """Yield all collection folders of a specific user"""
1398 endpoint = "/collections/folders"
1399 params = {"username": username, "offset": offset, "limit": 50,
1400 "mature_content": self.mature}
1401 return self._pagination_list(endpoint, params)
1402
1403 def comments(self, target_id, target_type="deviation",
1404 comment_id=None, offset=0):
1405 """Fetch comments posted on a target"""
1406 endpoint = f"/comments/{target_type}/{target_id}"
1407 params = {
1408 "commentid" : comment_id,
1409 "maxdepth" : "5",
1410 "offset" : offset,
1411 "limit" : 50,
1412 "mature_content": self.mature,
1413 }
1414 return self._pagination_list(endpoint, params=params, key="thread")
1415
1416 def deviation(self, deviation_id, public=None):
1417 """Query and return info about a single Deviation"""
1418 endpoint = "/deviation/" + deviation_id
1419
1420 deviation = self._call(endpoint, public=public)
1421 if deviation.get("is_mature") and public is None and \
1422 self.refresh_token_key:
1423 deviation = self._call(endpoint, public=False)
1424
1425 if self.metadata:
1426 self._metadata((deviation,))
1427 if self.folders:
1428 self._folders((deviation,))
1429 return deviation
1430
1431 def deviation_content(self, deviation_id, public=None):
1432 """Get extended content of a single Deviation"""
1433 endpoint = "/deviation/content"
1434 params = {"deviationid": deviation_id}
1435 content = self._call(endpoint, params=params, public=public)
1436 if public and content["html"].startswith(
1437 ' <span class=\"username-with-symbol'):
1438 if self.refresh_token_key:
1439 content = self._call(endpoint, params=params, public=False)
1440 else:
1441 self.log.warning("Private Journal")
1442 return content
1443
1444 def deviation_download(self, deviation, public=None):
1445 """Get the original file download (if allowed)"""
1446 endpoint = "/deviation/download/" + deviation["deviationid"]
1447 params = {"mature_content": self.mature}
1448
1449 if public is None:
1450 public = self.public
1451 self.log.info("%s: Requesting download URL with %s token",
1452 deviation["index"], "public" if public else "private")
1453 try:
1454 return self._call(
1455 endpoint, params=params, public=public, log=False)
1456 except self.exc.AuthorizationError as exc:
1457 if isinstance(exc.message, dict):
1458 self.log.error("%s: '%s'", deviation["index"],
1459 exc.message.get("error_description"))
1460 if not public or not self.refresh_token_key:
1461 raise
1462 self.log.info("%s: Retrying with private token",
1463 deviation["index"])
1464 return self._call(endpoint, params=params, public=False)
1465
1466 def deviation_metadata(self, deviations):
1467 """ Fetch deviation metadata for a set of deviations"""
1468 endpoint = "/deviation/metadata?" + "&".join(
1469 f"deviationids[{num}]={deviation['deviationid']}"
1470 for num, deviation in enumerate(deviations)
1471 )
1472 return self._call(
1473 endpoint,
1474 params=self._metadata_params,
1475 public=self._metadata_public,
1476 )["metadata"]
1477
1478 def gallery(self, username, folder_id, offset=0, extend=True, public=None):
1479 """Yield all Deviation-objects contained in a gallery folder"""
1480 endpoint = "/gallery/" + folder_id
1481 params = {"username": username, "offset": offset, "limit": 24,
1482 "mature_content": self.mature, "mode": "newest"}
1483 return self._pagination(endpoint, params, extend, public)
1484
1485 def gallery_all(self, username, offset=0):
1486 """Yield all Deviation-objects of a specific user"""
1487 endpoint = "/gallery/all"
1488 params = {"username": username, "offset": offset, "limit": 24,
1489 "mature_content": self.mature}
1490 return self._pagination(endpoint, params)
1491
1492 def gallery_folders(self, username, offset=0):
1493 """Yield all gallery folders of a specific user"""
1494 endpoint = "/gallery/folders"
1495 params = {"username": username, "offset": offset, "limit": 50,
1496 "mature_content": self.mature}
1497 return self._pagination_list(endpoint, params)
1498
1499 def user_friends(self, username, offset=0):
1500 """Get the users list of friends"""
1501 endpoint = "/user/friends/" + username
1502 params = {"limit": 50, "offset": offset, "mature_content": self.mature}
1503 return self._pagination(endpoint, params)
1504
1505 def user_friends_watch(self, username):
1506 """Watch a user"""
1507 endpoint = "/user/friends/watch/" + username
1508 data = {
1509 "watch[friend]" : "0",
1510 "watch[deviations]" : "0",
1511 "watch[journals]" : "0",
1512 "watch[forum_threads]": "0",
1513 "watch[critiques]" : "0",
1514 "watch[scraps]" : "0",
1515 "watch[activity]" : "0",
1516 "watch[collections]" : "0",
1517 "mature_content" : self.mature,
1518 }
1519 return self._call(
1520 endpoint, method="POST", data=data, public=False, fatal=False,
1521 ).get("success")
1522
1523 def user_friends_unwatch(self, username):
1524 """Unwatch a user"""
1525 endpoint = "/user/friends/unwatch/" + username
1526 return self._call(
1527 endpoint, method="POST", public=False, fatal=False,
1528 ).get("success")
1529
1530 def user_profile(self, username):
1531 """Get user profile information"""
1532 endpoint = "/user/profile/" + username
1533 return self._call(endpoint, fatal=False)
1534
1535 def user_profile_posts(self, username):
1536 endpoint = "/user/profile/posts"
1537 params = {"username": username, "limit": 50,
1538 "mature_content": self.mature}
1539 return self._pagination(endpoint, params)
1540
1541 def user_statuses(self, username, offset=0):
1542 """Yield status updates of a specific user"""
1543 statuses = filter(
1544 lambda post: "/status-update/" in post["url"],
1545 self.user_profile_posts(username))
1546 if offset:
1547 statuses = util.advance(statuses, offset)
1548 return statuses
1549
1550 def authenticate(self, refresh_token_key):
1551 """Authenticate the application by requesting an access token"""
1552 self.headers["Authorization"] = self.extractor.cache(
1553 self._authenticate_impl, refresh_token_key, _exp=3600, _mem=False)
1554
1555 def _authenticate_impl(self, refresh_token_key):
1556 """Actual authenticate implementation"""
1557 url = "https://www.deviantart.com/oauth2/token"
1558 if refresh_token_key:
1559 self.log.info("Refreshing private access token")
1560 token = self.extractor.cache(
1561 _refresh_token_cache, refresh_token_key, _mem=False)
1562 data = {"grant_type": "refresh_token",
1563 "refresh_token": token}
1564 else:
1565 self.log.info("Requesting public access token")
1566 data = {"grant_type": "client_credentials"}
1567
1568 auth = util.HTTPBasicAuth(self.client_id, self.client_secret)
1569 response = self.extractor.request(
1570 url, method="POST", data=data, auth=auth, fatal=False)
1571 data = response.json()
1572
1573 if response.status_code != 200:
1574 self.log.debug("Server response: %s", data)
1575 raise self.exc.AuthenticationError(
1576 f"\"{data.get('error_description')}\" ({data.get('error')})")
1577 if refresh_token_key:
1578 self.extractor.cache_update(
1579 _refresh_token_cache, refresh_token_key, data["refresh_token"])
1580 return "Bearer " + data["access_token"]
1581
1582 def _call(self, endpoint, fatal=True, log=True, public=None, **kwargs):
1583 """Call an API endpoint"""
1584 url = "https://www.deviantart.com/api/v1/oauth2" + endpoint
1585 kwargs["fatal"] = None
1586
1587 if public is None:
1588 public = self.public
1589
1590 while True:
1591 if self.delay:
1592 self.extractor.sleep(self.delay, "api")
1593
1594 self.authenticate(None if public else self.refresh_token_key)
1595 kwargs["headers"] = self.headers
1596 response = self.extractor.request(url, **kwargs)
1597
1598 try:
1599 data = response.json()
1600 except ValueError:
1601 self.log.error("Unable to parse API response")
1602 data = {}
1603
1604 status = response.status_code
1605 if 200 <= status < 400:
1606 if self.delay > self.delay_min:
1607 self.delay -= 1
1608 return data
1609 if not fatal and status != 429:
1610 return None
1611
1612 error = data.get("error_description")
1613 if error == "User not found.":
1614 raise self.exc.NotFoundError("user or group")
1615 if error in {"Deviation not downloadable.",
1616 "Only subscribers may have access to this download."}:
1617 raise self.exc.AuthRequired()
1618 if error == "Free download limit reached.":
1619 raise self.exc.AuthorizationError(data)
1620
1621 self.log.debug(response.text)
1622 msg = f"API responded with {status} {response.reason}"
1623 if status == 429:
1624 if self.delay < 30:
1625 self.delay += 1
1626 self.log.warning("%s. Using %ds delay.", msg, self.delay)
1627
1628 if self._warn_429 and self.delay >= 3:
1629 self._warn_429 = False
1630 if self.client_id == self.CLIENT_ID:
1631 self.log.info(
1632 "Register your own OAuth application and use its "
1633 "credentials to prevent this error: "
1634 "https://gdl-org.github.io/docs/configuration.html"
1635 "#extractor-deviantart-client-id-client-secret")
1636 else:
1637 if log:
1638 self.log.error(msg)
1639 return data
1640
1641 def _should_switch_tokens(self, results, params):
1642 if len(results) < params["limit"]:
1643 return True
1644
1645 if not self.extractor.jwt:
1646 for item in results:
1647 if item.get("is_mature"):
1648 return True
1649
1650 return False
1651
1652 def _pagination(self, endpoint, params,
1653 extend=True, public=None, unpack=False, key="results"):
1654 warn = True
1655 if public is None:
1656 public = self.public
1657
1658 if self.limit and params["limit"] > self.limit:
1659 params["limit"] = (params["limit"] // self.limit) * self.limit
1660
1661 while True:
1662 data = self._call(endpoint, params=params, public=public)
1663 try:
1664 results = data[key]
1665 except KeyError:
1666 self.log.error("Unexpected API response: %s", data)
1667 return
1668
1669 if unpack:
1670 results = [item["journal"] for item in results
1671 if "journal" in item]
1672 if extend:
1673 if public and self._should_switch_tokens(results, params):
1674 if self.refresh_token_key:
1675 self.log.debug("Switching to private access token")
1676 public = False
1677 continue
1678 elif data["has_more"] and warn:
1679 warn = False
1680 self.log.warning(
1681 "Private or mature deviations detected! "
1682 "Run 'gallery-dl oauth:deviantart' and follow the "
1683 "instructions to be able to access them.")
1684
1685 # "statusid" cannot be used instead
1686 if results and "deviationid" in results[0]:
1687 if self.metadata:
1688 self._metadata(results)
1689 if self.folders:
1690 self._folders(results)
1691 else: # attempt to fix "deleted" deviations
1692 for dev in self._shared_content(results):
1693 if not dev["is_deleted"]:
1694 continue
1695 patch = self._call(
1696 "/deviation/" + dev["deviationid"], fatal=False)
1697 if patch:
1698 dev.update(patch)
1699
1700 yield from results
1701
1702 if not data["has_more"] and (
1703 self.strategy != "manual" or not results or not extend):
1704 return
1705
1706 if "next_cursor" in data:
1707 if not data["next_cursor"]:
1708 return
1709 params["offset"] = None
1710 params["cursor"] = data["next_cursor"]
1711 elif data["next_offset"] is not None:
1712 params["offset"] = data["next_offset"]
1713 params["cursor"] = None
1714 else:
1715 if params.get("offset") is None:
1716 return
1717 params["offset"] = int(params["offset"]) + len(results)
1718
1719 def _pagination_list(self, endpoint, params, key="results"):
1720 return list(self._pagination(endpoint, params, False, key=key))
1721
1722 def _shared_content(self, results):
1723 """Return an iterable of shared deviations in 'results'"""
1724 for result in results:
1725 for item in result.get("items") or ():
1726 if "deviation" in item:
1727 yield item["deviation"]
1728
1729 def _metadata(self, deviations):
1730 """Add extended metadata to each deviation object"""
1731 if len(deviations) <= self.limit:
1732 self._metadata_batch(deviations)
1733 else:
1734 n = self.limit
1735 for index in range(0, len(deviations), n):
1736 self._metadata_batch(deviations[index:index+n])
1737
1738 def _metadata_batch(self, deviations):
1739 """Fetch extended metadata for a single batch of deviations"""
1740 for deviation, metadata in zip(
1741 deviations, self.deviation_metadata(deviations)):
1742 deviation.update(metadata)
1743 deviation["tags"] = [t["tag_name"] for t in deviation["tags"]]
1744
1745 def _folders(self, deviations):
1746 """Add a list of all containing folders to each deviation object"""
1747 for deviation in deviations:
1748 username = deviation["author"]["username"]
1749 deviation["folders"] = self.extractor.cache(
1750 self._folders_map, username)[deviation["deviationid"]]
1751
1752 def _folders_map(self, username):
1753 """Generate a deviation_id -> folders mapping for 'username'"""
1754 self.log.info("Collecting folder information for '%s'", username)
1755 folders = self.extractor.cache(self.gallery_folders, username)
1756
1757 # create 'folderid'-to-'folder' mapping
1758 fmap = {
1759 folder["folderid"]: folder
1760 for folder in folders
1761 }
1762
1763 # add parent names to folders, but ignore "Featured" as parent
1764 featured = folders[0]["folderid"]
1765 done = False
1766
1767 while not done:
1768 done = True
1769 for folder in folders:
1770 parent = folder["parent"]
1771 if not parent:
1772 pass
1773 elif parent == featured:
1774 folder["parent"] = None
1775 else:
1776 parent = fmap[parent]
1777 if parent["parent"]:
1778 done = False
1779 else:
1780 folder["name"] = parent["name"] + "/" + folder["name"]
1781 folder["parent"] = None
1782
1783 # map deviationids to folder names
1784 dmap = collections.defaultdict(list)
1785 for folder in folders:
1786 for deviation in self.gallery(
1787 username, folder["folderid"], 0, False):
1788 dmap[deviation["deviationid"]].append(folder["name"])
1789 return dmap
1790
1791
1792 class DeviantartEclipseAPI():
1793 """Interface to the DeviantArt Eclipse API"""
1794
1795 def __init__(self, extractor):
1796 self.extractor = extractor
1797 self.log = extractor.log
1798 self.request = self.extractor._limited_request
1799 self.csrf_token = None
1800
1801 def deviation_extended_fetch(self, deviation_id, user, kind=None):
1802 endpoint = "/_puppy/dadeviation/init"
1803 params = {
1804 "deviationid" : deviation_id,
1805 "username" : user,
1806 "type" : kind,
1807 "include_session" : "false",
1808 "expand" : "deviation.related",
1809 "da_minor_version": "20230710",
1810 }
1811 return self._call(endpoint, params)
1812
1813 def deviation_media(self, deviation_id):
1814 endpoint = "/_puppy/dadeviation/media"
1815 params = {"deviationid": deviation_id}
1816 return self._call(endpoint, params)
1817
1818 def gallery_scraps(self, user, offset=0):
1819 endpoint = "/_puppy/dashared/gallection/contents"
1820 params = {
1821 "username" : user,
1822 "type" : "gallery",
1823 "offset" : offset,
1824 "limit" : 24,
1825 "scraps_folder": "true",
1826 }
1827 return self._pagination(endpoint, params)
1828
1829 def galleries_search(self, user, query, offset=0, order="most-recent"):
1830 endpoint = "/_puppy/dashared/gallection/search"
1831 params = {
1832 "username": user,
1833 "type" : "gallery",
1834 "order" : order,
1835 "q" : query,
1836 "offset" : offset,
1837 "limit" : 24,
1838 }
1839 return self._pagination(endpoint, params)
1840
1841 def search_deviations(self, params):
1842 endpoint = "/_puppy/dabrowse/search/deviations"
1843 return self._pagination(endpoint, params, key="deviations")
1844
1845 def user_info(self, user, expand=False):
1846 endpoint = "/_puppy/dauserprofile/init/about"
1847 params = {"username": user}
1848 return self._call(endpoint, params)
1849
1850 def _call(self, endpoint, params):
1851 url = "https://www.deviantart.com" + endpoint
1852 params["csrf_token"] = self.csrf_token or self._fetch_csrf_token()
1853
1854 response = self.request(url, params=params, fatal=None)
1855
1856 try:
1857 return response.json()
1858 except Exception:
1859 return {"error": response.text}
1860
1861 def _pagination(self, endpoint, params, key="results"):
1862 limit = params.get("limit", 24)
1863 warn = True
1864
1865 while True:
1866 data = self._call(endpoint, params)
1867
1868 results = data.get(key)
1869 if results is None:
1870 return
1871 if len(results) < limit and warn and data.get("hasMore"):
1872 warn = False
1873 self.log.warning(
1874 "Private deviations detected! "
1875 "Provide login credentials or session cookies "
1876 "to be able to access them.")
1877 yield from results
1878
1879 if not data.get("hasMore"):
1880 return
1881
1882 if "nextCursor" in data:
1883 params["offset"] = None
1884 params["cursor"] = data["nextCursor"]
1885 elif "nextOffset" in data:
1886 params["offset"] = data["nextOffset"]
1887 params["cursor"] = None
1888 elif params.get("offset") is None:
1889 return
1890 else:
1891 params["offset"] = int(params["offset"]) + len(results)
1892
1893 def _fetch_csrf_token(self, page=None):
1894 if page is None:
1895 page = self.request(self.extractor.root + "/").text
1896 self.csrf_token = token = text.extr(
1897 page, "window.__CSRF_TOKEN__ = '", "'")
1898 return token
1899
1900
1901 def eclipse_media(media, format="preview"):
1902 url = [media["baseUri"]]
1903
1904 formats = {
1905 fmt["t"]: fmt
1906 for fmt in media["types"]
1907 }
1908
1909 if tokens := media.get("token") or ():
1910 if len(tokens) <= 1:
1911 fmt = formats[format]
1912 if "c" in fmt:
1913 url.append(fmt["c"].replace(
1914 "<prettyName>", media["prettyName"]))
1915 url.append("?token=")
1916 url.append(tokens[-1])
1917
1918 return "".join(url), formats
1919
1920
1921 def _refresh_token_cache(token):
1922 if token and token[0] == "#":
1923 return None
1924 return token