]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitter.py
41d0b6be8c8654bba8db336e1032f95abdc72e05
[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 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 _extract_formats_from_vmap_url(self, vmap_url, video_id):
24 vmap_data = self._download_xml(vmap_url, video_id)
25 video_url = xpath_text(vmap_data, './/MediaFile').strip()
26 if determine_ext(video_url) == 'm3u8':
27 return self._extract_m3u8_formats(
28 video_url, video_id, ext='mp4', m3u8_id='hls',
29 entry_protocol='m3u8_native')
30 return [{
31 'url': video_url,
32 }]
33
34 @staticmethod
35 def _search_dimensions_in_video_url(a_format, video_url):
36 m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
37 if m:
38 a_format.update({
39 'width': int(m.group('width')),
40 'height': int(m.group('height')),
41 })
42
43
44 class TwitterCardIE(TwitterBaseIE):
45 IE_NAME = 'twitter:card'
46 _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?P<path>cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
47 _TESTS = [
48 {
49 'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
50 # MD5 checksums are different in different places
51 'info_dict': {
52 'id': '560070183650213889',
53 'ext': 'mp4',
54 'title': 'Twitter web player',
55 'thumbnail': r're:^https?://.*\.jpg$',
56 'duration': 30.033,
57 },
58 },
59 {
60 'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
61 'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
62 'info_dict': {
63 'id': '623160978427936768',
64 'ext': 'mp4',
65 'title': 'Twitter web player',
66 'thumbnail': r're:^https?://.*$',
67 },
68 },
69 {
70 'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
71 'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
72 'info_dict': {
73 'id': 'dq4Oj5quskI',
74 'ext': 'mp4',
75 'title': 'Ubuntu 11.10 Overview',
76 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
77 'upload_date': '20111013',
78 'uploader': 'OMG! Ubuntu!',
79 'uploader_id': 'omgubuntu',
80 },
81 'add_ie': ['Youtube'],
82 },
83 {
84 'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
85 'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
86 'info_dict': {
87 'id': 'iBb2x00UVlv',
88 'ext': 'mp4',
89 'upload_date': '20151113',
90 'uploader_id': '1189339351084113920',
91 'uploader': 'ArsenalTerje',
92 'title': 'Vine by ArsenalTerje',
93 'timestamp': 1447451307,
94 },
95 'add_ie': ['Vine'],
96 }, {
97 'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
98 'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
99 'info_dict': {
100 'id': '705235433198714880',
101 'ext': 'mp4',
102 'title': 'Twitter web player',
103 'thumbnail': r're:^https?://.*',
104 },
105 }, {
106 'url': 'https://twitter.com/i/videos/752274308186120192',
107 'only_matching': True,
108 },
109 ]
110
111 _API_BASE = 'https://api.twitter.com/1.1'
112
113 def _parse_media_info(self, media_info, video_id):
114 formats = []
115 for media_variant in media_info.get('variants', []):
116 media_url = media_variant['url']
117 if media_url.endswith('.m3u8'):
118 formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
119 elif media_url.endswith('.mpd'):
120 formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
121 else:
122 tbr = int_or_none(dict_get(media_variant, ('bitRate', 'bitrate')), scale=1000)
123 a_format = {
124 'url': media_url,
125 'format_id': 'http-%d' % tbr if tbr else 'http',
126 'tbr': tbr,
127 }
128 # Reported bitRate may be zero
129 if not a_format['tbr']:
130 del a_format['tbr']
131
132 self._search_dimensions_in_video_url(a_format, media_url)
133
134 formats.append(a_format)
135 return formats
136
137 def _extract_mobile_formats(self, username, video_id):
138 webpage = self._download_webpage(
139 'https://mobile.twitter.com/%s/status/%s' % (username, video_id),
140 video_id, 'Downloading mobile webpage',
141 headers={
142 # A recent mobile UA is necessary for `gt` cookie
143 'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
144 })
145 main_script_url = self._html_search_regex(
146 r'<script[^>]+src="([^"]+main\.[^"]+)"', webpage, 'main script URL')
147 main_script = self._download_webpage(
148 main_script_url, video_id, 'Downloading main script')
149 bearer_token = self._search_regex(
150 r'BEARER_TOKEN\s*:\s*"([^"]+)"',
151 main_script, 'bearer token')
152 # https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
153 api_data = self._download_json(
154 '%s/statuses/show/%s.json' % (self._API_BASE, video_id),
155 video_id, 'Downloading API data',
156 headers={
157 'Authorization': 'Bearer ' + bearer_token,
158 })
159 media_info = try_get(api_data, lambda o: o['extended_entities']['media'][0]['video_info']) or {}
160 return self._parse_media_info(media_info, video_id)
161
162 def _real_extract(self, url):
163 path, video_id = re.search(self._VALID_URL, url).groups()
164
165 config = None
166 formats = []
167 duration = None
168
169 urls = [url]
170 if path.startswith('cards/'):
171 urls.append('https://twitter.com/i/videos/' + video_id)
172
173 for u in urls:
174 webpage = self._download_webpage(
175 u, video_id, headers={'Referer': 'https://twitter.com/'})
176
177 iframe_url = self._html_search_regex(
178 r'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
179 webpage, 'video iframe', default=None)
180 if iframe_url:
181 return self.url_result(iframe_url)
182
183 config = self._parse_json(self._html_search_regex(
184 r'data-(?:player-)?config="([^"]+)"', webpage,
185 'data player config', default='{}'),
186 video_id)
187
188 if config.get('source_type') == 'vine':
189 return self.url_result(config['player_url'], 'Vine')
190
191 periscope_url = PeriscopeIE._extract_url(webpage)
192 if periscope_url:
193 return self.url_result(periscope_url, PeriscopeIE.ie_key())
194
195 video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
196
197 if video_url:
198 if determine_ext(video_url) == 'm3u8':
199 formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
200 else:
201 f = {
202 'url': video_url,
203 }
204
205 self._search_dimensions_in_video_url(f, video_url)
206
207 formats.append(f)
208
209 vmap_url = config.get('vmapUrl') or config.get('vmap_url')
210 if vmap_url:
211 formats.extend(
212 self._extract_formats_from_vmap_url(vmap_url, video_id))
213
214 media_info = None
215
216 for entity in config.get('status', {}).get('entities', []):
217 if 'mediaInfo' in entity:
218 media_info = entity['mediaInfo']
219
220 if media_info:
221 formats.extend(self._parse_media_info(media_info, video_id))
222 duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
223
224 username = config.get('user', {}).get('screen_name')
225 if username:
226 formats.extend(self._extract_mobile_formats(username, video_id))
227
228 if formats:
229 title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
230 thumbnail = config.get('posterImageUrl') or config.get('image_src')
231 duration = float_or_none(config.get('duration'), scale=1000) or duration
232 break
233
234 if not formats:
235 headers = {
236 'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw',
237 'Referer': url,
238 }
239 ct0 = self._get_cookies(url).get('ct0')
240 if ct0:
241 headers['csrf_token'] = ct0.value
242 guest_token = self._download_json(
243 '%s/guest/activate.json' % self._API_BASE, video_id,
244 'Downloading guest token', data=b'',
245 headers=headers)['guest_token']
246 headers['x-guest-token'] = guest_token
247 self._set_cookie('api.twitter.com', 'gt', guest_token)
248 config = self._download_json(
249 '%s/videos/tweet/config/%s.json' % (self._API_BASE, video_id),
250 video_id, headers=headers)
251 track = config['track']
252 vmap_url = track.get('vmapUrl')
253 if vmap_url:
254 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
255 else:
256 playback_url = track['playbackUrl']
257 if determine_ext(playback_url) == 'm3u8':
258 formats = self._extract_m3u8_formats(
259 playback_url, video_id, 'mp4',
260 entry_protocol='m3u8_native', m3u8_id='hls')
261 else:
262 formats = [{
263 'url': playback_url,
264 }]
265 title = 'Twitter web player'
266 thumbnail = config.get('posterImage')
267 duration = float_or_none(track.get('durationMs'), scale=1000)
268
269 self._remove_duplicate_formats(formats)
270 self._sort_formats(formats)
271
272 return {
273 'id': video_id,
274 'title': title,
275 'thumbnail': thumbnail,
276 'duration': duration,
277 'formats': formats,
278 }
279
280
281 class TwitterIE(InfoExtractor):
282 IE_NAME = 'twitter'
283 _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
284 _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
285 _TEMPLATE_STATUSES_URL = 'https://twitter.com/statuses/%s'
286
287 _TESTS = [{
288 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
289 'info_dict': {
290 'id': '643211948184596480',
291 'ext': 'mp4',
292 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
293 'thumbnail': r're:^https?://.*\.jpg',
294 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
295 'uploader': 'FREE THE NIPPLE',
296 'uploader_id': 'freethenipple',
297 'duration': 12.922,
298 },
299 }, {
300 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
301 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
302 'info_dict': {
303 'id': '657991469417025536',
304 'ext': 'mp4',
305 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
306 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
307 'thumbnail': r're:^https?://.*\.png',
308 'uploader': 'Gifs',
309 'uploader_id': 'giphz',
310 },
311 'expected_warnings': ['height', 'width'],
312 'skip': 'Account suspended',
313 }, {
314 'url': 'https://twitter.com/starwars/status/665052190608723968',
315 'info_dict': {
316 'id': '665052190608723968',
317 'ext': 'mp4',
318 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
319 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
320 'uploader_id': 'starwars',
321 'uploader': 'Star Wars',
322 },
323 }, {
324 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
325 'info_dict': {
326 'id': '705235433198714880',
327 'ext': 'mp4',
328 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
329 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
330 'uploader_id': 'BTNBrentYarina',
331 'uploader': 'Brent Yarina',
332 },
333 'params': {
334 # The same video as https://twitter.com/i/videos/tweet/705235433198714880
335 # Test case of TwitterCardIE
336 'skip_download': True,
337 },
338 }, {
339 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
340 'info_dict': {
341 'id': '700207533655363584',
342 'ext': 'mp4',
343 'title': 'JG - BEAT PROD: @suhmeduh #Damndaniel',
344 'description': 'JG on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
345 'thumbnail': r're:^https?://.*\.jpg',
346 'uploader': 'JG',
347 'uploader_id': 'jaydingeer',
348 'duration': 30.0,
349 },
350 }, {
351 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
352 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
353 'info_dict': {
354 'id': 'MIOxnrUteUd',
355 'ext': 'mp4',
356 'title': 'Vince Mancini - Vine of the day',
357 'description': 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
358 'uploader': 'Vince Mancini',
359 'uploader_id': 'Filmdrunk',
360 'timestamp': 1402826626,
361 'upload_date': '20140615',
362 },
363 'add_ie': ['Vine'],
364 }, {
365 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
366 'info_dict': {
367 'id': '719944021058060289',
368 'ext': 'mp4',
369 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
370 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
371 'uploader_id': 'captainamerica',
372 'uploader': 'Captain America',
373 'duration': 3.17,
374 },
375 }, {
376 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
377 'info_dict': {
378 'id': '1zqKVVlkqLaKB',
379 'ext': 'mp4',
380 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
381 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
382 'upload_date': '20160923',
383 'uploader_id': 'OPP_HSD',
384 'uploader': 'Sgt Kerry Schmidt',
385 'timestamp': 1474613214,
386 },
387 'add_ie': ['Periscope'],
388 }, {
389 # has mp4 formats via mobile API
390 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
391 'info_dict': {
392 'id': '852138619213144067',
393 'ext': 'mp4',
394 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
395 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
396 'uploader': 'عالم الأخبار',
397 'uploader_id': 'news_al3alm',
398 'duration': 277.4,
399 },
400 }, {
401 'url': 'https://twitter.com/i/web/status/910031516746514432',
402 'info_dict': {
403 'id': '910031516746514432',
404 'ext': 'mp4',
405 'title': 'Préfet de Guadeloupe - [Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre.',
406 'thumbnail': r're:^https?://.*\.jpg',
407 'description': 'Préfet de Guadeloupe on Twitter: "[Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre. https://t.co/mwx01Rs4lo"',
408 'uploader': 'Préfet de Guadeloupe',
409 'uploader_id': 'Prefet971',
410 'duration': 47.48,
411 },
412 'params': {
413 'skip_download': True, # requires ffmpeg
414 },
415 }, {
416 # card via api.twitter.com/1.1/videos/tweet/config
417 'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
418 'info_dict': {
419 'id': '1001551623938805763',
420 'ext': 'mp4',
421 'title': 're:.*?Shep is on a roll today.*?',
422 'thumbnail': r're:^https?://.*\.jpg',
423 'description': 'md5:63b036c228772523ae1924d5f8e5ed6b',
424 'uploader': 'Lis Power',
425 'uploader_id': 'LisPower1',
426 'duration': 111.278,
427 },
428 'params': {
429 'skip_download': True, # requires ffmpeg
430 },
431 }]
432
433 def _real_extract(self, url):
434 mobj = re.match(self._VALID_URL, url)
435 user_id = mobj.group('user_id')
436 twid = mobj.group('id')
437
438 webpage, urlh = self._download_webpage_handle(
439 self._TEMPLATE_STATUSES_URL % twid, twid)
440
441 if 'twitter.com/account/suspended' in urlh.geturl():
442 raise ExtractorError('Account suspended by Twitter.', expected=True)
443
444 if user_id is None:
445 mobj = re.match(self._VALID_URL, urlh.geturl())
446 user_id = mobj.group('user_id')
447
448 username = remove_end(self._og_search_title(webpage), ' on Twitter')
449
450 title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
451
452 # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
453 title = re.sub(r'\s+(https?://[^ ]+)', '', title)
454
455 info = {
456 'uploader_id': user_id,
457 'uploader': username,
458 'webpage_url': url,
459 'description': '%s on Twitter: "%s"' % (username, description),
460 'title': username + ' - ' + title,
461 }
462
463 mobj = re.search(r'''(?x)
464 <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
465 <source[^>]+video-src="(?P<url>[^"]+)"
466 ''', webpage)
467
468 if mobj:
469 more_info = mobj.group('more_info')
470 height = int_or_none(self._search_regex(
471 r'data-height="(\d+)"', more_info, 'height', fatal=False))
472 width = int_or_none(self._search_regex(
473 r'data-width="(\d+)"', more_info, 'width', fatal=False))
474 thumbnail = self._search_regex(
475 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
476 info.update({
477 'id': twid,
478 'url': mobj.group('url'),
479 'height': height,
480 'width': width,
481 'thumbnail': thumbnail,
482 })
483 return info
484
485 twitter_card_url = None
486 if 'class="PlayableMedia' in webpage:
487 twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
488 else:
489 twitter_card_iframe_url = self._search_regex(
490 r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
491 webpage, 'Twitter card iframe URL', default=None, group='url')
492 if twitter_card_iframe_url:
493 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
494
495 if twitter_card_url:
496 info.update({
497 '_type': 'url_transparent',
498 'ie_key': 'TwitterCard',
499 'url': twitter_card_url,
500 })
501 return info
502
503 raise ExtractorError('There\'s no video in this tweet.')
504
505
506 class TwitterAmplifyIE(TwitterBaseIE):
507 IE_NAME = 'twitter:amplify'
508 _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
509
510 _TEST = {
511 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
512 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
513 'info_dict': {
514 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
515 'ext': 'mp4',
516 'title': 'Twitter Video',
517 'thumbnail': 're:^https?://.*',
518 },
519 }
520
521 def _real_extract(self, url):
522 video_id = self._match_id(url)
523 webpage = self._download_webpage(url, video_id)
524
525 vmap_url = self._html_search_meta(
526 'twitter:amplify:vmap', webpage, 'vmap url')
527 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
528
529 thumbnails = []
530 thumbnail = self._html_search_meta(
531 'twitter:image:src', webpage, 'thumbnail', fatal=False)
532
533 def _find_dimension(target):
534 w = int_or_none(self._html_search_meta(
535 'twitter:%s:width' % target, webpage, fatal=False))
536 h = int_or_none(self._html_search_meta(
537 'twitter:%s:height' % target, webpage, fatal=False))
538 return w, h
539
540 if thumbnail:
541 thumbnail_w, thumbnail_h = _find_dimension('image')
542 thumbnails.append({
543 'url': thumbnail,
544 'width': thumbnail_w,
545 'height': thumbnail_h,
546 })
547
548 video_w, video_h = _find_dimension('player')
549 formats[0].update({
550 'width': video_w,
551 'height': video_h,
552 })
553
554 return {
555 'id': video_id,
556 'title': 'Twitter Video',
557 'formats': formats,
558 'thumbnails': thumbnails,
559 }