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