]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitter.py
Prepate to upload
[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?://.*(?:\bformat=|\.)jpg',
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 def _parse_media_info(self, media_info, video_id):
112 formats = []
113 for media_variant in media_info.get('variants', []):
114 media_url = media_variant['url']
115 if media_url.endswith('.m3u8'):
116 formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
117 elif media_url.endswith('.mpd'):
118 formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
119 else:
120 tbr = int_or_none(dict_get(media_variant, ('bitRate', 'bitrate')), scale=1000)
121 a_format = {
122 'url': media_url,
123 'format_id': 'http-%d' % tbr if tbr else 'http',
124 'tbr': tbr,
125 }
126 # Reported bitRate may be zero
127 if not a_format['tbr']:
128 del a_format['tbr']
129
130 self._search_dimensions_in_video_url(a_format, media_url)
131
132 formats.append(a_format)
133 return formats
134
135 def _extract_mobile_formats(self, username, video_id):
136 webpage = self._download_webpage(
137 'https://mobile.twitter.com/%s/status/%s' % (username, video_id),
138 video_id, 'Downloading mobile webpage',
139 headers={
140 # A recent mobile UA is necessary for `gt` cookie
141 'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
142 })
143 main_script_url = self._html_search_regex(
144 r'<script[^>]+src="([^"]+main\.[^"]+)"', webpage, 'main script URL')
145 main_script = self._download_webpage(
146 main_script_url, video_id, 'Downloading main script')
147 bearer_token = self._search_regex(
148 r'BEARER_TOKEN\s*:\s*"([^"]+)"',
149 main_script, 'bearer token')
150 # https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
151 api_data = self._download_json(
152 'https://api.twitter.com/1.1/statuses/show/%s.json' % video_id,
153 video_id, 'Downloading API data',
154 headers={
155 'Authorization': 'Bearer ' + bearer_token,
156 })
157 media_info = try_get(api_data, lambda o: o['extended_entities']['media'][0]['video_info']) or {}
158 return self._parse_media_info(media_info, video_id)
159
160 def _real_extract(self, url):
161 path, video_id = re.search(self._VALID_URL, url).groups()
162
163 config = None
164 formats = []
165 duration = None
166
167 urls = [url]
168 if path.startswith('cards/'):
169 urls.append('https://twitter.com/i/videos/' + video_id)
170
171 for u in urls:
172 webpage = self._download_webpage(u, video_id)
173
174 iframe_url = self._html_search_regex(
175 r'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
176 webpage, 'video iframe', default=None)
177 if iframe_url:
178 return self.url_result(iframe_url)
179
180 config = self._parse_json(self._html_search_regex(
181 r'data-(?:player-)?config="([^"]+)"', webpage,
182 'data player config', default='{}'),
183 video_id)
184
185 if config.get('source_type') == 'vine':
186 return self.url_result(config['player_url'], 'Vine')
187
188 periscope_url = PeriscopeIE._extract_url(webpage)
189 if periscope_url:
190 return self.url_result(periscope_url, PeriscopeIE.ie_key())
191
192 video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
193
194 if video_url:
195 if determine_ext(video_url) == 'm3u8':
196 formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
197 else:
198 f = {
199 'url': video_url,
200 }
201
202 self._search_dimensions_in_video_url(f, video_url)
203
204 formats.append(f)
205
206 vmap_url = config.get('vmapUrl') or config.get('vmap_url')
207 if vmap_url:
208 formats.extend(
209 self._extract_formats_from_vmap_url(vmap_url, video_id))
210
211 media_info = None
212
213 for entity in config.get('status', {}).get('entities', []):
214 if 'mediaInfo' in entity:
215 media_info = entity['mediaInfo']
216
217 if media_info:
218 formats.extend(self._parse_media_info(media_info, video_id))
219 duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
220
221 username = config.get('user', {}).get('screen_name')
222 if username:
223 formats.extend(self._extract_mobile_formats(username, video_id))
224
225 if formats:
226 break
227
228 self._remove_duplicate_formats(formats)
229 self._sort_formats(formats)
230
231 title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
232 thumbnail = config.get('posterImageUrl') or config.get('image_src')
233 duration = float_or_none(config.get('duration'), scale=1000) or duration
234
235 return {
236 'id': video_id,
237 'title': title,
238 'thumbnail': thumbnail,
239 'duration': duration,
240 'formats': formats,
241 }
242
243
244 class TwitterIE(InfoExtractor):
245 IE_NAME = 'twitter'
246 _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
247 _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
248 _TEMPLATE_STATUSES_URL = 'https://twitter.com/statuses/%s'
249
250 _TESTS = [{
251 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
252 'info_dict': {
253 'id': '643211948184596480',
254 'ext': 'mp4',
255 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
256 'thumbnail': r're:^https?://.*\.jpg',
257 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
258 'uploader': 'FREE THE NIPPLE',
259 'uploader_id': 'freethenipple',
260 'duration': 12.922,
261 },
262 }, {
263 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
264 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
265 'info_dict': {
266 'id': '657991469417025536',
267 'ext': 'mp4',
268 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
269 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
270 'thumbnail': r're:^https?://.*\.png',
271 'uploader': 'Gifs',
272 'uploader_id': 'giphz',
273 },
274 'expected_warnings': ['height', 'width'],
275 'skip': 'Account suspended',
276 }, {
277 'url': 'https://twitter.com/starwars/status/665052190608723968',
278 'info_dict': {
279 'id': '665052190608723968',
280 'ext': 'mp4',
281 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
282 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
283 'uploader_id': 'starwars',
284 'uploader': 'Star Wars',
285 },
286 }, {
287 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
288 'info_dict': {
289 'id': '705235433198714880',
290 'ext': 'mp4',
291 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
292 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
293 'uploader_id': 'BTNBrentYarina',
294 'uploader': 'Brent Yarina',
295 },
296 'params': {
297 # The same video as https://twitter.com/i/videos/tweet/705235433198714880
298 # Test case of TwitterCardIE
299 'skip_download': True,
300 },
301 }, {
302 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
303 'info_dict': {
304 'id': '700207533655363584',
305 'ext': 'mp4',
306 'title': 'JG - BEAT PROD: @suhmeduh #Damndaniel',
307 'description': 'JG on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
308 'thumbnail': r're:^https?://.*\.jpg',
309 'uploader': 'JG',
310 'uploader_id': 'jaydingeer',
311 'duration': 30.0,
312 },
313 }, {
314 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
315 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
316 'info_dict': {
317 'id': 'MIOxnrUteUd',
318 'ext': 'mp4',
319 'title': 'Vince Mancini - Vine of the day',
320 'description': 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
321 'uploader': 'Vince Mancini',
322 'uploader_id': 'Filmdrunk',
323 'timestamp': 1402826626,
324 'upload_date': '20140615',
325 },
326 'add_ie': ['Vine'],
327 }, {
328 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
329 'info_dict': {
330 'id': '719944021058060289',
331 'ext': 'mp4',
332 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
333 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
334 'uploader_id': 'captainamerica',
335 'uploader': 'Captain America',
336 'duration': 3.17,
337 },
338 }, {
339 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
340 'info_dict': {
341 'id': '1zqKVVlkqLaKB',
342 'ext': 'mp4',
343 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
344 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
345 'upload_date': '20160923',
346 'uploader_id': 'OPP_HSD',
347 'uploader': 'Sgt Kerry Schmidt',
348 'timestamp': 1474613214,
349 },
350 'add_ie': ['Periscope'],
351 }, {
352 # has mp4 formats via mobile API
353 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
354 'info_dict': {
355 'id': '852138619213144067',
356 'ext': 'mp4',
357 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
358 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
359 'uploader': 'عالم الأخبار',
360 'uploader_id': 'news_al3alm',
361 'duration': 277.4,
362 },
363 }, {
364 'url': 'https://twitter.com/i/web/status/910031516746514432',
365 'info_dict': {
366 'id': '910031516746514432',
367 'ext': 'mp4',
368 '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.',
369 'thumbnail': r're:^https?://.*\.jpg',
370 '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"',
371 'uploader': 'Préfet de Guadeloupe',
372 'uploader_id': 'Prefet971',
373 'duration': 47.48,
374 },
375 'params': {
376 'skip_download': True, # requires ffmpeg
377 },
378 }]
379
380 def _real_extract(self, url):
381 mobj = re.match(self._VALID_URL, url)
382 user_id = mobj.group('user_id')
383 twid = mobj.group('id')
384
385 webpage, urlh = self._download_webpage_handle(
386 self._TEMPLATE_STATUSES_URL % twid, twid)
387
388 if 'twitter.com/account/suspended' in urlh.geturl():
389 raise ExtractorError('Account suspended by Twitter.', expected=True)
390
391 if user_id is None:
392 mobj = re.match(self._VALID_URL, urlh.geturl())
393 user_id = mobj.group('user_id')
394
395 username = remove_end(self._og_search_title(webpage), ' on Twitter')
396
397 title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
398
399 # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
400 title = re.sub(r'\s+(https?://[^ ]+)', '', title)
401
402 info = {
403 'uploader_id': user_id,
404 'uploader': username,
405 'webpage_url': url,
406 'description': '%s on Twitter: "%s"' % (username, description),
407 'title': username + ' - ' + title,
408 }
409
410 mobj = re.search(r'''(?x)
411 <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
412 <source[^>]+video-src="(?P<url>[^"]+)"
413 ''', webpage)
414
415 if mobj:
416 more_info = mobj.group('more_info')
417 height = int_or_none(self._search_regex(
418 r'data-height="(\d+)"', more_info, 'height', fatal=False))
419 width = int_or_none(self._search_regex(
420 r'data-width="(\d+)"', more_info, 'width', fatal=False))
421 thumbnail = self._search_regex(
422 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
423 info.update({
424 'id': twid,
425 'url': mobj.group('url'),
426 'height': height,
427 'width': width,
428 'thumbnail': thumbnail,
429 })
430 return info
431
432 twitter_card_url = None
433 if 'class="PlayableMedia' in webpage:
434 twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
435 else:
436 twitter_card_iframe_url = self._search_regex(
437 r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
438 webpage, 'Twitter card iframe URL', default=None, group='url')
439 if twitter_card_iframe_url:
440 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
441
442 if twitter_card_url:
443 info.update({
444 '_type': 'url_transparent',
445 'ie_key': 'TwitterCard',
446 'url': twitter_card_url,
447 })
448 return info
449
450 raise ExtractorError('There\'s no video in this tweet.')
451
452
453 class TwitterAmplifyIE(TwitterBaseIE):
454 IE_NAME = 'twitter:amplify'
455 _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
456
457 _TEST = {
458 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
459 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
460 'info_dict': {
461 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
462 'ext': 'mp4',
463 'title': 'Twitter Video',
464 'thumbnail': 're:^https?://.*',
465 },
466 }
467
468 def _real_extract(self, url):
469 video_id = self._match_id(url)
470 webpage = self._download_webpage(url, video_id)
471
472 vmap_url = self._html_search_meta(
473 'twitter:amplify:vmap', webpage, 'vmap url')
474 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
475
476 thumbnails = []
477 thumbnail = self._html_search_meta(
478 'twitter:image:src', webpage, 'thumbnail', fatal=False)
479
480 def _find_dimension(target):
481 w = int_or_none(self._html_search_meta(
482 'twitter:%s:width' % target, webpage, fatal=False))
483 h = int_or_none(self._html_search_meta(
484 'twitter:%s:height' % target, webpage, fatal=False))
485 return w, h
486
487 if thumbnail:
488 thumbnail_w, thumbnail_h = _find_dimension('image')
489 thumbnails.append({
490 'url': thumbnail,
491 'width': thumbnail_w,
492 'height': thumbnail_h,
493 })
494
495 video_w, video_h = _find_dimension('player')
496 formats[0].update({
497 'width': video_w,
498 'height': video_h,
499 })
500
501 return {
502 'id': video_id,
503 'title': 'Twitter Video',
504 'formats': formats,
505 'thumbnails': thumbnails,
506 }