]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitter.py
de41065d64921af6e861775f85dc5f3011caa524
[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(u, video_id)
175
176 iframe_url = self._html_search_regex(
177 r'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
178 webpage, 'video iframe', default=None)
179 if iframe_url:
180 return self.url_result(iframe_url)
181
182 config = self._parse_json(self._html_search_regex(
183 r'data-(?:player-)?config="([^"]+)"', webpage,
184 'data player config', default='{}'),
185 video_id)
186
187 if config.get('source_type') == 'vine':
188 return self.url_result(config['player_url'], 'Vine')
189
190 periscope_url = PeriscopeIE._extract_url(webpage)
191 if periscope_url:
192 return self.url_result(periscope_url, PeriscopeIE.ie_key())
193
194 video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
195
196 if video_url:
197 if determine_ext(video_url) == 'm3u8':
198 formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
199 else:
200 f = {
201 'url': video_url,
202 }
203
204 self._search_dimensions_in_video_url(f, video_url)
205
206 formats.append(f)
207
208 vmap_url = config.get('vmapUrl') or config.get('vmap_url')
209 if vmap_url:
210 formats.extend(
211 self._extract_formats_from_vmap_url(vmap_url, video_id))
212
213 media_info = None
214
215 for entity in config.get('status', {}).get('entities', []):
216 if 'mediaInfo' in entity:
217 media_info = entity['mediaInfo']
218
219 if media_info:
220 formats.extend(self._parse_media_info(media_info, video_id))
221 duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
222
223 username = config.get('user', {}).get('screen_name')
224 if username:
225 formats.extend(self._extract_mobile_formats(username, video_id))
226
227 if formats:
228 title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
229 thumbnail = config.get('posterImageUrl') or config.get('image_src')
230 duration = float_or_none(config.get('duration'), scale=1000) or duration
231 break
232
233 if not formats:
234 headers = {
235 'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw',
236 'Referer': url,
237 }
238 ct0 = self._get_cookies(url).get('ct0')
239 if ct0:
240 headers['csrf_token'] = ct0.value
241 guest_token = self._download_json(
242 '%s/guest/activate.json' % self._API_BASE, video_id,
243 'Downloading guest token', data=b'',
244 headers=headers)['guest_token']
245 headers['x-guest-token'] = guest_token
246 self._set_cookie('api.twitter.com', 'gt', guest_token)
247 config = self._download_json(
248 '%s/videos/tweet/config/%s.json' % (self._API_BASE, video_id),
249 video_id, headers=headers)
250 track = config['track']
251 vmap_url = track.get('vmapUrl')
252 if vmap_url:
253 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
254 else:
255 playback_url = track['playbackUrl']
256 if determine_ext(playback_url) == 'm3u8':
257 formats = self._extract_m3u8_formats(
258 playback_url, video_id, 'mp4',
259 entry_protocol='m3u8_native', m3u8_id='hls')
260 else:
261 formats = [{
262 'url': playback_url,
263 }]
264 title = 'Twitter web player'
265 thumbnail = config.get('posterImage')
266 duration = float_or_none(track.get('durationMs'), scale=1000)
267
268 self._remove_duplicate_formats(formats)
269 self._sort_formats(formats)
270
271 return {
272 'id': video_id,
273 'title': title,
274 'thumbnail': thumbnail,
275 'duration': duration,
276 'formats': formats,
277 }
278
279
280 class TwitterIE(InfoExtractor):
281 IE_NAME = 'twitter'
282 _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
283 _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
284 _TEMPLATE_STATUSES_URL = 'https://twitter.com/statuses/%s'
285
286 _TESTS = [{
287 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
288 'info_dict': {
289 'id': '643211948184596480',
290 'ext': 'mp4',
291 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
292 'thumbnail': r're:^https?://.*\.jpg',
293 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
294 'uploader': 'FREE THE NIPPLE',
295 'uploader_id': 'freethenipple',
296 'duration': 12.922,
297 },
298 }, {
299 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
300 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
301 'info_dict': {
302 'id': '657991469417025536',
303 'ext': 'mp4',
304 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
305 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
306 'thumbnail': r're:^https?://.*\.png',
307 'uploader': 'Gifs',
308 'uploader_id': 'giphz',
309 },
310 'expected_warnings': ['height', 'width'],
311 'skip': 'Account suspended',
312 }, {
313 'url': 'https://twitter.com/starwars/status/665052190608723968',
314 'info_dict': {
315 'id': '665052190608723968',
316 'ext': 'mp4',
317 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
318 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
319 'uploader_id': 'starwars',
320 'uploader': 'Star Wars',
321 },
322 }, {
323 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
324 'info_dict': {
325 'id': '705235433198714880',
326 'ext': 'mp4',
327 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
328 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
329 'uploader_id': 'BTNBrentYarina',
330 'uploader': 'Brent Yarina',
331 },
332 'params': {
333 # The same video as https://twitter.com/i/videos/tweet/705235433198714880
334 # Test case of TwitterCardIE
335 'skip_download': True,
336 },
337 }, {
338 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
339 'info_dict': {
340 'id': '700207533655363584',
341 'ext': 'mp4',
342 'title': 'JG - BEAT PROD: @suhmeduh #Damndaniel',
343 'description': 'JG on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
344 'thumbnail': r're:^https?://.*\.jpg',
345 'uploader': 'JG',
346 'uploader_id': 'jaydingeer',
347 'duration': 30.0,
348 },
349 }, {
350 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
351 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
352 'info_dict': {
353 'id': 'MIOxnrUteUd',
354 'ext': 'mp4',
355 'title': 'Vince Mancini - Vine of the day',
356 'description': 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
357 'uploader': 'Vince Mancini',
358 'uploader_id': 'Filmdrunk',
359 'timestamp': 1402826626,
360 'upload_date': '20140615',
361 },
362 'add_ie': ['Vine'],
363 }, {
364 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
365 'info_dict': {
366 'id': '719944021058060289',
367 'ext': 'mp4',
368 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
369 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
370 'uploader_id': 'captainamerica',
371 'uploader': 'Captain America',
372 'duration': 3.17,
373 },
374 }, {
375 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
376 'info_dict': {
377 'id': '1zqKVVlkqLaKB',
378 'ext': 'mp4',
379 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
380 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
381 'upload_date': '20160923',
382 'uploader_id': 'OPP_HSD',
383 'uploader': 'Sgt Kerry Schmidt',
384 'timestamp': 1474613214,
385 },
386 'add_ie': ['Periscope'],
387 }, {
388 # has mp4 formats via mobile API
389 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
390 'info_dict': {
391 'id': '852138619213144067',
392 'ext': 'mp4',
393 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
394 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
395 'uploader': 'عالم الأخبار',
396 'uploader_id': 'news_al3alm',
397 'duration': 277.4,
398 },
399 }, {
400 'url': 'https://twitter.com/i/web/status/910031516746514432',
401 'info_dict': {
402 'id': '910031516746514432',
403 'ext': 'mp4',
404 '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.',
405 'thumbnail': r're:^https?://.*\.jpg',
406 '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"',
407 'uploader': 'Préfet de Guadeloupe',
408 'uploader_id': 'Prefet971',
409 'duration': 47.48,
410 },
411 'params': {
412 'skip_download': True, # requires ffmpeg
413 },
414 }, {
415 # card via api.twitter.com/1.1/videos/tweet/config
416 'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
417 'info_dict': {
418 'id': '1001551623938805763',
419 'ext': 'mp4',
420 'title': 're:.*?Shep is on a roll today.*?',
421 'thumbnail': r're:^https?://.*\.jpg',
422 'description': 'md5:63b036c228772523ae1924d5f8e5ed6b',
423 'uploader': 'Lis Power',
424 'uploader_id': 'LisPower1',
425 'duration': 111.278,
426 },
427 'params': {
428 'skip_download': True, # requires ffmpeg
429 },
430 }]
431
432 def _real_extract(self, url):
433 mobj = re.match(self._VALID_URL, url)
434 user_id = mobj.group('user_id')
435 twid = mobj.group('id')
436
437 webpage, urlh = self._download_webpage_handle(
438 self._TEMPLATE_STATUSES_URL % twid, twid)
439
440 if 'twitter.com/account/suspended' in urlh.geturl():
441 raise ExtractorError('Account suspended by Twitter.', expected=True)
442
443 if user_id is None:
444 mobj = re.match(self._VALID_URL, urlh.geturl())
445 user_id = mobj.group('user_id')
446
447 username = remove_end(self._og_search_title(webpage), ' on Twitter')
448
449 title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
450
451 # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
452 title = re.sub(r'\s+(https?://[^ ]+)', '', title)
453
454 info = {
455 'uploader_id': user_id,
456 'uploader': username,
457 'webpage_url': url,
458 'description': '%s on Twitter: "%s"' % (username, description),
459 'title': username + ' - ' + title,
460 }
461
462 mobj = re.search(r'''(?x)
463 <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
464 <source[^>]+video-src="(?P<url>[^"]+)"
465 ''', webpage)
466
467 if mobj:
468 more_info = mobj.group('more_info')
469 height = int_or_none(self._search_regex(
470 r'data-height="(\d+)"', more_info, 'height', fatal=False))
471 width = int_or_none(self._search_regex(
472 r'data-width="(\d+)"', more_info, 'width', fatal=False))
473 thumbnail = self._search_regex(
474 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
475 info.update({
476 'id': twid,
477 'url': mobj.group('url'),
478 'height': height,
479 'width': width,
480 'thumbnail': thumbnail,
481 })
482 return info
483
484 twitter_card_url = None
485 if 'class="PlayableMedia' in webpage:
486 twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
487 else:
488 twitter_card_iframe_url = self._search_regex(
489 r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
490 webpage, 'Twitter card iframe URL', default=None, group='url')
491 if twitter_card_iframe_url:
492 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
493
494 if twitter_card_url:
495 info.update({
496 '_type': 'url_transparent',
497 'ie_key': 'TwitterCard',
498 'url': twitter_card_url,
499 })
500 return info
501
502 raise ExtractorError('There\'s no video in this tweet.')
503
504
505 class TwitterAmplifyIE(TwitterBaseIE):
506 IE_NAME = 'twitter:amplify'
507 _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
508
509 _TEST = {
510 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
511 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
512 'info_dict': {
513 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
514 'ext': 'mp4',
515 'title': 'Twitter Video',
516 'thumbnail': 're:^https?://.*',
517 },
518 }
519
520 def _real_extract(self, url):
521 video_id = self._match_id(url)
522 webpage = self._download_webpage(url, video_id)
523
524 vmap_url = self._html_search_meta(
525 'twitter:amplify:vmap', webpage, 'vmap url')
526 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
527
528 thumbnails = []
529 thumbnail = self._html_search_meta(
530 'twitter:image:src', webpage, 'thumbnail', fatal=False)
531
532 def _find_dimension(target):
533 w = int_or_none(self._html_search_meta(
534 'twitter:%s:width' % target, webpage, fatal=False))
535 h = int_or_none(self._html_search_meta(
536 'twitter:%s:height' % target, webpage, fatal=False))
537 return w, h
538
539 if thumbnail:
540 thumbnail_w, thumbnail_h = _find_dimension('image')
541 thumbnails.append({
542 'url': thumbnail,
543 'width': thumbnail_w,
544 'height': thumbnail_h,
545 })
546
547 video_w, video_h = _find_dimension('player')
548 formats[0].update({
549 'width': video_w,
550 'height': video_h,
551 })
552
553 return {
554 'id': video_id,
555 'title': 'Twitter Video',
556 'formats': formats,
557 'thumbnails': thumbnails,
558 }