Debian Codegraph @

gallery_dl/extractor/tumblr.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2016-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.tumblr.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util, dt, oauth
13
14
15 BASE_PATTERN = (
16 r"(?:tumblr:(?:https?://)?([^/]+)|"
17 r"(?:https?://)?"
18 r"(?:(?:www\.)?tumblr\.com/(?:blog/(?:view/)?)?([\w:-]+)|"
19 r"([\w-]+\.tumblr\.com)))"
20 )
21
22 POST_TYPES = {"text", "quote", "link", "answer", "video",
23 "audio", "photo", "chat", "search"}
24
25
26 class TumblrExtractor(Extractor):
27 """Base class for tumblr extractors"""
28 category = "tumblr"
29 directory_fmt = ("{category}", "{blog_name}")
30 filename_fmt = "{category}_{blog_name}_{id}_{num:>02}.{extension}"
31 archive_fmt = "{id}_{num}"
32
33 def _init(self):
34 if name := self.groups[1]:
35 if not name.startswith("t:"):
36 name += ".tumblr.com"
37 self.blog = name
38 else:
39 self.blog = self.groups[0] or self.groups[2]
40
41 self.api = TumblrAPI(self)
42 self.types = self._setup_posttypes()
43 self.avatar = self.config("avatar", False)
44 self.inline = self.config("inline", True)
45 self.reblogs = self.config("reblogs", True)
46 self.external = self.config("external", False)
47 self.original = self.config("original", True)
48 self.fallback_delay = self.config("fallback-delay", 120.0)
49 self.fallback_retries = self.config("fallback-retries", 2)
50
51 if len(self.types) == 1:
52 self.api.posts_type = next(iter(self.types))
53 elif not self.types:
54 self.log.warning("no valid post types selected")
55
56 if il := self.inline:
57 if il == "reblog":
58 self._extract_body = lambda p: p["reblog"]["comment"]
59 elif il == "original":
60 self._extract_body = lambda p: (p["reblog"]["tree_html"] or
61 p["reblog"]["comment"])
62 self.inline = True
63
64 if self.reblogs == "same-blog":
65 self._skip_reblog = self._skip_reblog_same_blog
66
67 self.date_min, self.api.before = self._get_date_min_max(0, None)
68
69 def skip_date(self, date):
70 self.api.before = int(dt.to_ts(date))
71 return True
72
73 def items(self):
74 blog = None
75
76 # pre-compile regular expressions
77 self._sub_video = text.re(
78 r"https?://((?:vt|vtt|ve)(?:\.media)?\.tumblr\.com"
79 r"/tumblr_[^_]+)_\d+\.([0-9a-z]+)").sub
80 if self.inline:
81 self._sub_image = text.re(
82 r"https?://(\d+\.media\.tumblr\.com(?:/[0-9a-f]+)?"
83 r"/tumblr(?:_inline)?_[^_]+)_\d+\.([0-9a-z]+)").sub
84 self._subn_orig_image = text.re(
85 r"/s\d+x\d+/").subn
86 self._finditer_inline = text.re(
87 r'<(?:img|source()) [^>]*src="([^"]+)"').finditer
88
89 for post in self.posts():
90 if self.date_min > post["timestamp"]:
91 return
92 if post["type"] not in self.types:
93 continue
94
95 if "blog" in post:
96 blog = post["blog"]
97 self.blog = blog["name"] + ".tumblr.com"
98 else:
99 if not blog:
100 blog = self.api.info(self.blog)
101 blog["uuid"] = self.blog
102
103 if self.avatar:
104 url = self.api.avatar(self.blog)
105 yield Message.Directory, "", {"blog": blog}
106 yield self._prepare_avatar(url, post.copy(), blog)
107
108 post["blog"] = blog
109
110 reblog = "reblogged_from_id" in post
111 if reblog and self._skip_reblog(post):
112 self.log.debug("%s: Skipping reblogged post from %s",
113 post.get("id"), post.get("reblogged_from_name"))
114 continue
115 post["reblogged"] = reblog
116
117 if "trail" in post:
118 del post["trail"]
119 post["date"] = self.parse_timestamp(post["timestamp"])
120 post["source"] = None
121 posts = []
122
123 if "photos" in post: # type "photo" or "link"
124 post["source"] = "photo"
125 photos = post["photos"]
126 del post["photos"]
127
128 for photo in photos:
129 post["photo"] = photo
130
131 best_photo = photo["original_size"]
132 for alt_photo in photo["alt_sizes"]:
133 if (alt_photo["height"] > best_photo["height"] or
134 alt_photo["width"] > best_photo["width"]):
135 best_photo = alt_photo
136 photo.update(best_photo)
137
138 if self.original and "/s2048x3072/" in photo["url"] and (
139 photo["width"] == 2048 or photo["height"] == 3072):
140 photo["url"], fb = self._original_photo(photo["url"])
141 if fb:
142 post["_fallback"] = self._original_image_fallback(
143 photo["url"], post["id"])
144
145 del photo["original_size"]
146 del photo["alt_sizes"]
147 posts.append(
148 self._prepare_image(photo["url"], post.copy()))
149 del post["photo"]
150 post.pop("_fallback", None)
151
152 url = post.get("audio_url") # type "audio"
153 if url and url.startswith("https://a.tumblr.com/"):
154 post["source"] = "audio"
155 posts.append(self._prepare(url, post.copy()))
156
157 if url := post.get("video_url"): # type "video"
158 post["source"] = "video"
159 posts.append(self._prepare(
160 self._original_video(url), post.copy()))
161
162 if self.inline and "reblog" in post: # inline media
163 # only "chat" posts are missing a "reblog" key in their
164 # API response, but they can't contain images/videos anyway
165 seen = set()
166 if txt := post.get("answer"):
167 post["source"] = "answer"
168 self._extract_inline(posts, post, seen, txt)
169 if txt := post.get("question"):
170 post["source"] = "question"
171 self._extract_inline(posts, post, seen, txt)
172 if txt := self._extract_body(post):
173 post["source"] = "inline"
174 self._extract_inline(posts, post, seen, txt)
175
176 if self.external: # external links
177 if url := post.get("permalink_url") or post.get("url"):
178 post["source"] = "external"
179 post["extension"] = None
180 posts.append((Message.Queue, url, post.copy()))
181 del post["extension"]
182
183 del post["source"]
184 post["count"] = len(posts)
185 yield Message.Directory, "", post
186
187 for num, (msg, url, post) in enumerate(posts, 1):
188 post["num"] = num
189 post["count"] = len(posts)
190 yield msg, url, post
191
192 def items_blogs(self):
193 for blog in self.blogs():
194 blog["_extractor"] = TumblrUserExtractor
195 yield Message.Queue, blog["url"], blog
196
197 def posts(self):
198 """Return an iterable containing all relevant posts"""
199
200 def _setup_posttypes(self):
201 types = self.config("posts", "all")
202
203 if types == "all":
204 return POST_TYPES
205
206 elif not types:
207 return frozenset()
208
209 else:
210 if isinstance(types, str):
211 types = types.split(",")
212 types = frozenset(types)
213
214 if invalid := types - POST_TYPES:
215 types = types & POST_TYPES
216 self.log.warning("Invalid post types: '%s'",
217 "', '".join(sorted(invalid)))
218 return types
219
220 def _prepare(self, url, post):
221 text.nameext_from_url(url, post)
222 post["hash"] = post["filename"].partition("_")[2]
223 return Message.Url, url, post
224
225 def _prepare_image(self, url, post):
226 text.nameext_from_url(url, post)
227
228 # try ".gifv" (#3095)
229 # it's unknown whether all gifs in this case are actually webps
230 # incorrect extensions will be corrected by 'adjust-extensions'
231 if post["extension"] == "gif":
232 post["_fallback"] = (url + "v",)
233 post["_http_headers"] = {"Accept": # copied from chrome 106
234 "image/avif,image/webp,image/apng,"
235 "image/svg+xml,image/*,*/*;q=0.8"}
236
237 parts = post["filename"].split("_")
238 try:
239 post["hash"] = parts[1] if parts[1] != "inline" else parts[2]
240 except IndexError:
241 # filename doesn't follow the usual pattern (#129)
242 post["hash"] = post["filename"]
243
244 return Message.Url, url, post
245
246 def _prepare_avatar(self, url, post, blog):
247 text.nameext_from_url(url, post)
248 post["num"] = post["count"] = 1
249 post["blog"] = blog
250 post["reblogged"] = False
251 post["type"] = post["id"] = post["hash"] = "avatar"
252 return Message.Url, url, post
253
254 def _skip_reblog(self, _):
255 return not self.reblogs
256
257 def _skip_reblog_same_blog(self, post):
258 try:
259 return post["blog"]["uuid"] != post.get("reblogged_root_uuid")
260 except Exception:
261 return self.blog != post.get("reblogged_root_uuid")
262
263 def _extract_body(self, post):
264 rb = post["reblog"]
265 return rb["comment"] + rb["tree_html"]
266
267 def _extract_inline(self, posts, post, seen, txt):
268 more = txt.find(">[[MORE]]<") + 1
269 for match in self._finditer_inline(txt):
270 post["keepreading"] = (match.end() > more) if more else False
271 vid, url = match.groups()
272 if vid is None:
273 if url not in seen:
274 seen.add(url)
275 url, fb = self._original_inline_image(url)
276 if fb:
277 post["_fallback"] = self._original_image_fallback(
278 url, post["id"])
279 posts.append(self._prepare_image(url, post.copy()))
280 post.pop("_fallback", None)
281 else:
282 url = self._original_video(url)
283 if url not in seen:
284 seen.add(url)
285 posts.append(self._prepare(url, post.copy()))
286
287 def _original_photo(self, url):
288 resized = url.replace("/s2048x3072/", "/s99999x99999/", 1)
289 return self._update_image_token(resized)
290
291 def _original_inline_image(self, url):
292 if self.original:
293 resized, n = self._subn_orig_image("/s99999x99999/", url, 1)
294 if n:
295 return self._update_image_token(resized)
296 return self._sub_image(r"https://\1_1280.\2", url), False
297
298 def _original_video(self, url):
299 return self._sub_video(r"https://\1.\2", url)
300
301 def _update_image_token(self, resized):
302 headers = {"Accept": "text/html,*/*;q=0.8"}
303 try:
304 response = self.request(resized, headers=headers)
305 except Exception:
306 return resized, True
307 else:
308 updated = text.extr(response.text, '" src="', '"')
309 return updated, (resized == updated)
310
311 def _original_image_fallback(self, url, post_id):
312 for _ in util.repeat(self.fallback_retries):
313 self.sleep(self.fallback_delay, "image token")
314 yield self._update_image_token(url)[0]
315 self.log.warning("Unable to fetch higher-resolution "
316 "version of %s (%s)", url, post_id)
317
318
319 class TumblrUserExtractor(TumblrExtractor):
320 """Extractor for a Tumblr user's posts"""
321 subcategory = "user"
322 pattern = BASE_PATTERN + r"(?:/page/\d+|/archive)?/?$"
323 example = "https://www.tumblr.com/BLOG"
324
325 def posts(self):
326 return self.api.posts(self.blog, {})
327
328
329 class TumblrPostExtractor(TumblrExtractor):
330 """Extractor for a single Tumblr post"""
331 subcategory = "post"
332 pattern = BASE_PATTERN + r"/(?:post/|image/)?(\d+)"
333 example = "https://www.tumblr.com/BLOG/12345"
334
335 def posts(self):
336 self.date_min = 0
337 return self.api.posts(self.blog, {"id": self.groups[3]})
338
339 def _setup_posttypes(self):
340 return POST_TYPES
341
342
343 class TumblrTagExtractor(TumblrExtractor):
344 """Extractor for Tumblr user's posts by tag"""
345 subcategory = "tag"
346 pattern = BASE_PATTERN + r"(?:/archive)?/tagged/([^/?#]+)"
347 example = "https://www.tumblr.com/BLOG/tagged/TAG"
348
349 def posts(self):
350 self.kwdict["search_tags"] = tag = text.unquote(
351 self.groups[3].replace("-", " "))
352 return self.api.posts(self.blog, {"tag": tag})
353
354
355 class TumblrDayExtractor(TumblrExtractor):
356 """Extractor for Tumblr user's posts by day"""
357 subcategory = "day"
358 pattern = BASE_PATTERN + r"/day/(\d\d\d\d/\d\d/\d\d)"
359 example = "https://www.tumblr.com/BLOG/day/1970/01/01"
360
361 def posts(self):
362 year, month, day = self.groups[3].split("/")
363 ordinal = dt.date(int(year), int(month), int(day)).toordinal()
364
365 # 719163 == date(1970, 1, 1).toordinal()
366 self.date_min = (ordinal - 719163) * 86400
367 self.api.before = self.date_min + 86400
368 return self.api.posts(self.blog, {})
369
370
371 class TumblrLikesExtractor(TumblrExtractor):
372 """Extractor for a Tumblr user's liked posts"""
373 subcategory = "likes"
374 directory_fmt = ("{category}", "{blog_name}", "likes")
375 archive_fmt = "f_{blog[name]}_{id}_{num}"
376 pattern = BASE_PATTERN + r"/likes"
377 example = "https://www.tumblr.com/BLOG/likes"
378
379 def posts(self):
380 return self.api.likes(self.blog)
381
382
383 class TumblrFollowingExtractor(TumblrExtractor):
384 """Extractor for a Tumblr user's followed blogs"""
385 subcategory = "following"
386 pattern = BASE_PATTERN + r"/following"
387 example = "https://www.tumblr.com/BLOG/following"
388
389 items = TumblrExtractor.items_blogs
390
391 def blogs(self):
392 return self.api.following(self.blog)
393
394
395 class TumblrFollowersExtractor(TumblrExtractor):
396 """Extractor for a Tumblr user's followers"""
397 subcategory = "followers"
398 pattern = BASE_PATTERN + r"/followers"
399 example = "https://www.tumblr.com/BLOG/followers"
400
401 items = TumblrExtractor.items_blogs
402
403 def blogs(self):
404 return self.api.followers(self.blog)
405
406
407 class TumblrSearchExtractor(TumblrExtractor):
408 """Extractor for a Tumblr search"""
409 subcategory = "search"
410 pattern = (r"(?:https?://)?(?:www\.)?tumblr\.com/search/([^/?#]+)"
411 r"(?:/([^/?#]+)(?:/([^/?#]+))?)?(?:/?\?([^#]+))?")
412 example = "https://www.tumblr.com/search/QUERY"
413
414 def posts(self):
415 search, mode, post_type, query = self.groups
416 params = text.parse_query(query)
417 return self.api.search(text.unquote(search), params, mode, post_type)
418
419
420 class TumblrAPI(oauth.OAuth1API):
421 """Interface for the Tumblr API v2
422
423 https://github.com/tumblr/docs/blob/master/api.md
424 """
425 ROOT = "https://api.tumblr.com"
426 API_KEY = "O3hU2tMi5e4Qs5t3vezEi6L0qRORJ5y9oUpSGsrWu8iA3UCc3B"
427 API_SECRET = "sFdsK3PDdP2QpYMRAoq0oDnw0sFS24XigXmdfnaeNZpJpqAn03"
428 BLOG_CACHE = {}
429
430 def __init__(self, extractor):
431 oauth.OAuth1API.__init__(self, extractor)
432 self.posts_type = self.before = None
433
434 def info(self, blog):
435 """Return general information about a blog"""
436 try:
437 return self.BLOG_CACHE[blog]
438 except KeyError:
439 endpoint = f"/v2/blog/{blog}/info"
440 params = {"api_key": self.api_key} if self.api_key else None
441 self.BLOG_CACHE[blog] = blog = self._call(endpoint, params)["blog"]
442 return blog
443
444 def avatar(self, blog, size="512"):
445 """Retrieve a blog avatar"""
446 if self.api_key:
447 return (f"{self.ROOT}/v2/blog/{blog}/avatar/{size}"
448 f"?api_key={self.api_key}")
449 endpoint = f"/v2/blog/{blog}/avatar"
450 params = {"size": size}
451 return self._call(
452 endpoint, params, allow_redirects=False)["avatar_url"]
453
454 def posts(self, blog, params):
455 """Retrieve published posts"""
456 params["offset"] = self.extractor.config("offset")
457 params["limit"] = 50
458 params["reblog_info"] = "true"
459 params["type"] = self.posts_type
460 params["before"] = self.before
461
462 if self.before and params["offset"]:
463 self.log.warning("'offset' and 'date-max' cannot be used together")
464
465 endpoint = f"/v2/blog/{blog}/posts"
466 return self._pagination(endpoint, params, blog=blog, cache=True)
467
468 def likes(self, blog):
469 """Retrieve liked posts"""
470 endpoint = f"/v2/blog/{blog}/likes"
471 params = {"limit": "50", "before": self.before}
472 if self.api_key:
473 params["api_key"] = self.api_key
474
475 while True:
476 posts = self._call(endpoint, params)["liked_posts"]
477 if not posts:
478 return
479 yield from posts
480 params["before"] = posts[-1]["liked_timestamp"]
481
482 def following(self, blog):
483 endpoint = f"/v2/blog/{blog}/following"
484 return self._pagination_blogs(endpoint)
485
486 def followers(self, blog):
487 endpoint = f"/v2/blog/{blog}/followers"
488 return self._pagination_blogs(endpoint)
489
490 def search(self, query, params, mode="top", post_type=None):
491 """Retrieve search results"""
492 endpoint = "/v2/timeline/search"
493
494 params["limit"] = "50"
495 params["days"] = params.pop("t", None)
496 params["query"] = query
497 params["mode"] = mode
498 params["reblog_info"] = "true" if self.extractor.reblogs else "false"
499 if post_type:
500 params["post_type_filter"] = post_type
501
502 return self._pagination(endpoint, params)
503
504 def _call(self, endpoint, params, **kwargs):
505 url = self.ROOT + endpoint
506 kwargs["params"] = params
507
508 while True:
509 response = self.request(url, **kwargs)
510
511 try:
512 data = response.json()
513 except ValueError:
514 data = response.text
515 status = response.status_code
516 else:
517 status = data["meta"]["status"]
518 if 200 <= status < 400:
519 return data["response"]
520
521 self.log.debug(data)
522
523 if status == 403:
524 msg = data.get("response")
525 if msg == "You do not have permission to view this blog" and \
526 self.api_key is None:
527 self.log.debug("Retrying with 'api_key' authentication")
528 self.api_key = params["api_key"] = \
529 self.session.auth.consumer_key
530 self.session = self.extractor.session
531 continue
532 msg = f"'{msg}'" if isinstance(msg, str) else None
533 raise self.exc.AuthorizationError(msg)
534
535 elif status == 404:
536 try:
537 error = data["errors"][0]["detail"]
538 board = ("only viewable within the Tumblr dashboard"
539 in error)
540 except Exception:
541 board = False
542
543 if board:
544 if self.api_key is None:
545 self.log.info(
546 "Ensure your 'access-token' and "
547 "'access-token-secret' belong to the same "
548 "application as 'api-key' and 'api-secret'")
549 else:
550 self.log.info("Run 'gallery-dl oauth:tumblr' "
551 "to access dashboard-only blogs")
552 raise self.exc.AuthorizationError(error)
553 raise self.exc.NotFoundError("user or post")
554
555 elif status == 429:
556 # daily rate limit
557 if response.headers.get("x-ratelimit-perday-remaining") == "0":
558 self.log.info("Daily API rate limit exceeded")
559 reset = response.headers.get("x-ratelimit-perday-reset")
560
561 api_key = self.api_key or self.session.auth.consumer_key
562 if api_key == self.API_KEY:
563 self.log.info(
564 "Register your own OAuth application and use its "
565 "credentials to prevent this error: "
566 "https://gdl-org.github.io/docs/configuration.html"
567 "#extractor-tumblr-api-key-api-secret")
568
569 if self.extractor.config("ratelimit") == "wait":
570 self.extractor.wait(seconds=reset)
571 continue
572
573 t = (dt.now() + dt.timedelta(0, float(reset))).time()
574 raise self.exc.AbortExtraction(
575 f"Aborting - Rate limit will reset at "
576 f"{t.hour:02}:{t.minute:02}:{t.second:02}")
577
578 # hourly rate limit
579 if reset := response.headers.get("x-ratelimit-perhour-reset"):
580 self.log.info("Hourly API rate limit exceeded")
581 self.extractor.wait(seconds=reset)
582 continue
583
584 raise self.exc.AbortExtraction(data)
585
586 def _pagination(self, endpoint, params,
587 blog=None, key="posts", cache=False):
588 if self.api_key:
589 params["api_key"] = self.api_key
590
591 if strategy := self.extractor.config("pagination"):
592 if strategy not in {"api", "before"} and "offset" not in params:
593 self.log.warning('Unable to use "pagination": "%s". '
594 'Falling back to "api".', strategy)
595 strategy = "api"
596 elif params.get("before"):
597 strategy = "before"
598 elif "offset" not in params:
599 strategy = "api"
600 self.log.debug("Pagination strategy '%s'", strategy or "offset")
601
602 while True:
603 data = self._call(endpoint, params)
604
605 if "timeline" in data:
606 data = data["timeline"]
607 posts = data["elements"]
608
609 else:
610 if cache:
611 self.BLOG_CACHE[blog] = data["blog"]
612 cache = False
613 posts = data[key]
614
615 yield from posts
616
617 if strategy == "api":
618 try:
619 endpoint = data["_links"]["next"]["href"]
620 except KeyError:
621 return
622 if params is not None and self.api_key:
623 endpoint = f"{endpoint}&api_key={self.api_key}"
624 params = None
625
626 elif strategy == "before":
627 if not posts:
628 return
629 timestamp = posts[-1]["timestamp"] + 1
630 if params["before"] and timestamp >= params["before"]:
631 return
632 params["before"] = timestamp
633 params["offset"] = None
634
635 else: # offset
636 params["offset"] = \
637 text.parse_int(params["offset"]) + params["limit"]
638 params["before"] = None
639 if params["offset"] >= data["total_posts"]:
640 return
641
642 def _pagination_blogs(self, endpoint, params=None):
643 if params is None:
644 params = {}
645 if self.api_key:
646 params["api_key"] = self.api_key
647 params["limit"] = 20
648 params["offset"] = text.parse_int(params.get("offset"), 0)
649
650 while True:
651 data = self._call(endpoint, params)
652
653 blogs = data["blogs"]
654 yield from blogs
655
656 params["offset"] = params["offset"] + params["limit"]
657 if params["offset"] >= data["total_blogs"]:
658 return