]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/imgur.py
[ie/matchtv] Fix extractor (#10190)
[yt-dlp.git] / yt_dlp / extractor / imgur.py
1 import functools
2 import re
3
4 from .common import InfoExtractor
5 from ..utils import (
6 ExtractorError,
7 determine_ext,
8 float_or_none,
9 int_or_none,
10 js_to_json,
11 mimetype2ext,
12 parse_iso8601,
13 str_or_none,
14 strip_or_none,
15 traverse_obj,
16 url_or_none,
17 )
18
19
20 class ImgurBaseIE(InfoExtractor):
21 _CLIENT_ID = '546c25a59c58ad7'
22
23 @classmethod
24 def _imgur_result(cls, item_id):
25 return cls.url_result(f'https://imgur.com/{item_id}', ImgurIE, item_id)
26
27 def _call_api(self, endpoint, video_id, **kwargs):
28 return self._download_json(
29 f'https://api.imgur.com/post/v1/{endpoint}/{video_id}?client_id={self._CLIENT_ID}&include=media,account',
30 video_id, **kwargs)
31
32 @staticmethod
33 def get_description(s):
34 if 'Discover the magic of the internet at Imgur' in s:
35 return None
36 return s or None
37
38
39 class ImgurIE(ImgurBaseIE):
40 _VALID_URL = r'https?://(?:i\.)?imgur\.com/(?!(?:a|gallery|t|topic|r)/)(?P<id>[a-zA-Z0-9]+)'
41
42 _TESTS = [{
43 'url': 'https://imgur.com/A61SaA1',
44 'info_dict': {
45 'id': 'A61SaA1',
46 'ext': 'mp4',
47 'title': 'MRW gifv is up and running without any bugs',
48 'timestamp': 1416446068,
49 'upload_date': '20141120',
50 'dislike_count': int,
51 'comment_count': int,
52 'release_timestamp': 1416446068,
53 'release_date': '20141120',
54 'like_count': int,
55 'thumbnail': 'https://i.imgur.com/A61SaA1h.jpg',
56 },
57 }, {
58 'url': 'https://i.imgur.com/A61SaA1.gifv',
59 'only_matching': True,
60 }, {
61 'url': 'https://i.imgur.com/crGpqCV.mp4',
62 'only_matching': True,
63 }, {
64 'url': 'https://i.imgur.com/jxBXAMC.gifv',
65 'info_dict': {
66 'id': 'jxBXAMC',
67 'ext': 'mp4',
68 'title': 'Fahaka puffer feeding',
69 'timestamp': 1533835503,
70 'upload_date': '20180809',
71 'release_date': '20180809',
72 'like_count': int,
73 'duration': 30.0,
74 'comment_count': int,
75 'release_timestamp': 1533835503,
76 'thumbnail': 'https://i.imgur.com/jxBXAMCh.jpg',
77 'dislike_count': int,
78 },
79 }, {
80 # needs Accept header, ref: https://github.com/yt-dlp/yt-dlp/issues/9458
81 'url': 'https://imgur.com/zV03bd5',
82 'md5': '59df97884e8ba76143ff6b640a0e2904',
83 'info_dict': {
84 'id': 'zV03bd5',
85 'ext': 'mp4',
86 'title': 'Ive - Liz',
87 'timestamp': 1710491255,
88 'upload_date': '20240315',
89 'like_count': int,
90 'dislike_count': int,
91 'duration': 56.92,
92 'comment_count': int,
93 'release_timestamp': 1710491255,
94 'release_date': '20240315',
95 },
96 }]
97
98 def _real_extract(self, url):
99 video_id = self._match_id(url)
100 data = self._call_api('media', video_id)
101 if not traverse_obj(data, ('media', 0, (
102 ('type', {lambda t: t == 'video' or None}),
103 ('metadata', 'is_animated'))), get_all=False):
104 raise ExtractorError(f'{video_id} is not a video or animated image', expected=True)
105 webpage = self._download_webpage(
106 f'https://i.imgur.com/{video_id}.gifv', video_id, fatal=False) or ''
107 formats = []
108
109 media_fmt = traverse_obj(data, ('media', 0, {
110 'url': ('url', {url_or_none}),
111 'ext': ('ext', {str}),
112 'width': ('width', {int_or_none}),
113 'height': ('height', {int_or_none}),
114 'filesize': ('size', {int_or_none}),
115 'acodec': ('metadata', 'has_sound', {lambda b: None if b else 'none'}),
116 }))
117 media_url = media_fmt.get('url')
118 if media_url:
119 if not media_fmt.get('ext'):
120 media_fmt['ext'] = mimetype2ext(traverse_obj(
121 data, ('media', 0, 'mime_type'))) or determine_ext(media_url)
122 if traverse_obj(data, ('media', 0, 'type')) == 'image':
123 media_fmt['acodec'] = 'none'
124 media_fmt.setdefault('preference', -10)
125 formats.append(media_fmt)
126
127 video_elements = self._search_regex(
128 r'(?s)<div class="video-elements">(.*?)</div>',
129 webpage, 'video elements', default=None)
130
131 if video_elements:
132 def og_get_size(media_type):
133 return {
134 p: int_or_none(self._og_search_property(f'{media_type}:{p}', webpage, default=None))
135 for p in ('width', 'height')
136 }
137
138 size = og_get_size('video')
139 if not any(size.values()):
140 size = og_get_size('image')
141
142 formats = traverse_obj(
143 re.finditer(r'<source\s+src="(?P<src>[^"]+)"\s+type="(?P<type>[^"]+)"', video_elements),
144 (..., {
145 'format_id': ('type', {lambda s: s.partition('/')[2]}),
146 'url': ('src', {self._proto_relative_url}),
147 'ext': ('type', {mimetype2ext}),
148 }))
149 for f in formats:
150 f.update(size)
151
152 # We can get the original gif format from the webpage as well
153 gif_json = traverse_obj(self._search_json(
154 r'var\s+videoItem\s*=', webpage, 'GIF info', video_id,
155 transform_source=js_to_json, fatal=False), {
156 'url': ('gifUrl', {self._proto_relative_url}),
157 'filesize': ('size', {int_or_none}),
158 })
159 if gif_json:
160 gif_json.update(size)
161 gif_json.update({
162 'format_id': 'gif',
163 'preference': -10, # gifs < videos
164 'ext': 'gif',
165 'acodec': 'none',
166 'vcodec': 'gif',
167 'container': 'gif',
168 })
169 formats.append(gif_json)
170
171 search = functools.partial(self._html_search_meta, html=webpage, default=None)
172
173 twitter_fmt = {
174 'format_id': 'twitter',
175 'url': url_or_none(search('twitter:player:stream')),
176 'ext': mimetype2ext(search('twitter:player:stream:content_type')),
177 'width': int_or_none(search('twitter:width')),
178 'height': int_or_none(search('twitter:height')),
179 }
180 if twitter_fmt['url']:
181 formats.append(twitter_fmt)
182
183 if not formats:
184 self.raise_no_formats(
185 f'No sources found for video {video_id}. Maybe a plain image?', expected=True)
186 self._remove_duplicate_formats(formats)
187
188 return {
189 'title': self._og_search_title(webpage, default=None),
190 'description': self.get_description(self._og_search_description(webpage, default='')),
191 **traverse_obj(data, {
192 'uploader_id': ('account_id', {lambda a: str(a) if int_or_none(a) else None}),
193 'uploader': ('account', 'username', {lambda x: strip_or_none(x) or None}),
194 'uploader_url': ('account', 'avatar_url', {url_or_none}),
195 'like_count': ('upvote_count', {int_or_none}),
196 'dislike_count': ('downvote_count', {int_or_none}),
197 'comment_count': ('comment_count', {int_or_none}),
198 'age_limit': ('is_mature', {lambda x: 18 if x else None}),
199 'timestamp': (('updated_at', 'created_at'), {parse_iso8601}),
200 'release_timestamp': ('created_at', {parse_iso8601}),
201 }, get_all=False),
202 **traverse_obj(data, ('media', 0, 'metadata', {
203 'title': ('title', {lambda x: strip_or_none(x) or None}),
204 'description': ('description', {self.get_description}),
205 'duration': ('duration', {float_or_none}),
206 'timestamp': (('updated_at', 'created_at'), {parse_iso8601}),
207 'release_timestamp': ('created_at', {parse_iso8601}),
208 }), get_all=False),
209 'id': video_id,
210 'formats': formats,
211 'thumbnail': url_or_none(search('thumbnailUrl')),
212 'http_headers': {'Accept': '*/*'},
213 }
214
215
216 class ImgurGalleryBaseIE(ImgurBaseIE):
217 _GALLERY = True
218
219 def _real_extract(self, url):
220 gallery_id = self._match_id(url)
221
222 data = self._call_api('albums', gallery_id, fatal=False, expected_status=404)
223
224 info = traverse_obj(data, {
225 'title': ('title', {lambda x: strip_or_none(x) or None}),
226 'description': ('description', {self.get_description}),
227 })
228
229 if traverse_obj(data, 'is_album'):
230
231 items = traverse_obj(data, (
232 'media', lambda _, v: v.get('type') == 'video' or v['metadata']['is_animated'],
233 'id', {lambda x: str_or_none(x) or None}))
234
235 # if a gallery with exactly one video, apply album metadata to video
236 media_id = None
237 if self._GALLERY and len(items) == 1:
238 media_id = items[0]
239
240 if not media_id:
241 result = self.playlist_result(
242 map(self._imgur_result, items), gallery_id)
243 result.update(info)
244 return result
245 gallery_id = media_id
246
247 result = self._imgur_result(gallery_id)
248 info['_type'] = 'url_transparent'
249 result.update(info)
250 return result
251
252
253 class ImgurGalleryIE(ImgurGalleryBaseIE):
254 IE_NAME = 'imgur:gallery'
255 _VALID_URL = r'https?://(?:i\.)?imgur\.com/(?:gallery|(?:t(?:opic)?|r)/[^/?#]+)/(?P<id>[a-zA-Z0-9]+)'
256
257 _TESTS = [{
258 'url': 'http://imgur.com/gallery/Q95ko',
259 'info_dict': {
260 'id': 'Q95ko',
261 'title': 'Adding faces make every GIF better',
262 },
263 'playlist_count': 25,
264 'skip': 'Zoinks! You\'ve taken a wrong turn.',
265 }, {
266 # TODO: static images - replace with animated/video gallery
267 'url': 'http://imgur.com/topic/Aww/ll5Vk',
268 'only_matching': True,
269 }, {
270 'url': 'https://imgur.com/gallery/YcAQlkx',
271 'add_ies': ['Imgur'],
272 'info_dict': {
273 'id': 'YcAQlkx',
274 'ext': 'mp4',
275 'title': 'Classic Steve Carell gif...cracks me up everytime....damn the repost downvotes....',
276 'timestamp': 1358554297,
277 'upload_date': '20130119',
278 'uploader_id': '1648642',
279 'uploader': 'wittyusernamehere',
280 'release_timestamp': 1358554297,
281 'thumbnail': 'https://i.imgur.com/YcAQlkxh.jpg',
282 'release_date': '20130119',
283 'uploader_url': 'https://i.imgur.com/u3R4I2S_d.png?maxwidth=290&fidelity=grand',
284 'comment_count': int,
285 'dislike_count': int,
286 'like_count': int,
287 },
288 }, {
289 # TODO: static image - replace with animated/video gallery
290 'url': 'http://imgur.com/topic/Funny/N8rOudd',
291 'only_matching': True,
292 }, {
293 'url': 'http://imgur.com/r/aww/VQcQPhM',
294 'add_ies': ['Imgur'],
295 'info_dict': {
296 'id': 'VQcQPhM',
297 'ext': 'mp4',
298 'title': 'The boss is here',
299 'timestamp': 1476494751,
300 'upload_date': '20161015',
301 'uploader_id': '19138530',
302 'uploader': 'thematrixcam',
303 'comment_count': int,
304 'dislike_count': int,
305 'uploader_url': 'https://i.imgur.com/qCjr5Pi_d.png?maxwidth=290&fidelity=grand',
306 'release_timestamp': 1476494751,
307 'like_count': int,
308 'release_date': '20161015',
309 'thumbnail': 'https://i.imgur.com/VQcQPhMh.jpg',
310 },
311 },
312 # from https://github.com/ytdl-org/youtube-dl/pull/16674
313 {
314 'url': 'https://imgur.com/t/unmuted/6lAn9VQ',
315 'info_dict': {
316 'id': '6lAn9VQ',
317 'title': 'Penguins !',
318 },
319 'playlist_count': 3,
320 }, {
321 'url': 'https://imgur.com/t/unmuted/kx2uD3C',
322 'add_ies': ['Imgur'],
323 'info_dict': {
324 'id': 'ZVMv45i',
325 'ext': 'mp4',
326 'title': 'Intruder',
327 'timestamp': 1528129683,
328 'upload_date': '20180604',
329 'release_timestamp': 1528129683,
330 'release_date': '20180604',
331 'like_count': int,
332 'dislike_count': int,
333 'comment_count': int,
334 'duration': 30.03,
335 'thumbnail': 'https://i.imgur.com/ZVMv45ih.jpg',
336 },
337 }, {
338 'url': 'https://imgur.com/t/unmuted/wXSK0YH',
339 'add_ies': ['Imgur'],
340 'info_dict': {
341 'id': 'JCAP4io',
342 'ext': 'mp4',
343 'title': 're:I got the blues$',
344 'description': 'Luka’s vocal stylings.\n\nFP edit: don’t encourage me. I’ll never stop posting Luka and friends.',
345 'timestamp': 1527809525,
346 'upload_date': '20180531',
347 'like_count': int,
348 'dislike_count': int,
349 'duration': 30.03,
350 'comment_count': int,
351 'release_timestamp': 1527809525,
352 'thumbnail': 'https://i.imgur.com/JCAP4ioh.jpg',
353 'release_date': '20180531',
354 },
355 }]
356
357
358 class ImgurAlbumIE(ImgurGalleryBaseIE):
359 IE_NAME = 'imgur:album'
360 _VALID_URL = r'https?://(?:i\.)?imgur\.com/a/(?P<id>[a-zA-Z0-9]+)'
361 _GALLERY = False
362 _TESTS = [{
363 # TODO: only static images - replace with animated/video gallery
364 'url': 'http://imgur.com/a/j6Orj',
365 'only_matching': True,
366 },
367 # from https://github.com/ytdl-org/youtube-dl/pull/21693
368 {
369 'url': 'https://imgur.com/a/iX265HX',
370 'info_dict': {
371 'id': 'iX265HX',
372 'title': 'enen-no-shouboutai',
373 },
374 'playlist_count': 2,
375 }, {
376 'url': 'https://imgur.com/a/8pih2Ed',
377 'info_dict': {
378 'id': '8pih2Ed',
379 },
380 'playlist_mincount': 1,
381 }]