Debian Codegraph @

gallery_dl/extractor/deviantart.py

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