Debian Codegraph @

gallery_dl/extractor/mastodon.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2019-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 Mastodon instances"""
10
11 from .common import BaseExtractor, Message
12 from .. import text
13
14
15 class MastodonExtractor(BaseExtractor):
16 """Base class for mastodon extractors"""
17 basecategory = "mastodon"
18 directory_fmt = ("mastodon", "{instance}", "{account[username]}")
19 filename_fmt = "{category}_{id}_{media[id]}.{extension}"
20 archive_fmt = "{media[id]}"
21
22 def __init__(self, match):
23 BaseExtractor.__init__(self, match)
24 self.item = self.groups[-1]
25
26 def _init(self):
27 self.instance = self.root.partition("://")[2]
28 self.reblogs = self.config("reblogs", False)
29 self.replies = self.config("replies", True)
30 self.cards = self.config("cards", False)
31
32 def items(self):
33 for status in self.statuses():
34
35 if self._check_moved:
36 self._check_moved(status["account"])
37 if not self.reblogs and status["reblog"]:
38 self.log.debug("Skipping %s (reblog)", status["id"])
39 continue
40 if not self.replies and status["in_reply_to_id"]:
41 self.log.debug("Skipping %s (reply)", status["id"])
42 continue
43
44 attachments = status["media_attachments"]
45 del status["media_attachments"]
46
47 if status["reblog"]:
48 attachments.extend(status["reblog"]["media_attachments"])
49
50 if self.cards:
51 if card := status.get("card"):
52 if url := card.get("image"):
53 card["weburl"] = card.get("url")
54 card["url"] = url
55 card["id"] = "card" + "".join(
56 url.split("/")[6:-2]).lstrip("0")
57 attachments.append(card)
58
59 status["instance"] = self.instance
60 acct = status["account"]["acct"]
61 status["instance_remote"] = \
62 acct.rpartition("@")[2] if "@" in acct else None
63
64 status["count"] = len(attachments)
65 status["tags"] = [tag["name"] for tag in status["tags"]]
66 status["date"] = self.parse_datetime_iso(status["created_at"][:19])
67
68 yield Message.Directory, "", status
69 for status["num"], media in enumerate(attachments, 1):
70 status["media"] = media
71 url = media["url"]
72 yield Message.Url, url, text.nameext_from_url(url, status)
73
74 def statuses(self):
75 """Return an iterable containing all relevant Status objects"""
76 return ()
77
78 def _check_moved(self, account):
79 self._check_moved = None
80 # Certain fediverse software (such as Iceshrimp and Sharkey) have a
81 # null account "moved" field instead of not having it outright.
82 # To handle this, check if the "moved" value is truthy instead
83 # if only it exists.
84 if account.get("moved"):
85 self.log.warning("Account '%s' moved to '%s'",
86 account["acct"], account["moved"]["acct"])
87
88
89 BASE_PATTERN = MastodonExtractor.update({
90 "mastodon.social": {
91 "root" : "https://mastodon.social",
92 "pattern" : r"mastodon\.social",
93 "client-id" : "dBSHdpsnOUZgxOnjKSQrWEPakO3ctM7HmsyoOd4FcRo",
94 "client-secret": "DdrODTHs_XoeOsNVXnILTMabtdpWrWOAtrmw91wU1zI",
95 },
96 "pawoo": {
97 "root" : "https://pawoo.net",
98 "pattern" : r"pawoo\.net",
99 "client-id" : "978a25f843ec01e53d09be2c290cd75c"
100 "782bc3b7fdbd7ea4164b9f3c3780c8ff",
101 "client-secret": "9208e3d4a7997032cf4f1b0e12e5df38"
102 "8428ef1fadb446dcfeb4f5ed6872d97b",
103 },
104 "baraag": {
105 "root" : "https://baraag.net",
106 "pattern" : r"baraag\.net",
107 "client-id" : "czxx2qilLElYHQ_sm-lO8yXuGwOHxLX9RYYaD0-nq1o",
108 "client-secret": "haMaFdMBgK_-BIxufakmI2gFgkYjqmgXGEO2tB-R2xY",
109 }
110 }) + "(?:/web)?"
111
112
113 class MastodonUserExtractor(MastodonExtractor):
114 """Extractor for all images of an account/user"""
115 subcategory = "user"
116 pattern = BASE_PATTERN + r"/(?:@|users/)([^/?#]+)(?:/media)?/?$"
117 example = "https://mastodon.social/@USER"
118
119 def statuses(self):
120 api = MastodonAPI(self)
121
122 return api.account_statuses(
123 api.account_id_by_username(self.item),
124 only_media=(
125 not self.reblogs and
126 not self.cards and
127 not self.config("text-posts", False)
128 ),
129 exclude_replies=not self.replies,
130 )
131
132
133 class MastodonBookmarkExtractor(MastodonExtractor):
134 """Extractor for mastodon bookmarks"""
135 subcategory = "bookmark"
136 pattern = BASE_PATTERN + r"/bookmarks"
137 example = "https://mastodon.social/bookmarks"
138
139 def statuses(self):
140 return MastodonAPI(self).account_bookmarks()
141
142
143 class MastodonFavoriteExtractor(MastodonExtractor):
144 """Extractor for mastodon favorites"""
145 subcategory = "favorite"
146 pattern = BASE_PATTERN + r"/favourites"
147 example = "https://mastodon.social/favourites"
148
149 def statuses(self):
150 return MastodonAPI(self).account_favorites()
151
152
153 class MastodonListExtractor(MastodonExtractor):
154 """Extractor for mastodon lists"""
155 subcategory = "list"
156 pattern = BASE_PATTERN + r"/lists/(\w+)"
157 example = "https://mastodon.social/lists/12345"
158
159 def statuses(self):
160 return MastodonAPI(self).timelines_list(self.item)
161
162
163 class MastodonHashtagExtractor(MastodonExtractor):
164 """Extractor for mastodon hashtags"""
165 subcategory = "hashtag"
166 pattern = BASE_PATTERN + r"/tags/(\w+)"
167 example = "https://mastodon.social/tags/NAME"
168
169 def statuses(self):
170 return MastodonAPI(self).timelines_tag(self.item)
171
172
173 class MastodonFollowingExtractor(MastodonExtractor):
174 """Extractor for followed mastodon users"""
175 subcategory = "following"
176 pattern = BASE_PATTERN + r"/(?:@|users/)([^/?#]+)/following"
177 example = "https://mastodon.social/@USER/following"
178
179 def items(self):
180 api = MastodonAPI(self)
181 account_id = api.account_id_by_username(self.item)
182
183 for account in api.account_following(account_id):
184 account["_extractor"] = MastodonUserExtractor
185 yield Message.Queue, account["url"], account
186
187
188 class MastodonStatusExtractor(MastodonExtractor):
189 """Extractor for images from a status"""
190 subcategory = "status"
191 pattern = (BASE_PATTERN + r"/(?:@[^/?#]+|(?:users/[^/?#]+/)?"
192 r"(?:statuses|notice|objects()))/(?!following)([^/?#]+)")
193 example = "https://mastodon.social/@USER/12345"
194
195 def statuses(self):
196 if self.groups[-2] is not None:
197 url = f"{self.root}/objects/{self.item}"
198 location = self.request_location(url)
199 self.item = location.rpartition("/")[2]
200 return (MastodonAPI(self).status(self.item),)
201
202
203 class MastodonAPI():
204 """Minimal interface for the Mastodon API
205
206 https://docs.joinmastodon.org/
207 https://github.com/tootsuite/mastodon
208 """
209
210 def __init__(self, extractor):
211 self.root = extractor.root
212 self.extractor = extractor
213 self.exc = extractor.exc
214
215 access_token = extractor.config("access-token")
216 if access_token is None or access_token == "cache":
217 access_token = self.extractor.cache(
218 _access_token_cache, extractor.instance, _mem=False)
219 if not access_token:
220 access_token = extractor.config_instance("access-token")
221
222 if access_token:
223 self.headers = {"Authorization": "Bearer " + access_token}
224 else:
225 self.headers = None
226
227 def account_id_by_username(self, username):
228 if username.startswith("id:"):
229 return username[3:]
230
231 try:
232 return self.account_lookup(username)["id"]
233 except Exception:
234 # fall back to account search
235 pass
236
237 if "@" in username:
238 handle = "@" + username
239 else:
240 handle = f"@{username}@{self.extractor.instance}"
241
242 for account in self.account_search(handle, 1):
243 if account["acct"] == username:
244 self.extractor._check_moved(account)
245 return account["id"]
246 raise self.exc.NotFoundError("account")
247
248 def account_bookmarks(self):
249 """Statuses the user has bookmarked"""
250 endpoint = "/v1/bookmarks"
251 return self._pagination(endpoint, None)
252
253 def account_favorites(self):
254 """Statuses the user has favourited"""
255 endpoint = "/v1/favourites"
256 return self._pagination(endpoint, None)
257
258 def account_following(self, account_id):
259 """Accounts which the given account is following"""
260 endpoint = f"/v1/accounts/{account_id}/following"
261 return self._pagination(endpoint, None)
262
263 def account_lookup(self, username):
264 """Quickly lookup a username to see if it is available"""
265 endpoint = "/v1/accounts/lookup"
266 params = {"acct": username}
267 return self._call(endpoint, params).json()
268
269 def account_search(self, query, limit=40):
270 """Search for matching accounts by username or display name"""
271 endpoint = "/v1/accounts/search"
272 params = {"q": query, "limit": limit}
273 return self._call(endpoint, params).json()
274
275 def account_statuses(self, account_id, only_media=True,
276 exclude_replies=False):
277 """Statuses posted to the given account"""
278 endpoint = f"/v1/accounts/{account_id}/statuses"
279 params = {"only_media" : "true" if only_media else "false",
280 "exclude_replies": "true" if exclude_replies else "false"}
281 return self._pagination(endpoint, params)
282
283 def status(self, status_id):
284 """Obtain information about a status"""
285 endpoint = "/v1/statuses/" + status_id
286 return self._call(endpoint).json()
287
288 def timelines_list(self, list_id):
289 """View statuses in the given list timeline"""
290 endpoint = "/v1/timelines/list/" + list_id
291 return self._pagination(endpoint, None)
292
293 def timelines_tag(self, hashtag):
294 """View public statuses containing the given hashtag"""
295 endpoint = "/v1/timelines/tag/" + hashtag
296 return self._pagination(endpoint, None)
297
298 def _call(self, endpoint, params=None):
299 if endpoint.startswith("http"):
300 url = endpoint
301 else:
302 url = self.root + "/api" + endpoint
303
304 while True:
305 response = self.extractor.request(
306 url, params=params, headers=self.headers, fatal=None)
307 code = response.status_code
308
309 if code < 400:
310 return response
311 if code == 401:
312 raise self.exc.AbortExtraction(
313 f"Invalid or missing access token.\nRun 'gallery-dl oauth:"
314 f"mastodon:{self.extractor.instance}' to obtain one.")
315 if code == 404:
316 raise self.exc.NotFoundError()
317 if code == 429:
318 self.extractor.wait(until=self.extractor.parse_datetime_iso(
319 response.headers["x-ratelimit-reset"]))
320 continue
321 raise self.exc.AbortExtraction(response.json().get("error"))
322
323 def _pagination(self, endpoint, params):
324 url = endpoint
325 while url:
326 response = self._call(url, params)
327 yield from response.json()
328
329 url = response.links.get("next")
330 if not url:
331 return
332 url = url["url"]
333 params = None
334
335
336 def _access_token_cache(instance):
337 return None