Debian Codegraph @

gallery_dl/extractor/reddit.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017-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.reddit.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14 BASE_PATTERN = r"(?:https?://)?(?:www\.)?(?:\w+\.)?reddit\.com"
15
16
17 class RedditExtractor(Extractor):
18 """Base class for reddit extractors"""
19 category = "reddit"
20 directory_fmt = ("{category}", "{subreddit}")
21 filename_fmt = "{id}{num:? //>02} {title|link_title:[:220]}.{extension}"
22 archive_fmt = "{filename}"
23 cookies_domain = ".reddit.com"
24 request_interval = 0.6
25
26 def items(self):
27 self.api = RedditAPI(self)
28 match_submission = RedditSubmissionExtractor.pattern.match
29 match_subreddit = RedditSubredditExtractor.pattern.match
30 match_user = RedditUserExtractor.pattern.match
31
32 parentdir = self.config("parent-directory")
33 max_depth = self.config("recursion", 0)
34 previews = self.config("previews", True)
35 embeds = self.config("embeds", True)
36 pinned = self.config("pinned", True)
37
38 if videos := self.config("videos", "dash"):
39 if videos == "dash":
40 self._extract_video = self._extract_video_dash
41 elif videos == "ytdl":
42 self._extract_video = self._extract_video_ytdl
43 videos = True
44
45 selftext = self.config("selftext")
46 if selftext is None:
47 selftext = self.api.comments
48 selftext = True if selftext else False
49
50 submissions = self.submissions()
51 visited = set()
52 depth = 0
53
54 while True:
55 extra = []
56
57 for submission, comments in submissions:
58 if not pinned and (submission.get("pinned") or
59 submission.get("stickied")):
60 self.log.debug("%s: Skipping pinned submission",
61 submission.get("id"))
62 continue
63
64 urls = []
65
66 if submission and submission.get("_media", True):
67 submission["comment"] = None
68 submission["date"] = self.parse_timestamp(
69 submission["created_utc"])
70 yield Message.Directory, "", submission
71 visited.add(submission["id"])
72 submission["num"] = 0
73
74 if "crosspost_parent_list" in submission:
75 try:
76 media = submission["crosspost_parent_list"][-1]
77 except Exception:
78 media = submission
79 else:
80 media = submission
81
82 url = media["url"]
83 if url and url.startswith((
84 "https://i.redd.it/",
85 "https://preview.redd.it/",
86 )):
87 text.nameext_from_url(url, submission)
88 yield Message.Url, url, submission
89
90 elif "gallery_data" in media:
91 for url in self._extract_gallery(media):
92 submission["num"] += 1
93 text.nameext_from_url(url, submission)
94 yield Message.Url, url, submission
95
96 elif embeds and "media_metadata" in media:
97 for embed in self._extract_embed(submission, media):
98 submission["num"] += 1
99 text.nameext_from_url(embed, submission)
100 yield Message.Url, embed, submission
101
102 elif media["is_video"]:
103 if videos:
104 text.nameext_from_url(url, submission)
105 if not submission["extension"]:
106 submission["extension"] = "mp4"
107 url = "ytdl:" + self._extract_video(media)
108 yield Message.Url, url, submission
109
110 elif not url and (
111 embed := media.get("secure_media_embed")) and (
112 src := text.extr(embed.get("content", ""), 'src="', '"')): # noqa: E501
113 urls.append((src, submission))
114
115 elif not submission["is_self"]:
116 urls.append((url, submission))
117
118 if selftext and (txt := submission["selftext_html"]):
119 for url in text.extract_iter(txt, ' href="', '"'):
120 urls.append((url, submission))
121
122 elif parentdir:
123 yield Message.Directory, "", comments[0]
124
125 if self.api.comments:
126 if comments and not submission:
127 submission = comments[0]
128 submission.setdefault("num", 0)
129 if not parentdir:
130 yield Message.Directory, "", submission
131
132 for comment in comments:
133 media = (embeds and "media_metadata" in comment)
134 html = comment["body_html"] or ""
135 href = (' href="' in html)
136
137 if not media and not href:
138 continue
139
140 data = submission.copy()
141 data["comment"] = comment
142 comment["date"] = data["date"] = self.parse_timestamp(
143 comment["created_utc"])
144
145 if media:
146 for url in self._extract_embed(data, comment):
147 data["num"] += 1
148 text.nameext_from_url(url, data)
149 yield Message.Url, url, data
150 submission["num"] = data["num"]
151
152 if href:
153 for url in text.extract_iter(html, ' href="', '"'):
154 urls.append((url, data))
155
156 for url, data in urls:
157 if not url or url[0] == "#":
158 continue
159 if url[0] == "/":
160 url = "https://www.reddit.com" + url
161 if url.startswith((
162 "https://www.reddit.com/message/compose",
163 "https://reddit.com/message/compose",
164 "https://preview.redd.it/",
165 )):
166 continue
167
168 if match := match_submission(url):
169 extra.append(match[1])
170 elif not match_user(url) and not match_subreddit(url):
171 if previews and "preview" in data:
172 data["_fallback"] = self._previews(data)
173 yield Message.Queue, text.unescape(url), data
174 if "_fallback" in data:
175 del data["_fallback"]
176
177 if not extra or depth == max_depth:
178 return
179 depth += 1
180 submissions = (
181 self.api.submission(sid) for sid in extra
182 if sid not in visited
183 )
184
185 def submissions(self):
186 """Return an iterable containing all (submission, comments) tuples"""
187
188 def _extract_gallery(self, submission):
189 gallery = submission["gallery_data"]
190 if gallery is None:
191 self.log.warning("gallery %s: deleted", submission["id"])
192 return
193
194 meta = submission.get("media_metadata")
195 if meta is None:
196 self.log.warning("gallery %s: missing 'media_metadata'",
197 submission["id"])
198 return
199
200 for item in gallery["items"]:
201 data = meta[item["media_id"]]
202 if data["status"] != "valid" or "s" not in data:
203 self.log.warning(
204 "gallery %s: skipping item %s (status: %s)",
205 submission["id"], item["media_id"], data.get("status"))
206 continue
207 src = data["s"]
208 if url := src.get("u") or src.get("gif") or src.get("mp4"):
209 yield url.partition("?")[0].replace("/preview.", "/i.", 1)
210 else:
211 self.log.error(
212 "gallery %s: unable to fetch download URL for item %s",
213 submission["id"], item["media_id"])
214 self.log.debug(src)
215
216 def _extract_embed(self, submission, media):
217 meta = media["media_metadata"]
218 if not meta:
219 return
220
221 for mid, data in meta.items():
222 if data["status"] != "valid":
223 self.log.warning(
224 "embed %s: skipping item %s (status: %s)",
225 submission["id"], mid, data.get("status"))
226 continue
227
228 if src := data.get("s"):
229 if url := src.get("u") or src.get("gif") or src.get("mp4"):
230 if "//external" not in url:
231 url = url.partition("?")[0].replace(
232 "/preview.", "/i.", 1)
233 yield url
234 else:
235 self.log.error(
236 "embed %s: unable to fetch download URL for item %s",
237 submission["id"], mid)
238 self.log.debug(src)
239 elif url := data.get("dashUrl"):
240 submission["_ytdl_manifest"] = "dash"
241 yield "ytdl:" + url
242 elif url := data.get("hlsUrl"):
243 submission["_ytdl_manifest"] = "hls"
244 yield "ytdl:" + url
245
246 def _extract_video_ytdl(self, submission):
247 return "https://www.reddit.com" + submission["permalink"]
248
249 def _extract_video_dash(self, submission):
250 submission["_ytdl_extra"] = {"title": submission["title"]}
251 try:
252 url = submission["secure_media"]["reddit_video"]["dash_url"]
253 submission["_ytdl_manifest"] = "dash"
254 return url
255 except Exception:
256 return submission["url"]
257
258 def _extract_video(self, submission):
259 submission["_ytdl_extra"] = {"title": submission["title"]}
260 return submission["url"]
261
262 def _previews(self, post):
263 try:
264 if "reddit_video_preview" in post["preview"]:
265 video = post["preview"]["reddit_video_preview"]
266 if "fallback_url" in video:
267 yield video["fallback_url"]
268 if "dash_url" in video:
269 yield "ytdl:" + video["dash_url"]
270 if "hls_url" in video:
271 yield "ytdl:" + video["hls_url"]
272 except Exception as exc:
273 self.log.debug("%s: %s", exc.__class__.__name__, exc)
274
275 try:
276 for image in post["preview"]["images"]:
277 if variants := image.get("variants"):
278 if "gif" in variants:
279 yield variants["gif"]["source"]["url"]
280 if "mp4" in variants:
281 yield variants["mp4"]["source"]["url"]
282 yield image["source"]["url"]
283 except Exception as exc:
284 self.log.debug("%s: %s", exc.__class__.__name__, exc)
285
286
287 class RedditSubredditExtractor(RedditExtractor):
288 """Extractor for URLs from subreddits on reddit.com"""
289 subcategory = "subreddit"
290 pattern = (BASE_PATTERN +
291 r"(/r/[^/?#]+(?:/([a-z]+))?)/?(?:\?([^#]*))?(?:$|#)")
292 example = "https://www.reddit.com/r/SUBREDDIT/"
293
294 def __init__(self, match):
295 if sub := match[2]:
296 self.subcategory += "-" + sub
297 RedditExtractor.__init__(self, match)
298
299 def submissions(self):
300 subreddit, sub, query = self.groups
301 params = text.parse_query(query)
302 if sub == "search":
303 self.kwdict["search_tags"] = params.get("q", "")
304 if "restrict_sr" not in params:
305 params["restrict_sr"] = "1"
306 return self.api.submissions_subreddit(subreddit, params)
307
308
309 class RedditHomeExtractor(RedditSubredditExtractor):
310 """Extractor for submissions from your home feed on reddit.com"""
311 subcategory = "home"
312 pattern = BASE_PATTERN + r"((?:/([a-z]+))?)/?(?:\?([^#]*))?(?:$|#)"
313 example = "https://www.reddit.com/"
314
315
316 class RedditUserExtractor(RedditExtractor):
317 """Extractor for URLs from posts by a reddit user"""
318 subcategory = "user"
319 directory_fmt = ("{category}", "Users", "{user[name]}")
320 pattern = (BASE_PATTERN +
321 r"/u(?:ser)?/([^/?#]+)(/[a-z]+)?/?(?:\?([^#]*))?$")
322 example = "https://www.reddit.com/user/USER/"
323
324 def __init__(self, match):
325 if sub := match[2]:
326 self.subcategory += "-" + sub[1:]
327 RedditExtractor.__init__(self, match)
328
329 def submissions(self):
330 username, sub, qs = self.groups
331 username = text.unquote(username)
332 self.kwdict["user"] = user = self.api.user_about(username)
333
334 submissions = self.api.submissions_user(
335 (user.get("name") or username) + (sub or ""), text.parse_query(qs))
336 only = sub not in {"/upvoted", "/downvoted", "/saved"}
337 if self.config("only", only):
338 submissions = self._only(submissions, user)
339 return submissions
340
341 def _only(self, submissions, user):
342 try:
343 uid = "t2_" + user["id"]
344 except Exception:
345 if user.get("is_suspended"):
346 raise self.exc.NotFoundError("Suspended User", False)
347 raise self.exc.NotFoundError("user")
348 for submission, comments in submissions:
349 if submission and submission.get("author_fullname") != uid:
350 submission["_media"] = False
351 comments = [
352 comment
353 for comment in (comments or ())
354 if comment.get("author_fullname") == uid
355 ]
356 if submission or comments:
357 yield submission, comments
358
359
360 class RedditSubmissionExtractor(RedditExtractor):
361 """Extractor for URLs from a submission on reddit.com"""
362 subcategory = "submission"
363 pattern = (r"(?:https?://)?(?:"
364 r"(?:www\.)?(?:\w+\.)?reddit\.com/(?:(?:(?:r|u|user)/[^/?#]+/)?"
365 r"comments|gallery)|redd\.it)/([a-z0-9]+)")
366 example = "https://www.reddit.com/r/SUBREDDIT/comments/id/"
367
368 def submissions(self):
369 return (self.api.submission(self.groups[0]),)
370
371
372 class RedditImageExtractor(Extractor):
373 """Extractor for reddit-hosted images"""
374 category = "reddit"
375 subcategory = "image"
376 archive_fmt = "{filename}"
377 pattern = (r"(?:https?://)?((?:i|preview)\.redd\.it|i\.reddituploads\.com)"
378 r"/([^/?#]+)(\?[^#]*)?")
379 example = "https://i.redd.it/NAME.EXT"
380
381 def __init__(self, match):
382 Extractor.__init__(self, match)
383 domain = match[1]
384 self.path = match[2]
385 if domain == "preview.redd.it":
386 self.domain = "i.redd.it"
387 self.query = ""
388 else:
389 self.domain = domain
390 self.query = match[3] or ""
391
392 def items(self):
393 url = f"https://{self.domain}/{self.path}{self.query}"
394 data = text.nameext_from_url(url)
395 yield Message.Directory, "", data
396 yield Message.Url, url, data
397
398
399 class RedditRedirectExtractor(Extractor):
400 """Extractor for personalized share URLs produced by the mobile app"""
401 category = "reddit"
402 subcategory = "redirect"
403 pattern = BASE_PATTERN + r"/(?:(r|u|user)/([^/?#]+))/s/([a-zA-Z0-9]{10})"
404 example = "https://www.reddit.com/r/SUBREDDIT/s/abc456GHIJ"
405
406 def items(self):
407 sub_type, subreddit, share_url = self.groups
408 if sub_type == "u":
409 sub_type = "user"
410 url = f"https://www.reddit.com/{sub_type}/{subreddit}/s/{share_url}"
411 location = self.request_location(url, notfound="submission")
412 data = {"_extractor": RedditSubmissionExtractor}
413 yield Message.Queue, location, data
414
415
416 class RedditAPI():
417 """Interface for the Reddit API
418
419 Ref: https://www.reddit.com/dev/api/
420 """
421 ROOT = "https://oauth.reddit.com"
422 CLIENT_ID = "6N9uN0krSDE-ig"
423 USER_AGENT = "Python:gallery-dl:0.8.4 (by /u/mikf1)"
424
425 def __init__(self, extractor):
426 self.extractor = extractor
427 self.log = extractor.log
428
429 config = extractor.config
430
431 self.comments = text.parse_int(config("comments", 0))
432 self.morecomments = config("morecomments", False)
433 self._warn_429 = False
434
435 client_id = config("client-id")
436 if config("api") == "rest" or not client_id:
437 self.root = "https://www.reddit.com"
438 self.headers = None
439 self.authenticate = util.noop
440 self.log.debug("Using REST API")
441 else:
442 self.root = self.ROOT
443
444 if client_id is None or client_id == self.CLIENT_ID:
445 self.client_id = client_id = self.CLIENT_ID
446 self.headers = {"User-Agent": self.USER_AGENT}
447 self._warn_429 = True
448 kind = "default"
449 else:
450 self.client_id = client_id
451 self.headers = {"User-Agent": (config("user-agent-oauth") or
452 config("user-agent"))}
453 client_id = client_id[:5] + "*" * (len(client_id)-5)
454 kind = "custom"
455
456 self.log.debug(
457 "Using OAuth API with %s credentials (client-id %s)",
458 kind, client_id)
459
460 token = config("refresh-token")
461 if token is None or token == "cache":
462 self.refresh_token = extractor.cache(
463 _refresh_token_cache, "#"+self.client_id, _mem=False)
464 else:
465 self.refresh_token = token
466
467 if not self.refresh_token:
468 # allow downloading from quarantined subreddits (#2180)
469 extractor.cookies.set(
470 "_options", '%7B%22pref_quarantine_optin%22%3A%20true%7D',
471 domain=extractor.cookies_domain)
472
473 def submission(self, submission_id):
474 """Fetch the (submission, comments)=-tuple for a submission id"""
475 endpoint = "/comments/" + submission_id + "/.json"
476 link_id = "t3_" + submission_id if self.morecomments else None
477 submission, comments = self._call(endpoint, {"limit": self.comments})
478 return (submission["data"]["children"][0]["data"],
479 self._flatten(comments, link_id) if self.comments else ())
480
481 def submissions_subreddit(self, subreddit, params):
482 """Collect all (submission, comments)-tuples of a subreddit"""
483 endpoint = subreddit + "/.json"
484 return self._pagination(endpoint, params)
485
486 def submissions_user(self, username, params):
487 """Collect all (submission, comments)-tuples posted by a user"""
488 endpoint = f"/user/{username}/.json"
489 return self._pagination(endpoint, params)
490
491 def morechildren(self, link_id, children):
492 """Load additional comments from a submission"""
493 endpoint = "/api/morechildren"
494 params = {"link_id": link_id, "api_type": "json"}
495 index, done = 0, False
496 while not done:
497 if len(children) - index < 100:
498 done = True
499 params["children"] = ",".join(children[index:index + 100])
500 index += 100
501
502 data = self._call(endpoint, params)["json"]
503 for thing in data["data"]["things"]:
504 if thing["kind"] == "more":
505 if more := thing["data"].get("children"):
506 children.extend(more)
507 else:
508 yield thing["data"]
509
510 def user_about(self, username):
511 endpoint = f"/user/{username}/about.json"
512 return self._call(endpoint, {})["data"]
513
514 def authenticate(self):
515 """Authenticate the application by requesting an access token"""
516 self.headers["Authorization"] = self.extractor.cache(
517 self._authenticate_impl, self.refresh_token, _exp=3600, _mem=False)
518
519 def _authenticate_impl(self, refresh_token=None):
520 """Actual authenticate implementation"""
521 url = "https://www.reddit.com/api/v1/access_token"
522 self.headers["Authorization"] = None
523
524 if refresh_token:
525 self.log.info("Refreshing private access token")
526 data = {"grant_type": "refresh_token",
527 "refresh_token": refresh_token}
528 else:
529 self.log.info("Requesting public access token")
530 data = {"grant_type": ("https://oauth.reddit.com/"
531 "grants/installed_client"),
532 "device_id": "DO_NOT_TRACK_THIS_DEVICE"}
533
534 auth = util.HTTPBasicAuth(self.client_id, "")
535 response = self.extractor.request(
536 url, method="POST", headers=self.headers,
537 data=data, auth=auth, fatal=False)
538 data = response.json()
539
540 if response.status_code != 200:
541 self.log.debug("Server response: %s", data)
542 raise self.extractor.exc.AuthenticationError(
543 f"\"{data.get('error')}: {data.get('message')}\"")
544 return "Bearer " + data["access_token"]
545
546 def _call(self, endpoint, params):
547 url = self.root + endpoint
548 params["raw_json"] = "1"
549
550 while True:
551 self.authenticate()
552 response = self.extractor.request(
553 url, params=params, headers=self.headers, fatal=None)
554
555 remaining = response.headers.get("x-ratelimit-remaining")
556 if remaining and float(remaining) < 2:
557 self.log.warning("API rate limit exceeded")
558 if self._warn_429 and self.client_id == self.CLIENT_ID:
559 self.log.info(
560 "Register your own OAuth application and use its "
561 "credentials to prevent this error: "
562 "https://gdl-org.github.io/docs/configuration.html"
563 "#extractor-reddit-client-id-user-agent")
564 self._warn_429 = False
565 self.extractor.wait(
566 seconds=response.headers["x-ratelimit-reset"])
567 continue
568
569 try:
570 data = response.json()
571 except ValueError:
572 raise self.extractor.exc.AbortExtraction(
573 text.remove_html(response.text))
574
575 if "error" in data:
576 exc = self.extractor.exc
577 if data["error"] == 403:
578 raise exc.AuthorizationError()
579 if data["error"] == 404:
580 raise exc.NotFoundError(self.extractor.subcategory)
581 self.log.debug(data)
582 raise exc.AbortExtraction(data.get("message"))
583 return data
584
585 def _pagination(self, endpoint, params):
586 id_min = self._parse_id("id-min", 0)
587 id_max = self._parse_id("id-max", float("inf"))
588 if id_max == 2147483647:
589 self.log.debug("Ignoring 'id-max' setting \"zik0zj\"")
590 id_max = float("inf")
591 date_min, date_max = self.extractor._get_date_min_max(0, 253402210800)
592
593 if limit := self.extractor.config("limit"):
594 params["limit"] = limit
595
596 while True:
597 data = self._call(endpoint, params)["data"]
598
599 for child in data["children"]:
600 kind = child["kind"]
601 post = child["data"]
602
603 if (date_min <= post["created_utc"] <= date_max and
604 id_min <= util.b36decode(post["id"]) <= id_max):
605
606 if kind == "t3":
607 if post["num_comments"] and self.comments:
608 try:
609 yield self.submission(post["id"])
610 except self.extractor.exc.AuthorizationError:
611 pass
612 else:
613 yield post, ()
614
615 elif kind == "t1" and self.comments:
616 yield None, (post,)
617
618 if not data["after"]:
619 return
620 params["after"] = data["after"]
621
622 def _flatten(self, comments, link_id=None):
623 extra = []
624 queue = comments["data"]["children"]
625 while queue:
626 comment = queue.pop(0)
627 if comment["kind"] == "more":
628 if link_id:
629 extra.extend(comment["data"]["children"])
630 continue
631 comment = comment["data"]
632 yield comment
633 if comment["replies"]:
634 queue += comment["replies"]["data"]["children"]
635 if link_id and extra:
636 yield from self.morechildren(link_id, extra)
637
638 def _parse_id(self, key, default):
639 sid = self.extractor.config(key)
640 return util.b36decode(
641 sid.rpartition("_")[2].lower()) if sid else default
642
643
644 def _refresh_token_cache(token):
645 if token and token[0] == "#":
646 return None
647 return token