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