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