[twitter:card] Add support for another endpoint (closes #16586)
[youtube-dl] / youtube_dl / extractor / twitter.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_urlparse
8 from ..utils import (
9     determine_ext,
10     dict_get,
11     ExtractorError,
12     float_or_none,
13     int_or_none,
14     remove_end,
15     try_get,
16     xpath_text,
17 )
18
19 from .periscope import PeriscopeIE
20
21
22 class TwitterBaseIE(InfoExtractor):
23     def _extract_formats_from_vmap_url(self, vmap_url, video_id):
24         vmap_data = self._download_xml(vmap_url, video_id)
25         video_url = xpath_text(vmap_data, './/MediaFile').strip()
26         if determine_ext(video_url) == 'm3u8':
27             return self._extract_m3u8_formats(
28                 video_url, video_id, ext='mp4', m3u8_id='hls',
29                 entry_protocol='m3u8_native')
30         return [{
31             'url': video_url,
32         }]
33
34     @staticmethod
35     def _search_dimensions_in_video_url(a_format, video_url):
36         m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
37         if m:
38             a_format.update({
39                 'width': int(m.group('width')),
40                 'height': int(m.group('height')),
41             })
42
43
44 class TwitterCardIE(TwitterBaseIE):
45     IE_NAME = 'twitter:card'
46     _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?P<path>cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
47     _TESTS = [
48         {
49             'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
50             # MD5 checksums are different in different places
51             'info_dict': {
52                 'id': '560070183650213889',
53                 'ext': 'mp4',
54                 'title': 'Twitter web player',
55                 'thumbnail': r're:^https?://.*\.jpg$',
56                 'duration': 30.033,
57             },
58         },
59         {
60             'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
61             'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
62             'info_dict': {
63                 'id': '623160978427936768',
64                 'ext': 'mp4',
65                 'title': 'Twitter web player',
66                 'thumbnail': r're:^https?://.*$',
67             },
68         },
69         {
70             'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
71             'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
72             'info_dict': {
73                 'id': 'dq4Oj5quskI',
74                 'ext': 'mp4',
75                 'title': 'Ubuntu 11.10 Overview',
76                 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
77                 'upload_date': '20111013',
78                 'uploader': 'OMG! Ubuntu!',
79                 'uploader_id': 'omgubuntu',
80             },
81             'add_ie': ['Youtube'],
82         },
83         {
84             'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
85             'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
86             'info_dict': {
87                 'id': 'iBb2x00UVlv',
88                 'ext': 'mp4',
89                 'upload_date': '20151113',
90                 'uploader_id': '1189339351084113920',
91                 'uploader': 'ArsenalTerje',
92                 'title': 'Vine by ArsenalTerje',
93                 'timestamp': 1447451307,
94             },
95             'add_ie': ['Vine'],
96         }, {
97             'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
98             'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
99             'info_dict': {
100                 'id': '705235433198714880',
101                 'ext': 'mp4',
102                 'title': 'Twitter web player',
103                 'thumbnail': r're:^https?://.*',
104             },
105         }, {
106             'url': 'https://twitter.com/i/videos/752274308186120192',
107             'only_matching': True,
108         },
109     ]
110
111     def _parse_media_info(self, media_info, video_id):
112         formats = []
113         for media_variant in media_info.get('variants', []):
114             media_url = media_variant['url']
115             if media_url.endswith('.m3u8'):
116                 formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
117             elif media_url.endswith('.mpd'):
118                 formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
119             else:
120                 tbr = int_or_none(dict_get(media_variant, ('bitRate', 'bitrate')), scale=1000)
121                 a_format = {
122                     'url': media_url,
123                     'format_id': 'http-%d' % tbr if tbr else 'http',
124                     'tbr': tbr,
125                 }
126                 # Reported bitRate may be zero
127                 if not a_format['tbr']:
128                     del a_format['tbr']
129
130                 self._search_dimensions_in_video_url(a_format, media_url)
131
132                 formats.append(a_format)
133         return formats
134
135     def _extract_mobile_formats(self, username, video_id):
136         webpage = self._download_webpage(
137             'https://mobile.twitter.com/%s/status/%s' % (username, video_id),
138             video_id, 'Downloading mobile webpage',
139             headers={
140                 # A recent mobile UA is necessary for `gt` cookie
141                 'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
142             })
143         main_script_url = self._html_search_regex(
144             r'<script[^>]+src="([^"]+main\.[^"]+)"', webpage, 'main script URL')
145         main_script = self._download_webpage(
146             main_script_url, video_id, 'Downloading main script')
147         bearer_token = self._search_regex(
148             r'BEARER_TOKEN\s*:\s*"([^"]+)"',
149             main_script, 'bearer token')
150         # https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
151         api_data = self._download_json(
152             'https://api.twitter.com/1.1/statuses/show/%s.json' % video_id,
153             video_id, 'Downloading API data',
154             headers={
155                 'Authorization': 'Bearer ' + bearer_token,
156             })
157         media_info = try_get(api_data, lambda o: o['extended_entities']['media'][0]['video_info']) or {}
158         return self._parse_media_info(media_info, video_id)
159
160     def _real_extract(self, url):
161         path, video_id = re.search(self._VALID_URL, url).groups()
162
163         config = None
164         formats = []
165         duration = None
166
167         urls = [url]
168         if path.startswith('cards/'):
169             urls.append('https://twitter.com/i/videos/' + video_id)
170
171         for u in urls:
172             webpage = self._download_webpage(u, video_id)
173
174             iframe_url = self._html_search_regex(
175                 r'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
176                 webpage, 'video iframe', default=None)
177             if iframe_url:
178                 return self.url_result(iframe_url)
179
180             config = self._parse_json(self._html_search_regex(
181                 r'data-(?:player-)?config="([^"]+)"', webpage,
182                 'data player config', default='{}'),
183                 video_id)
184
185             if config.get('source_type') == 'vine':
186                 return self.url_result(config['player_url'], 'Vine')
187
188             periscope_url = PeriscopeIE._extract_url(webpage)
189             if periscope_url:
190                 return self.url_result(periscope_url, PeriscopeIE.ie_key())
191
192             video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
193
194             if video_url:
195                 if determine_ext(video_url) == 'm3u8':
196                     formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
197                 else:
198                     f = {
199                         'url': video_url,
200                     }
201
202                     self._search_dimensions_in_video_url(f, video_url)
203
204                     formats.append(f)
205
206             vmap_url = config.get('vmapUrl') or config.get('vmap_url')
207             if vmap_url:
208                 formats.extend(
209                     self._extract_formats_from_vmap_url(vmap_url, video_id))
210
211             media_info = None
212
213             for entity in config.get('status', {}).get('entities', []):
214                 if 'mediaInfo' in entity:
215                     media_info = entity['mediaInfo']
216
217             if media_info:
218                 formats.extend(self._parse_media_info(media_info, video_id))
219                 duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
220
221             username = config.get('user', {}).get('screen_name')
222             if username:
223                 formats.extend(self._extract_mobile_formats(username, video_id))
224
225             if formats:
226                 title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
227                 thumbnail = config.get('posterImageUrl') or config.get('image_src')
228                 duration = float_or_none(config.get('duration'), scale=1000) or duration
229                 break
230
231         if not formats:
232             config = self._download_json(
233                 'https://api.twitter.com/1.1/videos/tweet/config/%s.json' % video_id,
234                 video_id, headers={
235                     'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAIK1zgAAAAAA2tUWuhGZ2JceoId5GwYWU5GspY4%3DUq7gzFoCZs1QfwGoVdvSac3IniczZEYXIcDyumCauIXpcAPorE',
236                 })
237             track = config['track']
238             vmap_url = track.get('vmapUrl')
239             if vmap_url:
240                 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
241             else:
242                 playback_url = track['playbackUrl']
243                 if determine_ext(playback_url) == 'm3u8':
244                     formats = self._extract_m3u8_formats(
245                         playback_url, video_id, 'mp4',
246                         entry_protocol='m3u8_native', m3u8_id='hls')
247                 else:
248                     formats = [{
249                         'url': playback_url,
250                     }]
251             title = 'Twitter web player'
252             thumbnail = config.get('posterImage')
253             duration = float_or_none(track.get('durationMs'), scale=1000)
254
255         self._remove_duplicate_formats(formats)
256         self._sort_formats(formats)
257
258         return {
259             'id': video_id,
260             'title': title,
261             'thumbnail': thumbnail,
262             'duration': duration,
263             'formats': formats,
264         }
265
266
267 class TwitterIE(InfoExtractor):
268     IE_NAME = 'twitter'
269     _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
270     _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
271     _TEMPLATE_STATUSES_URL = 'https://twitter.com/statuses/%s'
272
273     _TESTS = [{
274         'url': 'https://twitter.com/freethenipple/status/643211948184596480',
275         'info_dict': {
276             'id': '643211948184596480',
277             'ext': 'mp4',
278             'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
279             'thumbnail': r're:^https?://.*\.jpg',
280             'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
281             'uploader': 'FREE THE NIPPLE',
282             'uploader_id': 'freethenipple',
283             'duration': 12.922,
284         },
285     }, {
286         'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
287         'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
288         'info_dict': {
289             'id': '657991469417025536',
290             'ext': 'mp4',
291             'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
292             'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
293             'thumbnail': r're:^https?://.*\.png',
294             'uploader': 'Gifs',
295             'uploader_id': 'giphz',
296         },
297         'expected_warnings': ['height', 'width'],
298         'skip': 'Account suspended',
299     }, {
300         'url': 'https://twitter.com/starwars/status/665052190608723968',
301         'info_dict': {
302             'id': '665052190608723968',
303             'ext': 'mp4',
304             'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
305             'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
306             'uploader_id': 'starwars',
307             'uploader': 'Star Wars',
308         },
309     }, {
310         'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
311         'info_dict': {
312             'id': '705235433198714880',
313             'ext': 'mp4',
314             'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
315             'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
316             'uploader_id': 'BTNBrentYarina',
317             'uploader': 'Brent Yarina',
318         },
319         'params': {
320             # The same video as https://twitter.com/i/videos/tweet/705235433198714880
321             # Test case of TwitterCardIE
322             'skip_download': True,
323         },
324     }, {
325         'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
326         'info_dict': {
327             'id': '700207533655363584',
328             'ext': 'mp4',
329             'title': 'JG - BEAT PROD: @suhmeduh #Damndaniel',
330             'description': 'JG on Twitter: "BEAT PROD: @suhmeduh  https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
331             'thumbnail': r're:^https?://.*\.jpg',
332             'uploader': 'JG',
333             'uploader_id': 'jaydingeer',
334             'duration': 30.0,
335         },
336     }, {
337         'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
338         'md5': '89a15ed345d13b86e9a5a5e051fa308a',
339         'info_dict': {
340             'id': 'MIOxnrUteUd',
341             'ext': 'mp4',
342             'title': 'Vince Mancini - Vine of the day',
343             'description': 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
344             'uploader': 'Vince Mancini',
345             'uploader_id': 'Filmdrunk',
346             'timestamp': 1402826626,
347             'upload_date': '20140615',
348         },
349         'add_ie': ['Vine'],
350     }, {
351         'url': 'https://twitter.com/captainamerica/status/719944021058060289',
352         'info_dict': {
353             'id': '719944021058060289',
354             'ext': 'mp4',
355             'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
356             'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
357             'uploader_id': 'captainamerica',
358             'uploader': 'Captain America',
359             'duration': 3.17,
360         },
361     }, {
362         'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
363         'info_dict': {
364             'id': '1zqKVVlkqLaKB',
365             'ext': 'mp4',
366             'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
367             'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence  https://t.co/EKrVgIXF3s"',
368             'upload_date': '20160923',
369             'uploader_id': 'OPP_HSD',
370             'uploader': 'Sgt Kerry Schmidt',
371             'timestamp': 1474613214,
372         },
373         'add_ie': ['Periscope'],
374     }, {
375         # has mp4 formats via mobile API
376         'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
377         'info_dict': {
378             'id': '852138619213144067',
379             'ext': 'mp4',
380             'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
381             'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة   https://t.co/xg6OhpyKfN"',
382             'uploader': 'عالم الأخبار',
383             'uploader_id': 'news_al3alm',
384             'duration': 277.4,
385         },
386     }, {
387         'url': 'https://twitter.com/i/web/status/910031516746514432',
388         'info_dict': {
389             'id': '910031516746514432',
390             'ext': 'mp4',
391             'title': 'Préfet de Guadeloupe - [Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre.',
392             'thumbnail': r're:^https?://.*\.jpg',
393             'description': 'Préfet de Guadeloupe on Twitter: "[Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre. https://t.co/mwx01Rs4lo"',
394             'uploader': 'Préfet de Guadeloupe',
395             'uploader_id': 'Prefet971',
396             'duration': 47.48,
397         },
398         'params': {
399             'skip_download': True,  # requires ffmpeg
400         },
401     }, {
402         # card via api.twitter.com/1.1/videos/tweet/config
403         'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
404         'info_dict': {
405             'id': '1001551623938805763',
406             'ext': 'mp4',
407             'title': 're:.*?Shep is on a roll today.*?',
408             'thumbnail': r're:^https?://.*\.jpg',
409             'description': 'md5:63b036c228772523ae1924d5f8e5ed6b',
410             'uploader': 'Lis Power',
411             'uploader_id': 'LisPower1',
412             'duration': 111.278,
413         },
414         'params': {
415             'skip_download': True,  # requires ffmpeg
416         },
417     }]
418
419     def _real_extract(self, url):
420         mobj = re.match(self._VALID_URL, url)
421         user_id = mobj.group('user_id')
422         twid = mobj.group('id')
423
424         webpage, urlh = self._download_webpage_handle(
425             self._TEMPLATE_STATUSES_URL % twid, twid)
426
427         if 'twitter.com/account/suspended' in urlh.geturl():
428             raise ExtractorError('Account suspended by Twitter.', expected=True)
429
430         if user_id is None:
431             mobj = re.match(self._VALID_URL, urlh.geturl())
432             user_id = mobj.group('user_id')
433
434         username = remove_end(self._og_search_title(webpage), ' on Twitter')
435
436         title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
437
438         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
439         title = re.sub(r'\s+(https?://[^ ]+)', '', title)
440
441         info = {
442             'uploader_id': user_id,
443             'uploader': username,
444             'webpage_url': url,
445             'description': '%s on Twitter: "%s"' % (username, description),
446             'title': username + ' - ' + title,
447         }
448
449         mobj = re.search(r'''(?x)
450             <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
451                 <source[^>]+video-src="(?P<url>[^"]+)"
452         ''', webpage)
453
454         if mobj:
455             more_info = mobj.group('more_info')
456             height = int_or_none(self._search_regex(
457                 r'data-height="(\d+)"', more_info, 'height', fatal=False))
458             width = int_or_none(self._search_regex(
459                 r'data-width="(\d+)"', more_info, 'width', fatal=False))
460             thumbnail = self._search_regex(
461                 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
462             info.update({
463                 'id': twid,
464                 'url': mobj.group('url'),
465                 'height': height,
466                 'width': width,
467                 'thumbnail': thumbnail,
468             })
469             return info
470
471         twitter_card_url = None
472         if 'class="PlayableMedia' in webpage:
473             twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
474         else:
475             twitter_card_iframe_url = self._search_regex(
476                 r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
477                 webpage, 'Twitter card iframe URL', default=None, group='url')
478             if twitter_card_iframe_url:
479                 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
480
481         if twitter_card_url:
482             info.update({
483                 '_type': 'url_transparent',
484                 'ie_key': 'TwitterCard',
485                 'url': twitter_card_url,
486             })
487             return info
488
489         raise ExtractorError('There\'s no video in this tweet.')
490
491
492 class TwitterAmplifyIE(TwitterBaseIE):
493     IE_NAME = 'twitter:amplify'
494     _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
495
496     _TEST = {
497         'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
498         'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
499         'info_dict': {
500             'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
501             'ext': 'mp4',
502             'title': 'Twitter Video',
503             'thumbnail': 're:^https?://.*',
504         },
505     }
506
507     def _real_extract(self, url):
508         video_id = self._match_id(url)
509         webpage = self._download_webpage(url, video_id)
510
511         vmap_url = self._html_search_meta(
512             'twitter:amplify:vmap', webpage, 'vmap url')
513         formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
514
515         thumbnails = []
516         thumbnail = self._html_search_meta(
517             'twitter:image:src', webpage, 'thumbnail', fatal=False)
518
519         def _find_dimension(target):
520             w = int_or_none(self._html_search_meta(
521                 'twitter:%s:width' % target, webpage, fatal=False))
522             h = int_or_none(self._html_search_meta(
523                 'twitter:%s:height' % target, webpage, fatal=False))
524             return w, h
525
526         if thumbnail:
527             thumbnail_w, thumbnail_h = _find_dimension('image')
528             thumbnails.append({
529                 'url': thumbnail,
530                 'width': thumbnail_w,
531                 'height': thumbnail_h,
532             })
533
534         video_w, video_h = _find_dimension('player')
535         formats[0].update({
536             'width': video_w,
537             'height': video_h,
538         })
539
540         return {
541             'id': video_id,
542             'title': 'Twitter Video',
543             'formats': formats,
544             'thumbnails': thumbnails,
545         }