]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/reddit.py
[extractor/GoPlay] Use new API (#6151)
[yt-dlp.git] / yt_dlp / extractor / reddit.py
CommitLineData
8e3fd7e0 1import random
0e96b408 2import urllib.parse
9bb2c767 3
0c43a481
S
4from .common import InfoExtractor
5from ..utils import (
6 ExtractorError,
0c43a481 7 float_or_none,
0e96b408 8 int_or_none,
9 traverse_obj,
29f7c58a 10 try_get,
11 unescapeHTML,
97abf05a 12 url_or_none,
0c43a481
S
13)
14
15
16class RedditIE(InfoExtractor):
8e3fd7e0 17 _VALID_URL = r'https?://(?P<subdomain>[^/]+\.)?reddit(?:media)?\.com/r/(?P<slug>[^/]+/comments/(?P<id>[^/?#&]+))'
0c43a481
S
18 _TESTS = [{
19 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj/that_small_heart_attack/',
20 'info_dict': {
21 'id': 'zv89llsvexdz',
22 'ext': 'mp4',
07689fc1 23 'display_id': '6rrwyj',
0c43a481 24 'title': 'That small heart attack.',
29f7c58a 25 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
26 'thumbnails': 'count:4',
0c43a481
S
27 'timestamp': 1501941939,
28 'upload_date': '20170805',
29 'uploader': 'Antw87',
29f7c58a 30 'duration': 12,
0c43a481
S
31 'like_count': int,
32 'dislike_count': int,
33 'comment_count': int,
34 'age_limit': 0,
84e0e33a 35 'channel_id': 'videos',
0c43a481
S
36 },
37 'params': {
0c43a481
S
38 'skip_download': True,
39 },
2e565f5b 40 }, {
41 # 1080p fallback format
42 'url': 'https://www.reddit.com/r/aww/comments/90bu6w/heat_index_was_110_degrees_so_we_offered_him_a/',
43 'md5': '8b5902cfda3006bf90faea7adf765a49',
44 'info_dict': {
45 'id': 'gyh95hiqc0b11',
46 'ext': 'mp4',
47 'display_id': '90bu6w',
48 'title': 'Heat index was 110 degrees so we offered him a cold drink. He went for a full body soak instead',
49 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
50 'thumbnails': 'count:7',
51 'timestamp': 1532051078,
52 'upload_date': '20180720',
53 'uploader': 'FootLoosePickleJuice',
54 'duration': 14,
55 'like_count': int,
56 'dislike_count': int,
57 'comment_count': int,
58 'age_limit': 0,
84e0e33a 59 'channel_id': 'aww',
2e565f5b 60 },
0e96b408 61 }, {
62 # videos embedded in reddit text post
63 'url': 'https://www.reddit.com/r/KamenRider/comments/wzqkxp/finale_kamen_rider_revice_episode_50_family_to/',
64 'playlist_count': 2,
65 'info_dict': {
66 'id': 'wzqkxp',
67 'title': 'md5:72d3d19402aa11eff5bd32fc96369b37',
68 },
1fc08914 69 }, {
70 # crossposted reddit-hosted media
71 'url': 'https://www.reddit.com/r/dumbfuckers_club/comments/zjjw82/cringe/',
72 'md5': '746180895c7b75a9d6b05341f507699a',
73 'info_dict': {
74 'id': 'a1oneun6pa5a1',
75 'ext': 'mp4',
76 'display_id': 'zjjw82',
77 'title': 'Cringe',
78 'uploader': 'Otaku-senpai69420',
79 'thumbnail': r're:^https?://.*\.(?:jpg|png)',
80 'upload_date': '20221212',
81 'timestamp': 1670812309,
82 'duration': 16,
83 'like_count': int,
84 'dislike_count': int,
85 'comment_count': int,
86 'age_limit': 0,
87 },
0c43a481
S
88 }, {
89 'url': 'https://www.reddit.com/r/videos/comments/6rrwyj',
90 'only_matching': True,
91 }, {
92 # imgur
93 'url': 'https://www.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
94 'only_matching': True,
12b0d4e0
M
95 }, {
96 # imgur @ old reddit
97 'url': 'https://old.reddit.com/r/MadeMeSmile/comments/6t7wi5/wait_for_it/',
98 'only_matching': True,
0c43a481
S
99 }, {
100 # streamable
101 'url': 'https://www.reddit.com/r/videos/comments/6t7sg9/comedians_hilarious_joke_about_the_guam_flag/',
102 'only_matching': True,
103 }, {
104 # youtube
105 'url': 'https://www.reddit.com/r/videos/comments/6t75wq/southern_man_tries_to_speak_without_an_accent/',
106 'only_matching': True,
dbd5c502 107 }, {
108 # reddit video @ nm reddit
109 'url': 'https://nm.reddit.com/r/Cricket/comments/8idvby/lousy_cameraman_finds_himself_in_cairns_line_of/',
110 'only_matching': True,
c470901c 111 }, {
112 'url': 'https://www.redditmedia.com/r/serbia/comments/pu9wbx/ako_vu%C4%8Di%C4%87_izgubi_izbore_ja_%C4%87u_da_crknem/',
113 'only_matching': True,
0c43a481
S
114 }]
115
8e3fd7e0 116 @staticmethod
117 def _gen_session_id():
118 id_length = 16
119 rand_max = 1 << (id_length * 4)
120 return '%0.*x' % (id_length, random.randrange(rand_max))
0c43a481 121
8e3fd7e0 122 def _real_extract(self, url):
123 subdomain, slug, video_id = self._match_valid_url(url).group('subdomain', 'slug', 'id')
124
125 self._set_cookie('.reddit.com', 'reddit_session', self._gen_session_id())
126 self._set_cookie('.reddit.com', '_options', '%7B%22pref_quarantine_optin%22%3A%20true%7D')
1b6bb4a8 127 data = self._download_json(f'https://{subdomain}reddit.com/r/{slug}/.json', video_id, fatal=False)
8e3fd7e0 128 if not data:
129 # Fall back to old.reddit.com in case the requested subdomain fails
130 data = self._download_json(f'https://old.reddit.com/r/{slug}/.json', video_id)
131 data = data[0]['data']['children'][0]['data']
0c43a481
S
132 video_url = data['url']
133
0c43a481
S
134 over_18 = data.get('over_18')
135 if over_18 is True:
136 age_limit = 18
137 elif over_18 is False:
138 age_limit = 0
139 else:
140 age_limit = None
141
29f7c58a 142 thumbnails = []
143
144 def add_thumbnail(src):
145 if not isinstance(src, dict):
146 return
147 thumbnail_url = url_or_none(src.get('url'))
148 if not thumbnail_url:
149 return
150 thumbnails.append({
151 'url': unescapeHTML(thumbnail_url),
152 'width': int_or_none(src.get('width')),
153 'height': int_or_none(src.get('height')),
154 })
155
156 for image in try_get(data, lambda x: x['preview']['images']) or []:
157 if not isinstance(image, dict):
158 continue
159 add_thumbnail(image.get('source'))
160 resolutions = image.get('resolutions')
161 if isinstance(resolutions, list):
162 for resolution in resolutions:
163 add_thumbnail(resolution)
164
e16fefd8 165 info = {
0c43a481 166 'title': data.get('title'),
29f7c58a 167 'thumbnails': thumbnails,
0c43a481
S
168 'timestamp': float_or_none(data.get('created_utc')),
169 'uploader': data.get('author'),
84e0e33a 170 'channel_id': data.get('subreddit'),
0c43a481
S
171 'like_count': int_or_none(data.get('ups')),
172 'dislike_count': int_or_none(data.get('downs')),
173 'comment_count': int_or_none(data.get('num_comments')),
174 'age_limit': age_limit,
175 }
e16fefd8 176
0e96b408 177 parsed_url = urllib.parse.urlparse(video_url)
178
179 # Check for embeds in text posts, or else raise to avoid recursing into the same reddit URL
180 if 'reddit.com' in parsed_url.netloc and f'/{video_id}/' in parsed_url.path:
181 entries = []
182 for media in traverse_obj(data, ('media_metadata', ...), expected_type=dict):
183 if not media.get('id') or media.get('e') != 'RedditVideo':
184 continue
185 formats = []
186 if media.get('hlsUrl'):
187 formats.extend(self._extract_m3u8_formats(
188 unescapeHTML(media['hlsUrl']), video_id, 'mp4', m3u8_id='hls', fatal=False))
189 if media.get('dashUrl'):
190 formats.extend(self._extract_mpd_formats(
191 unescapeHTML(media['dashUrl']), video_id, mpd_id='dash', fatal=False))
192 if formats:
193 entries.append({
194 'id': media['id'],
195 'display_id': video_id,
196 'formats': formats,
197 **info,
198 })
199 if entries:
200 return self.playlist_result(entries, video_id, info.get('title'))
201 raise ExtractorError('No media found', expected=True)
202
e16fefd8 203 # Check if media is hosted on reddit:
1fc08914 204 reddit_video = traverse_obj(data, (
205 (None, ('crosspost_parent_list', ...)), ('secure_media', 'media'), 'reddit_video'), get_all=False)
e16fefd8
JL
206 if reddit_video:
207 playlist_urls = [
208 try_get(reddit_video, lambda x: unescapeHTML(x[y]))
209 for y in ('dash_url', 'hls_url')
210 ]
211
212 # Update video_id
213 display_id = video_id
214 video_id = self._search_regex(
215 r'https?://v\.redd\.it/(?P<id>[^/?#&]+)', reddit_video['fallback_url'],
216 'video_id', default=display_id)
217
218 dash_playlist_url = playlist_urls[0] or f'https://v.redd.it/{video_id}/DASHPlaylist.mpd'
219 hls_playlist_url = playlist_urls[1] or f'https://v.redd.it/{video_id}/HLSPlaylist.m3u8'
220
2e565f5b 221 formats = [{
222 'url': unescapeHTML(reddit_video['fallback_url']),
223 'height': int_or_none(reddit_video.get('height')),
224 'width': int_or_none(reddit_video.get('width')),
225 'tbr': int_or_none(reddit_video.get('bitrate_kbps')),
226 'acodec': 'none',
02b2f9fa 227 'vcodec': 'h264',
2e565f5b 228 'ext': 'mp4',
229 'format_id': 'fallback',
230 'format_note': 'DASH video, mp4_dash',
231 }]
232 formats.extend(self._extract_m3u8_formats(
233 hls_playlist_url, display_id, 'mp4', m3u8_id='hls', fatal=False))
e16fefd8
JL
234 formats.extend(self._extract_mpd_formats(
235 dash_playlist_url, display_id, mpd_id='dash', fatal=False))
e16fefd8
JL
236
237 return {
238 **info,
239 'id': video_id,
240 'display_id': display_id,
241 'formats': formats,
242 'duration': int_or_none(reddit_video.get('duration')),
243 }
244
07689fc1 245 if parsed_url.netloc == 'v.redd.it':
246 self.raise_no_formats('This video is processing', expected=True, video_id=video_id)
247 return {
248 **info,
249 'id': parsed_url.path.split('/')[1],
250 'display_id': video_id,
251 }
252
e16fefd8
JL
253 # Not hosted on reddit, must continue extraction
254 return {
255 **info,
256 'display_id': video_id,
257 '_type': 'url_transparent',
258 'url': video_url,
259 }