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