]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/reddit.py
[test/download] Fallback test to `bv`
[yt-dlp.git] / yt_dlp / extractor / reddit.py
CommitLineData
8e3fd7e0 1import random
9bb2c767 2
0c43a481
S
3from .common import InfoExtractor
4from ..utils import (
5 ExtractorError,
6 int_or_none,
7 float_or_none,
29f7c58a 8 try_get,
9 unescapeHTML,
97abf05a 10 url_or_none,
0c43a481
S
11)
12
13
14class RedditIE(InfoExtractor):
15 _VALID_URL = r'https?://v\.redd\.it/(?P<id>[^/?#&]+)'
16 _TEST = {
17 # from https://www.reddit.com/r/videos/comments/6rrwyj/that_small_heart_attack/
18 'url': 'https://v.redd.it/zv89llsvexdz',
8315ee6c 19 'md5': '0a070c53eba7ec4534d95a5a1259e253',
0c43a481
S
20 'info_dict': {
21 'id': 'zv89llsvexdz',
22 'ext': 'mp4',
23 'title': 'zv89llsvexdz',
24 },
0c43a481
S
25 }
26
27 def _real_extract(self, url):
28 video_id = self._match_id(url)
29
30 formats = self._extract_m3u8_formats(
31 'https://v.redd.it/%s/HLSPlaylist.m3u8' % video_id, video_id,
32 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)
33
34 formats.extend(self._extract_mpd_formats(
35 'https://v.redd.it/%s/DASHPlaylist.mpd' % video_id, video_id,
36 mpd_id='dash', fatal=False))
37
54f37eea 38 self._sort_formats(formats)
665f42d8 39
0c43a481
S
40 return {
41 'id': video_id,
42 'title': video_id,
43 'formats': formats,
44 }
45
46
47class RedditRIE(InfoExtractor):
8e3fd7e0 48 _VALID_URL = r'https?://(?P<subdomain>[^/]+\.)?reddit(?:media)?\.com/r/(?P<slug>[^/]+/comments/(?P<id>[^/?#&]+))'
0c43a481
S
49 _TESTS = [{
50 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj/that_small_heart_attack/',
51 'info_dict': {
52 'id': 'zv89llsvexdz',
53 'ext': 'mp4',
54 'title': 'That small heart attack.',
29f7c58a 55 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
56 'thumbnails': 'count:4',
0c43a481
S
57 'timestamp': 1501941939,
58 'upload_date': '20170805',
59 'uploader': 'Antw87',
29f7c58a 60 'duration': 12,
0c43a481
S
61 'like_count': int,
62 'dislike_count': int,
63 'comment_count': int,
64 'age_limit': 0,
65 },
66 'params': {
0c43a481
S
67 'skip_download': True,
68 },
69 }, {
70 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj',
71 'only_matching': True,
72 }, {
73 # imgur
74 'url': 'https://www.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
75 'only_matching': True,
12b0d4e0
M
76 }, {
77 # imgur @ old reddit
78 'url': 'https://old.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
79 'only_matching': True,
0c43a481
S
80 }, {
81 # streamable
82 'url': 'https://www.reddit.com/r/videos/comments/6t7sg9/comedians_hilarious_joke_about_the_guam_flag/',
83 'only_matching': True,
84 }, {
85 # youtube
86 'url': 'https://www.reddit.com/r/videos/comments/6t75wq/southern_man_tries_to_speak_without_an_accent/',
87 'only_matching': True,
dbd5c502 88 }, {
89 # reddit video @ nm reddit
90 'url': 'https://nm.reddit.com/r/Cricket/comments/8idvby/lousy_cameraman_finds_himself_in_cairns_line_of/',
91 'only_matching': True,
c470901c 92 }, {
93 'url': 'https://www.redditmedia.com/r/serbia/comments/pu9wbx/ako_vu%C4%8Di%C4%87_izgubi_izbore_ja_%C4%87u_da_crknem/',
94 'only_matching': True,
0c43a481
S
95 }]
96
8e3fd7e0 97 @staticmethod
98 def _gen_session_id():
99 id_length = 16
100 rand_max = 1 << (id_length * 4)
101 return '%0.*x' % (id_length, random.randrange(rand_max))
0c43a481 102
8e3fd7e0 103 def _real_extract(self, url):
104 subdomain, slug, video_id = self._match_valid_url(url).group('subdomain', 'slug', 'id')
105
106 self._set_cookie('.reddit.com', 'reddit_session', self._gen_session_id())
107 self._set_cookie('.reddit.com', '_options', '%7B%22pref_quarantine_optin%22%3A%20true%7D')
1b6bb4a8 108 data = self._download_json(f'https://{subdomain}reddit.com/r/{slug}/.json', video_id, fatal=False)
8e3fd7e0 109 if not data:
110 # Fall back to old.reddit.com in case the requested subdomain fails
111 data = self._download_json(f'https://old.reddit.com/r/{slug}/.json', video_id)
112 data = data[0]['data']['children'][0]['data']
0c43a481
S
113 video_url = data['url']
114
115 # Avoid recursing into the same reddit URL
116 if 'reddit.com/' in video_url and '/%s/' % video_id in video_url:
117 raise ExtractorError('No media found', expected=True)
118
119 over_18 = data.get('over_18')
120 if over_18 is True:
121 age_limit = 18
122 elif over_18 is False:
123 age_limit = 0
124 else:
125 age_limit = None
126
29f7c58a 127 thumbnails = []
128
129 def add_thumbnail(src):
130 if not isinstance(src, dict):
131 return
132 thumbnail_url = url_or_none(src.get('url'))
133 if not thumbnail_url:
134 return
135 thumbnails.append({
136 'url': unescapeHTML(thumbnail_url),
137 'width': int_or_none(src.get('width')),
138 'height': int_or_none(src.get('height')),
139 })
140
141 for image in try_get(data, lambda x: x['preview']['images']) or []:
142 if not isinstance(image, dict):
143 continue
144 add_thumbnail(image.get('source'))
145 resolutions = image.get('resolutions')
146 if isinstance(resolutions, list):
147 for resolution in resolutions:
148 add_thumbnail(resolution)
149
0c43a481
S
150 return {
151 '_type': 'url_transparent',
152 'url': video_url,
153 'title': data.get('title'),
29f7c58a 154 'thumbnails': thumbnails,
0c43a481
S
155 'timestamp': float_or_none(data.get('created_utc')),
156 'uploader': data.get('author'),
29f7c58a 157 'duration': int_or_none(try_get(
158 data,
159 (lambda x: x['media']['reddit_video']['duration'],
160 lambda x: x['secure_media']['reddit_video']['duration']))),
0c43a481
S
161 'like_count': int_or_none(data.get('ups')),
162 'dislike_count': int_or_none(data.get('downs')),
163 'comment_count': int_or_none(data.get('num_comments')),
164 'age_limit': age_limit,
165 }