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