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