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