[periscope] Support pscp.tv URLs in embedded frames
[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 - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
339             'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence  https://t.co/EKrVgIXF3s"',
340             'upload_date': '20160923',
341             'uploader_id': 'OPP_HSD',
342             'uploader': 'Sgt Kerry Schmidt',
343             'timestamp': 1474613214,
344         },
345         'add_ie': ['Periscope'],
346     }, {
347         # has mp4 formats via mobile API
348         'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
349         'info_dict': {
350             'id': '852138619213144067',
351             'ext': 'mp4',
352             'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
353             'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة   https://t.co/xg6OhpyKfN"',
354             'uploader': 'عالم الأخبار',
355             'uploader_id': 'news_al3alm',
356         },
357         'params': {
358             'format': 'best[format_id^=http-]',
359         },
360     }]
361
362     def _real_extract(self, url):
363         mobj = re.match(self._VALID_URL, url)
364         user_id = mobj.group('user_id')
365         twid = mobj.group('id')
366
367         webpage, urlh = self._download_webpage_handle(
368             self._TEMPLATE_URL % (user_id, twid), twid)
369
370         if 'twitter.com/account/suspended' in urlh.geturl():
371             raise ExtractorError('Account suspended by Twitter.', expected=True)
372
373         username = remove_end(self._og_search_title(webpage), ' on Twitter')
374
375         title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
376
377         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
378         title = re.sub(r'\s+(https?://[^ ]+)', '', title)
379
380         info = {
381             'uploader_id': user_id,
382             'uploader': username,
383             'webpage_url': url,
384             'description': '%s on Twitter: "%s"' % (username, description),
385             'title': username + ' - ' + title,
386         }
387
388         mobj = re.search(r'''(?x)
389             <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
390                 <source[^>]+video-src="(?P<url>[^"]+)"
391         ''', webpage)
392
393         if mobj:
394             more_info = mobj.group('more_info')
395             height = int_or_none(self._search_regex(
396                 r'data-height="(\d+)"', more_info, 'height', fatal=False))
397             width = int_or_none(self._search_regex(
398                 r'data-width="(\d+)"', more_info, 'width', fatal=False))
399             thumbnail = self._search_regex(
400                 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
401             info.update({
402                 'id': twid,
403                 'url': mobj.group('url'),
404                 'height': height,
405                 'width': width,
406                 'thumbnail': thumbnail,
407             })
408             return info
409
410         twitter_card_url = None
411         if 'class="PlayableMedia' in webpage:
412             twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
413         else:
414             twitter_card_iframe_url = self._search_regex(
415                 r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
416                 webpage, 'Twitter card iframe URL', default=None, group='url')
417             if twitter_card_iframe_url:
418                 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
419
420         if twitter_card_url:
421             info.update({
422                 '_type': 'url_transparent',
423                 'ie_key': 'TwitterCard',
424                 'url': twitter_card_url,
425             })
426             return info
427
428         raise ExtractorError('There\'s no video in this tweet.')
429
430
431 class TwitterAmplifyIE(TwitterBaseIE):
432     IE_NAME = 'twitter:amplify'
433     _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
434
435     _TEST = {
436         'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
437         'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
438         'info_dict': {
439             'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
440             'ext': 'mp4',
441             'title': 'Twitter Video',
442             'thumbnail': 're:^https?://.*',
443         },
444     }
445
446     def _real_extract(self, url):
447         video_id = self._match_id(url)
448         webpage = self._download_webpage(url, video_id)
449
450         vmap_url = self._html_search_meta(
451             'twitter:amplify:vmap', webpage, 'vmap url')
452         video_url = self._get_vmap_video_url(vmap_url, video_id)
453
454         thumbnails = []
455         thumbnail = self._html_search_meta(
456             'twitter:image:src', webpage, 'thumbnail', fatal=False)
457
458         def _find_dimension(target):
459             w = int_or_none(self._html_search_meta(
460                 'twitter:%s:width' % target, webpage, fatal=False))
461             h = int_or_none(self._html_search_meta(
462                 'twitter:%s:height' % target, webpage, fatal=False))
463             return w, h
464
465         if thumbnail:
466             thumbnail_w, thumbnail_h = _find_dimension('image')
467             thumbnails.append({
468                 'url': thumbnail,
469                 'width': thumbnail_w,
470                 'height': thumbnail_h,
471             })
472
473         video_w, video_h = _find_dimension('player')
474         formats = [{
475             'url': video_url,
476             'width': video_w,
477             'height': video_h,
478         }]
479
480         return {
481             'id': video_id,
482             'title': 'Twitter Video',
483             'formats': formats,
484             'thumbnails': thumbnails,
485         }