Debian Codegraph @

gallery_dl/extractor/bluesky.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2024-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://bsky.app/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util
13
14 BASE_PATTERN = (r"(?:https?://)?"
15 r"(?:(?:www\.)?(?:c|[fv]x)?bs[ky]y[ex]?\.app|main\.bsky\.dev)")
16 USER_PATTERN = BASE_PATTERN + r"/profile/([^/?#]+)"
17
18
19 class BlueskyExtractor(Extractor):
20 """Base class for bluesky extractors"""
21 category = "bluesky"
22 directory_fmt = ("{category}", "{author[handle]}")
23 filename_fmt = "{createdAt[:19]}_{post_id}_{num}.{extension}"
24 archive_fmt = "{filename}"
25 root = "https://bsky.app"
26
27 def _init(self):
28 if meta := self.config("metadata") or ():
29 if isinstance(meta, str):
30 meta = meta.replace(" ", "").split(",")
31 elif not isinstance(meta, (list, tuple)):
32 meta = ("user", "facets")
33 self._metadata_user = ("user" in meta)
34 self._metadata_facets = ("facets" in meta)
35
36 self.api = BlueskyAPI(self)
37 self._user = self._user_did = None
38 self.instance = self.root.partition("://")[2]
39 self.videos = self.config("videos", True)
40 self.quoted = self.config("quoted", False)
41
42 def items(self):
43 for post in self.posts():
44 if "post" in post:
45 post = post["post"]
46 elif "item" in post:
47 post = post["item"]
48 if self._user_did and post["author"]["did"] != self._user_did:
49 self.log.debug("Skipping %s (repost)", self._pid(post))
50 continue
51 embed = post.get("embed")
52 try:
53 post.update(post.pop("record"))
54 except Exception:
55 self.log.debug("Skipping %s (no 'record')", self._pid(post))
56 continue
57
58 while True:
59 self._prepare(post)
60 files = self._extract_files(post)
61
62 yield Message.Directory, "", post
63 if files:
64 did = post["author"]["did"]
65 base = (f"{self.cache(self.api.service_endpoint, did)}"
66 f"/xrpc/com.atproto.sync.getBlob?did={did}&cid=")
67 for post["num"], file in enumerate(files, 1):
68 post.update(file)
69 yield Message.Url, base + file["filename"], post
70
71 if not self.quoted or not embed or "record" not in embed:
72 break
73
74 quote = embed["record"]
75 if "record" in quote:
76 quote = quote["record"]
77 value = quote.pop("value", None)
78 if value is None:
79 break
80 quote["quote_id"] = self._pid(post)
81 quote["quote_by"] = post["author"]
82 embed = quote.get("embed")
83 quote.update(value)
84 post = quote
85
86 def posts(self):
87 return ()
88
89 def _posts_records(self, actor, collection):
90 depth = self.config("depth", "0")
91
92 for record in self.api.list_records(actor, collection):
93 uri = None
94 try:
95 uri = record["value"]["subject"]["uri"]
96 if "/app.bsky.feed.post/" in uri:
97 yield from self.api.get_post_thread_uri(uri, depth)
98 except self.exc.ControlException:
99 pass # deleted post
100 except Exception as exc:
101 self.log.debug(record, exc_info=exc)
102 self.log.warning("Failed to extract %s (%s: %s)",
103 uri or "record", exc.__class__.__name__, exc)
104
105 def _pid(self, post):
106 return post["uri"].rpartition("/")[2]
107
108 def _instance(self, handle):
109 return ".".join(handle.rsplit(".", 2)[-2:])
110
111 def _prepare(self, post):
112 author = post["author"]
113 author["instance"] = self._instance(author["handle"])
114
115 if self._metadata_facets:
116 if "facets" in post:
117 post["hashtags"] = tags = []
118 post["mentions"] = dids = []
119 post["uris"] = uris = []
120 for facet in post["facets"]:
121 features = facet["features"][0]
122 if "tag" in features:
123 tags.append(features["tag"])
124 elif "did" in features:
125 dids.append(features["did"])
126 elif "uri" in features:
127 uris.append(features["uri"])
128 else:
129 post["hashtags"] = post["mentions"] = post["uris"] = ()
130
131 if self._metadata_user:
132 post["user"] = self._user or author
133
134 post["instance"] = self.instance
135 post["post_id"] = self._pid(post)
136 post["date"] = self.parse_datetime_iso(post["createdAt"][:19])
137
138 def _extract_files(self, post):
139 if "embed" not in post:
140 post["count"] = 0
141 return ()
142
143 files = []
144 media = post["embed"]
145 if "media" in media:
146 media = media["media"]
147
148 if "images" in media:
149 for image in media["images"]:
150 try:
151 files.append(self._extract_media(image, "image"))
152 except Exception:
153 pass
154 if "items" in media:
155 for item in media["items"]:
156 try:
157 files.append(self._extract_media(
158 item, "image" if "image" in item else "video"))
159 except Exception:
160 pass
161 if "video" in media and self.videos:
162 try:
163 files.append(self._extract_media(media, "video"))
164 except Exception:
165 pass
166
167 post["count"] = len(files)
168 return files
169
170 def _extract_media(self, media, key):
171 try:
172 aspect = media["aspectRatio"]
173 width = aspect["width"]
174 height = aspect["height"]
175 except KeyError:
176 width = height = 0
177
178 data = media[key]
179 try:
180 cid = data["ref"]["$link"]
181 except KeyError:
182 cid = data["cid"]
183
184 return {
185 "description": media.get("alt") or "",
186 "width" : width,
187 "height" : height,
188 "filename" : cid,
189 "extension" : data["mimeType"].rpartition("/")[2],
190 }
191
192 def _make_post(self, actor, kind):
193 did = self.api._did_from_actor(actor)
194 profile = self.cache(self.api.get_profile, did)
195
196 if kind not in profile:
197 return ()
198 cid = profile[kind].rpartition("/")[2].partition("@")[0]
199
200 return ({
201 "post": {
202 "embed": {"images": [{
203 "alt": kind,
204 "image": {
205 "$type" : "blob",
206 "ref" : {"$link": cid},
207 "mimeType": "image/jpeg",
208 "size" : 0,
209 },
210 "aspectRatio": {
211 "width" : 1000,
212 "height": 1000,
213 },
214 }]},
215 "author" : profile,
216 "record" : (),
217 "createdAt": "",
218 "uri" : cid,
219 },
220 },)
221
222
223 class BlueskyUserExtractor(Dispatch, BlueskyExtractor):
224 pattern = USER_PATTERN + r"$"
225 example = "https://bsky.app/profile/HANDLE"
226
227 def items(self):
228 base = f"{self.root}/profile/{self.groups[0]}/"
229 default = ("posts" if self.config("quoted", False) or
230 self.config("reposts", False) else "media")
231 return self._dispatch_extractors((
232 (BlueskyInfoExtractor , base + "info"),
233 (BlueskyAvatarExtractor , base + "avatar"),
234 (BlueskyBackgroundExtractor, base + "banner"),
235 (BlueskyPostsExtractor , base + "posts"),
236 (BlueskyRepliesExtractor , base + "replies"),
237 (BlueskyMediaExtractor , base + "media"),
238 (BlueskyVideoExtractor , base + "video"),
239 (BlueskyLikesExtractor , base + "likes"),
240 ), (default,))
241
242
243 class BlueskyPostsExtractor(BlueskyExtractor):
244 subcategory = "posts"
245 pattern = USER_PATTERN + r"/posts"
246 example = "https://bsky.app/profile/HANDLE/posts"
247
248 def posts(self):
249 return self.api.get_author_feed(
250 self.groups[0], "posts_and_author_threads")
251
252
253 class BlueskyRepliesExtractor(BlueskyExtractor):
254 subcategory = "replies"
255 pattern = USER_PATTERN + r"/replies"
256 example = "https://bsky.app/profile/HANDLE/replies"
257
258 def posts(self):
259 return self.api.get_author_feed(
260 self.groups[0], "posts_with_replies")
261
262
263 class BlueskyMediaExtractor(BlueskyExtractor):
264 subcategory = "media"
265 pattern = USER_PATTERN + r"/media"
266 example = "https://bsky.app/profile/HANDLE/media"
267
268 def posts(self):
269 return self.api.get_author_feed(
270 self.groups[0], "posts_with_media")
271
272
273 class BlueskyVideoExtractor(BlueskyExtractor):
274 subcategory = "video"
275 pattern = USER_PATTERN + r"/video"
276 example = "https://bsky.app/profile/HANDLE/video"
277
278 def posts(self):
279 return self.api.get_author_feed(
280 self.groups[0], "posts_with_video")
281
282
283 class BlueskyLikesExtractor(BlueskyExtractor):
284 subcategory = "likes"
285 pattern = USER_PATTERN + r"/likes"
286 example = "https://bsky.app/profile/HANDLE/likes"
287
288 def posts(self):
289 if self.config("endpoint") == "getActorLikes":
290 return self.api.get_actor_likes(self.groups[0])
291 return self._posts_records(self.groups[0], "app.bsky.feed.like")
292
293
294 class BlueskyFeedExtractor(BlueskyExtractor):
295 subcategory = "feed"
296 pattern = USER_PATTERN + r"/feed/([^/?#]+)"
297 example = "https://bsky.app/profile/HANDLE/feed/NAME"
298
299 def posts(self):
300 actor, feed = self.groups
301 return self.api.get_feed(actor, feed)
302
303
304 class BlueskyListExtractor(BlueskyExtractor):
305 subcategory = "list"
306 pattern = USER_PATTERN + r"/lists/([^/?#]+)"
307 example = "https://bsky.app/profile/HANDLE/lists/ID"
308
309 def posts(self):
310 actor, list_id = self.groups
311 return self.api.get_list_feed(actor, list_id)
312
313
314 class BlueskyFollowingExtractor(BlueskyExtractor):
315 subcategory = "following"
316 pattern = USER_PATTERN + r"/follows"
317 example = "https://bsky.app/profile/HANDLE/follows"
318
319 def items(self):
320 for user in self.api.get_follows(self.groups[0]):
321 url = "https://bsky.app/profile/" + user["did"]
322 user["_extractor"] = BlueskyUserExtractor
323 yield Message.Queue, url, user
324
325
326 class BlueskyPostExtractor(BlueskyExtractor):
327 subcategory = "post"
328 pattern = USER_PATTERN + r"/post/([^/?#]+)"
329 example = "https://bsky.app/profile/HANDLE/post/ID"
330
331 def posts(self):
332 actor, post_id = self.groups
333 return self.api.get_post_thread(actor, post_id)
334
335
336 class BlueskyInfoExtractor(BlueskyExtractor):
337 subcategory = "info"
338 pattern = USER_PATTERN + r"/info"
339 example = "https://bsky.app/profile/HANDLE/info"
340
341 def items(self):
342 self._metadata_user = True
343 self.api._did_from_actor(self.groups[0])
344 return iter(((Message.Directory, "", self._user.copy()),))
345
346
347 class BlueskyAvatarExtractor(BlueskyExtractor):
348 subcategory = "avatar"
349 filename_fmt = "avatar_{post_id}.{extension}"
350 pattern = USER_PATTERN + r"/avatar"
351 example = "https://bsky.app/profile/HANDLE/avatar"
352
353 def posts(self):
354 return self._make_post(self.groups[0], "avatar")
355
356
357 class BlueskyBackgroundExtractor(BlueskyExtractor):
358 subcategory = "background"
359 filename_fmt = "background_{post_id}.{extension}"
360 pattern = USER_PATTERN + r"/ba(?:nner|ckground)"
361 example = "https://bsky.app/profile/HANDLE/banner"
362
363 def posts(self):
364 return self._make_post(self.groups[0], "banner")
365
366
367 class BlueskySearchExtractor(BlueskyExtractor):
368 subcategory = "search"
369 pattern = BASE_PATTERN + r"/search(?:/|\?q=)(.+)"
370 example = "https://bsky.app/search?q=QUERY"
371
372 def posts(self):
373 query = text.unquote(self.groups[0].replace("+", " "))
374 return self.api.search_posts(query)
375
376
377 class BlueskyHashtagExtractor(BlueskyExtractor):
378 subcategory = "hashtag"
379 pattern = BASE_PATTERN + r"/hashtag/([^/?#]+)(?:/(top|latest))?"
380 example = "https://bsky.app/hashtag/NAME"
381
382 def posts(self):
383 hashtag, order = self.groups
384 return self.api.search_posts("#"+hashtag, order)
385
386
387 class BlueskyBookmarkExtractor(BlueskyExtractor):
388 subcategory = "bookmark"
389 pattern = BASE_PATTERN + r"/saved"
390 example = "https://bsky.app/saved"
391
392 def posts(self):
393 return self.api.get_bookmarks()
394
395
396 class BlueskyAPI():
397 """Interface for the Bluesky API
398
399 https://docs.bsky.app/docs/category/http-reference
400 """
401
402 def __init__(self, extractor):
403 self.extractor = extractor
404 self.log = extractor.log
405 self.headers = {"Accept": "application/json"}
406
407 self.username, self.password = extractor._get_auth_info()
408 if srv := extractor.config("api-server", False):
409 self.root = srv.rstrip("/")
410 elif self.username:
411 self.root = "https://bsky.social"
412 else:
413 self.root = "https://api.bsky.app"
414 self.authenticate = util.noop
415
416 def get_actor_likes(self, actor):
417 endpoint = "app.bsky.feed.getActorLikes"
418 params = {
419 "actor": self._did_from_actor(actor),
420 "limit": "100",
421 }
422 return self._pagination(endpoint, params, check_empty=True)
423
424 def get_author_feed(self, actor, filter="posts_and_author_threads"):
425 endpoint = "app.bsky.feed.getAuthorFeed"
426 params = {
427 "actor" : self._did_from_actor(actor, True),
428 "filter": filter,
429 "limit" : "100",
430 }
431 return self._pagination(endpoint, params)
432
433 def get_bookmarks(self):
434 endpoint = "app.bsky.bookmark.getBookmarks"
435 return self._pagination(endpoint, {}, "bookmarks", check_empty=True)
436
437 def get_feed(self, actor, feed):
438 endpoint = "app.bsky.feed.getFeed"
439 uri = (f"at://{self._did_from_actor(actor)}"
440 f"/app.bsky.feed.generator/{feed}")
441 params = {"feed": uri, "limit": "100"}
442 return self._pagination(endpoint, params)
443
444 def get_follows(self, actor):
445 endpoint = "app.bsky.graph.getFollows"
446 params = {
447 "actor": self._did_from_actor(actor),
448 "limit": "100",
449 }
450 return self._pagination(endpoint, params, "follows")
451
452 def get_list_feed(self, actor, list):
453 endpoint = "app.bsky.feed.getListFeed"
454 uri = f"at://{self._did_from_actor(actor)}/app.bsky.graph.list/{list}"
455 params = {"list" : uri, "limit": "100"}
456 return self._pagination(endpoint, params)
457
458 def get_post_thread(self, actor, post_id):
459 uri = (f"at://{self._did_from_actor(actor)}"
460 f"/app.bsky.feed.post/{post_id}")
461 depth = self.extractor.config("depth", "0")
462 return self.get_post_thread_uri(uri, depth)
463
464 def get_post_thread_uri(self, uri, depth="0"):
465 endpoint = "app.bsky.feed.getPostThread"
466 params = {
467 "uri" : uri,
468 "depth" : depth,
469 "parentHeight": "0",
470 }
471
472 thread = self._call(endpoint, params)["thread"]
473 if "replies" not in thread:
474 return (thread,)
475
476 index = 0
477 posts = [thread]
478 while index < len(posts):
479 post = posts[index]
480 if "replies" in post:
481 posts.extend(post["replies"])
482 index += 1
483 return posts
484
485 def get_profile(self, did):
486 endpoint = "app.bsky.actor.getProfile"
487 params = {"actor": did}
488 return self._call(endpoint, params)
489
490 def list_records(self, actor, collection):
491 endpoint = "com.atproto.repo.listRecords"
492 actor_did = self._did_from_actor(actor)
493 service = self.extractor.cache(self.service_endpoint, actor_did)
494 params = {
495 "repo" : actor_did,
496 "collection": collection,
497 "limit" : "100",
498 # "reverse" : "false",
499 }
500 return self._pagination(endpoint, params, "records", service)
501
502 def resolve_handle(self, handle):
503 endpoint = "com.atproto.identity.resolveHandle"
504 params = {"handle": handle}
505 return self._call(endpoint, params)["did"]
506
507 def service_endpoint(self, did):
508 if did.startswith('did:web:'):
509 url = f"https://{did[8:]}/.well-known/did.json"
510 else:
511 url = "https://plc.directory/" + did
512
513 try:
514 data = self.extractor.request_json(url)
515 for service in data["service"]:
516 if service["type"] == "AtprotoPersonalDataServer":
517 return service["serviceEndpoint"]
518 except Exception:
519 pass
520 return "https://bsky.social"
521
522 def search_posts(self, query, sort=None):
523 endpoint = "app.bsky.feed.searchPosts"
524 params = {
525 "q" : query,
526 "limit": "100",
527 "sort" : sort,
528 }
529 return self._pagination(endpoint, params, "posts")
530
531 def _did_from_actor(self, actor, user_did=False):
532 if actor.startswith("did:"):
533 did = actor
534 else:
535 did = self.extractor.cache(self.resolve_handle, actor)
536
537 extr = self.extractor
538 if user_did and not extr.config("reposts", False):
539 extr._user_did = did
540 if extr._metadata_user:
541 extr._user = user = extr.cache(self.get_profile, did)
542 user["instance"] = extr._instance(user["handle"])
543
544 return did
545
546 def authenticate(self):
547 self.headers["Authorization"] = self.extractor.cache(
548 self._authenticate_impl, self.username, _exp=3600, _mem=False)
549
550 def _authenticate_impl(self, username):
551 if refresh_token := self.extractor.cache(
552 _refresh_token_cache, username, _mem=False):
553 self.log.info("Refreshing access token for %s", username)
554 endpoint = "com.atproto.server.refreshSession"
555 headers = {"Authorization": "Bearer " + refresh_token}
556 json = None
557 else:
558 self.log.info("Logging in as %s", username)
559 endpoint = "com.atproto.server.createSession"
560 headers = None
561 json = {
562 "identifier": username,
563 "password" : self.password,
564 }
565
566 url = f"{self.root}/xrpc/{endpoint}"
567
568 while True:
569 response = self.extractor.request(
570 url, method="POST", headers=headers, json=json, fatal=None)
571 data = response.json()
572
573 if data.get("error") == "AuthFactorTokenRequired":
574 json["authFactorToken"] = self.extractor.input(
575 data.get("message", "Login Code") + ": ")
576 elif response.status_code != 200:
577 self.log.debug("Server response: %s", data)
578 raise self.extractor.exc.AuthenticationError(
579 f"\"{data.get('error')}: {data.get('message')}\"")
580 else:
581 break # success
582
583 self.extractor.cache_update(_refresh_token_cache, self.username,
584 data["refreshJwt"], _exp=84*86400)
585 return "Bearer " + data["accessJwt"]
586
587 def _call(self, endpoint, params, root=None):
588 if root is None:
589 root = self.root
590 url = f"{root}/xrpc/{endpoint}"
591
592 while True:
593 self.authenticate()
594 response = self.extractor.request(
595 url, params=params, headers=self.headers, fatal=None)
596
597 if response.status_code < 400:
598 return response.json()
599 if response.status_code == 429:
600 until = response.headers.get("RateLimit-Reset")
601 self.extractor.wait(until=until)
602 continue
603
604 msg = "API request failed"
605 try:
606 data = response.json()
607 msg = f"{msg} ('{data['error']}: {data['message']}')"
608 except Exception:
609 msg = f"{msg} ({response.status_code} {response.reason})"
610
611 self.extractor.log.debug("Server response: %s", response.text)
612 raise self.extractor.exc.AbortExtraction(msg)
613
614 def _pagination(self, endpoint, params,
615 key="feed", root=None, check_empty=False):
616 while True:
617 data = self._call(endpoint, params, root)
618
619 if check_empty and not data[key]:
620 return
621 yield from data[key]
622
623 cursor = data.get("cursor")
624 if not cursor:
625 return
626 params["cursor"] = cursor
627
628
629 def _refresh_token_cache(username):
630 return None