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