Debian Codegraph @

gallery_dl/extractor/reddit.py

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