]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/twitter.py
Fix `playlist_index` and add `playlist_autonumber` (#302)
[yt-dlp.git] / yt_dlp / extractor / twitter.py
CommitLineData
48aae2d2 1# coding: utf-8
23e7cba8
S
2from __future__ import unicode_literals
3
4import re
5
6from .common import InfoExtractor
18ca61c5
RA
7from ..compat import (
8 compat_HTTPError,
9 compat_parse_qs,
10 compat_urllib_parse_unquote,
11 compat_urllib_parse_urlparse,
12)
23e7cba8 13from ..utils import (
2edfd745
YCH
14 dict_get,
15 ExtractorError,
23e7cba8 16 float_or_none,
cf5881fc 17 int_or_none,
2edfd745 18 try_get,
18ca61c5
RA
19 strip_or_none,
20 unified_timestamp,
21 update_url_query,
2edfd745 22 xpath_text,
23e7cba8
S
23)
24
18ca61c5
RA
25from .periscope import (
26 PeriscopeBaseIE,
27 PeriscopeIE,
28)
f0bc5a86 29
23e7cba8 30
445d72b8 31class TwitterBaseIE(InfoExtractor):
18ca61c5
RA
32 _API_BASE = 'https://api.twitter.com/1.1/'
33 _BASE_REGEX = r'https?://(?:(?:www|m(?:obile)?)\.)?twitter\.com/'
34 _GUEST_TOKEN = None
35
36 def _extract_variant_formats(self, variant, video_id):
37 variant_url = variant.get('url')
38 if not variant_url:
4bed4363 39 return [], {}
18ca61c5 40 elif '.m3u8' in variant_url:
4bed4363 41 return self._extract_m3u8_formats_and_subtitles(
18ca61c5
RA
42 variant_url, video_id, 'mp4', 'm3u8_native',
43 m3u8_id='hls', fatal=False)
44 else:
45 tbr = int_or_none(dict_get(variant, ('bitrate', 'bit_rate')), 1000) or None
46 f = {
47 'url': variant_url,
48 'format_id': 'http' + ('-%d' % tbr if tbr else ''),
49 'tbr': tbr,
50 }
51 self._search_dimensions_in_video_url(f, variant_url)
4bed4363 52 return [f], {}
18ca61c5 53
9be31e77 54 def _extract_formats_from_vmap_url(self, vmap_url, video_id):
445d72b8 55 vmap_data = self._download_xml(vmap_url, video_id)
18ca61c5 56 formats = []
4bed4363 57 subtitles = {}
18ca61c5
RA
58 urls = []
59 for video_variant in vmap_data.findall('.//{http://twitter.com/schema/videoVMapV2.xsd}videoVariant'):
60 video_variant.attrib['url'] = compat_urllib_parse_unquote(
61 video_variant.attrib['url'])
62 urls.append(video_variant.attrib['url'])
4bed4363
F
63 fmts, subs = self._extract_variant_formats(
64 video_variant.attrib, video_id)
65 formats.extend(fmts)
66 subtitles = self._merge_subtitles(subtitles, subs)
18ca61c5
RA
67 video_url = strip_or_none(xpath_text(vmap_data, './/MediaFile'))
68 if video_url not in urls:
4bed4363
F
69 fmts, subs = self._extract_variant_formats({'url': video_url}, video_id)
70 formats.extend(fmts)
71 subtitles = self._merge_subtitles(subtitles, subs)
72 return formats, subtitles
445d72b8 73
2edfd745
YCH
74 @staticmethod
75 def _search_dimensions_in_video_url(a_format, video_url):
76 m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
77 if m:
78 a_format.update({
79 'width': int(m.group('width')),
80 'height': int(m.group('height')),
81 })
82
18ca61c5
RA
83 def _call_api(self, path, video_id, query={}):
84 headers = {
85 'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw',
86 }
87 if not self._GUEST_TOKEN:
88 self._GUEST_TOKEN = self._download_json(
89 self._API_BASE + 'guest/activate.json', video_id,
90 'Downloading guest token', data=b'',
91 headers=headers)['guest_token']
92 headers['x-guest-token'] = self._GUEST_TOKEN
93 try:
94 return self._download_json(
95 self._API_BASE + path, video_id, headers=headers, query=query)
96 except ExtractorError as e:
97 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
98 raise ExtractorError(self._parse_json(
99 e.cause.read().decode(),
100 video_id)['errors'][0]['message'], expected=True)
101 raise
102
103
104class TwitterCardIE(InfoExtractor):
014e8803 105 IE_NAME = 'twitter:card'
18ca61c5 106 _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/(?:cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
c3dea3f8 107 _TESTS = [
108 {
109 'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
acb6e97e 110 # MD5 checksums are different in different places
c3dea3f8 111 'info_dict': {
112 'id': '560070183650213889',
113 'ext': 'mp4',
18ca61c5
RA
114 'title': "Twitter - You can now shoot, edit and share video on Twitter. Capture life's most moving moments from your perspective.",
115 'description': 'md5:18d3e24bb4f6e5007487dd546e53bd96',
116 'uploader': 'Twitter',
117 'uploader_id': 'Twitter',
118 'thumbnail': r're:^https?://.*\.jpg',
c3dea3f8 119 'duration': 30.033,
18ca61c5
RA
120 'timestamp': 1422366112,
121 'upload_date': '20150127',
3615bfe1 122 },
23e7cba8 123 },
c3dea3f8 124 {
125 'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
18ca61c5 126 'md5': '7137eca597f72b9abbe61e5ae0161399',
c3dea3f8 127 'info_dict': {
128 'id': '623160978427936768',
129 'ext': 'mp4',
18ca61c5
RA
130 'title': "NASA - Fly over Pluto's icy Norgay Mountains and Sputnik Plain in this @NASANewHorizons #PlutoFlyby video.",
131 'description': "Fly over Pluto's icy Norgay Mountains and Sputnik Plain in this @NASANewHorizons #PlutoFlyby video. https://t.co/BJYgOjSeGA",
132 'uploader': 'NASA',
133 'uploader_id': 'NASA',
134 'timestamp': 1437408129,
135 'upload_date': '20150720',
c3dea3f8 136 },
4a7b7903
YCH
137 },
138 {
139 'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
f0bc5a86 140 'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
4a7b7903
YCH
141 'info_dict': {
142 'id': 'dq4Oj5quskI',
143 'ext': 'mp4',
144 'title': 'Ubuntu 11.10 Overview',
f0bc5a86 145 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
4a7b7903 146 'upload_date': '20111013',
18ca61c5 147 'uploader': 'OMG! UBUNTU!',
4a7b7903
YCH
148 'uploader_id': 'omgubuntu',
149 },
31752f76 150 'add_ie': ['Youtube'],
5f1b2aea
YCH
151 },
152 {
153 'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
3615bfe1 154 'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
5f1b2aea
YCH
155 'info_dict': {
156 'id': 'iBb2x00UVlv',
157 'ext': 'mp4',
158 'upload_date': '20151113',
159 'uploader_id': '1189339351084113920',
acb6e97e
YCH
160 'uploader': 'ArsenalTerje',
161 'title': 'Vine by ArsenalTerje',
e8f20ffa 162 'timestamp': 1447451307,
5f1b2aea
YCH
163 },
164 'add_ie': ['Vine'],
0ae937a7
YCH
165 }, {
166 'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
3615bfe1 167 'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
0ae937a7
YCH
168 'info_dict': {
169 'id': '705235433198714880',
170 'ext': 'mp4',
18ca61c5
RA
171 'title': "Brent Yarina - Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight.",
172 'description': "Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight. https://t.co/OrxcJ28Bns",
173 'uploader': 'Brent Yarina',
174 'uploader_id': 'BTNBrentYarina',
175 'timestamp': 1456976204,
176 'upload_date': '20160303',
0ae937a7 177 },
18ca61c5 178 'skip': 'This content is no longer available.',
748a462f
S
179 }, {
180 'url': 'https://twitter.com/i/videos/752274308186120192',
181 'only_matching': True,
0ae937a7 182 },
c3dea3f8 183 ]
23e7cba8
S
184
185 def _real_extract(self, url):
18ca61c5
RA
186 status_id = self._match_id(url)
187 return self.url_result(
188 'https://twitter.com/statuses/' + status_id,
189 TwitterIE.ie_key(), status_id)
c8398a9b 190
03879ff0 191
18ca61c5 192class TwitterIE(TwitterBaseIE):
014e8803 193 IE_NAME = 'twitter'
18ca61c5 194 _VALID_URL = TwitterBaseIE._BASE_REGEX + r'(?:(?:i/web|[^/]+)/status|statuses)/(?P<id>\d+)'
f57f84f6 195
cf5881fc 196 _TESTS = [{
48aae2d2 197 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
f57f84f6 198 'info_dict': {
48aae2d2 199 'id': '643211948184596480',
f57f84f6 200 'ext': 'mp4',
575036b4 201 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
ec85ded8 202 'thumbnail': r're:^https?://.*\.jpg',
18ca61c5 203 'description': 'FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ',
48aae2d2
YCH
204 'uploader': 'FREE THE NIPPLE',
205 'uploader_id': 'freethenipple',
3b65a6fb 206 'duration': 12.922,
18ca61c5
RA
207 'timestamp': 1442188653,
208 'upload_date': '20150913',
209 'age_limit': 18,
f57f84f6 210 },
cf5881fc
YCH
211 }, {
212 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
213 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
214 'info_dict': {
215 'id': '657991469417025536',
216 'ext': 'mp4',
217 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
218 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
ec85ded8 219 'thumbnail': r're:^https?://.*\.png',
cf5881fc
YCH
220 'uploader': 'Gifs',
221 'uploader_id': 'giphz',
222 },
7efc1c2b 223 'expected_warnings': ['height', 'width'],
fc0a45fa 224 'skip': 'Account suspended',
b703ebee
JMF
225 }, {
226 'url': 'https://twitter.com/starwars/status/665052190608723968',
b703ebee
JMF
227 'info_dict': {
228 'id': '665052190608723968',
229 'ext': 'mp4',
230 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
18ca61c5 231 'description': 'A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens. https://t.co/OkSqT2fjWJ',
b703ebee
JMF
232 'uploader_id': 'starwars',
233 'uploader': 'Star Wars',
18ca61c5
RA
234 'timestamp': 1447395772,
235 'upload_date': '20151113',
b703ebee 236 },
0ae937a7
YCH
237 }, {
238 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
239 'info_dict': {
240 'id': '705235433198714880',
241 'ext': 'mp4',
18ca61c5
RA
242 'title': "Brent Yarina - Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight.",
243 'description': "Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight. https://t.co/OrxcJ28Bns",
0ae937a7
YCH
244 'uploader_id': 'BTNBrentYarina',
245 'uploader': 'Brent Yarina',
18ca61c5
RA
246 'timestamp': 1456976204,
247 'upload_date': '20160303',
0ae937a7
YCH
248 },
249 'params': {
250 # The same video as https://twitter.com/i/videos/tweet/705235433198714880
251 # Test case of TwitterCardIE
252 'skip_download': True,
253 },
03879ff0
YCH
254 }, {
255 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
03879ff0
YCH
256 'info_dict': {
257 'id': '700207533655363584',
258 'ext': 'mp4',
00dd0cd5 259 'title': 'simon vertugo - BEAT PROD: @suhmeduh #Damndaniel',
18ca61c5 260 'description': 'BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ',
ec85ded8 261 'thumbnail': r're:^https?://.*\.jpg',
00dd0cd5 262 'uploader': 'simon vertugo',
18ca61c5 263 'uploader_id': 'simonvertugo',
3b65a6fb 264 'duration': 30.0,
18ca61c5
RA
265 'timestamp': 1455777459,
266 'upload_date': '20160218',
03879ff0 267 },
395fd4b0
YCH
268 }, {
269 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
270 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
271 'info_dict': {
272 'id': 'MIOxnrUteUd',
273 'ext': 'mp4',
18ca61c5
RA
274 'title': 'Dr.Pepperの飲み方 #japanese #バカ #ドクペ #電動ガン',
275 'uploader': 'TAKUMA',
276 'uploader_id': '1004126642786242560',
3615bfe1 277 'timestamp': 1402826626,
395fd4b0
YCH
278 'upload_date': '20140615',
279 },
280 'add_ie': ['Vine'],
36b7d9db
YCH
281 }, {
282 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
36b7d9db
YCH
283 'info_dict': {
284 'id': '719944021058060289',
285 'ext': 'mp4',
286 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
18ca61c5
RA
287 'description': '@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI',
288 'uploader_id': 'CaptainAmerica',
36b7d9db 289 'uploader': 'Captain America',
3b65a6fb 290 'duration': 3.17,
18ca61c5
RA
291 'timestamp': 1460483005,
292 'upload_date': '20160412',
36b7d9db 293 },
f0bc5a86
YCH
294 }, {
295 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
296 'info_dict': {
297 'id': '1zqKVVlkqLaKB',
298 'ext': 'mp4',
18ca61c5 299 'title': 'Sgt Kerry Schmidt - Ontario Provincial Police - Road rage, mischief, assault, rollover and fire in one occurrence',
f0bc5a86 300 'upload_date': '20160923',
18ca61c5
RA
301 'uploader_id': '1PmKqpJdOJQoY',
302 'uploader': 'Sgt Kerry Schmidt - Ontario Provincial Police',
f0bc5a86
YCH
303 'timestamp': 1474613214,
304 },
305 'add_ie': ['Periscope'],
2edfd745
YCH
306 }, {
307 # has mp4 formats via mobile API
308 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
309 'info_dict': {
310 'id': '852138619213144067',
311 'ext': 'mp4',
312 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
18ca61c5 313 'description': 'كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN',
2edfd745
YCH
314 'uploader': 'عالم الأخبار',
315 'uploader_id': 'news_al3alm',
3b65a6fb 316 'duration': 277.4,
18ca61c5
RA
317 'timestamp': 1492000653,
318 'upload_date': '20170412',
2edfd745 319 },
00dd0cd5 320 'skip': 'Account suspended',
5c1452e8
GF
321 }, {
322 'url': 'https://twitter.com/i/web/status/910031516746514432',
323 'info_dict': {
324 'id': '910031516746514432',
325 'ext': 'mp4',
326 '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.',
327 'thumbnail': r're:^https?://.*\.jpg',
18ca61c5 328 'description': '[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',
5c1452e8
GF
329 'uploader': 'Préfet de Guadeloupe',
330 'uploader_id': 'Prefet971',
331 'duration': 47.48,
18ca61c5
RA
332 'timestamp': 1505803395,
333 'upload_date': '20170919',
5c1452e8
GF
334 },
335 'params': {
336 'skip_download': True, # requires ffmpeg
337 },
2593725a
S
338 }, {
339 # card via api.twitter.com/1.1/videos/tweet/config
340 'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
341 'info_dict': {
342 'id': '1001551623938805763',
343 'ext': 'mp4',
344 'title': 're:.*?Shep is on a roll today.*?',
345 'thumbnail': r're:^https?://.*\.jpg',
18ca61c5 346 'description': 'md5:37b9f2ff31720cef23b2bd42ee8a0f09',
2593725a
S
347 'uploader': 'Lis Power',
348 'uploader_id': 'LisPower1',
349 'duration': 111.278,
18ca61c5
RA
350 'timestamp': 1527623489,
351 'upload_date': '20180529',
2593725a
S
352 },
353 'params': {
354 'skip_download': True, # requires ffmpeg
355 },
b7ef93f0
S
356 }, {
357 'url': 'https://twitter.com/foobar/status/1087791357756956680',
358 'info_dict': {
359 'id': '1087791357756956680',
360 'ext': 'mp4',
361 'title': 'Twitter - A new is coming. Some of you got an opt-in to try it now. Check out the emoji button, quick keyboard shortcuts, upgraded trends, advanced search, and more. Let us know your thoughts!',
362 'thumbnail': r're:^https?://.*\.jpg',
18ca61c5 363 'description': 'md5:6dfd341a3310fb97d80d2bf7145df976',
b7ef93f0
S
364 'uploader': 'Twitter',
365 'uploader_id': 'Twitter',
366 'duration': 61.567,
18ca61c5
RA
367 'timestamp': 1548184644,
368 'upload_date': '20190122',
369 },
370 }, {
371 # not available in Periscope
372 'url': 'https://twitter.com/ViviEducation/status/1136534865145286656',
373 'info_dict': {
374 'id': '1vOGwqejwoWxB',
375 'ext': 'mp4',
376 'title': 'Vivi - Vivi founder @lior_rauchy announcing our new student feedback tool live at @EduTECH_AU #EduTECH2019',
377 'uploader': 'Vivi',
378 'uploader_id': '1eVjYOLGkGrQL',
b7ef93f0 379 },
18ca61c5 380 'add_ie': ['TwitterBroadcast'],
30a074c2 381 }, {
382 # unified card
383 'url': 'https://twitter.com/BrooklynNets/status/1349794411333394432?s=20',
384 'info_dict': {
385 'id': '1349794411333394432',
386 'ext': 'mp4',
387 'title': 'md5:d1c4941658e4caaa6cb579260d85dcba',
388 'thumbnail': r're:^https?://.*\.jpg',
389 'description': 'md5:71ead15ec44cee55071547d6447c6a3e',
390 'uploader': 'Brooklyn Nets',
391 'uploader_id': 'BrooklynNets',
392 'duration': 324.484,
393 'timestamp': 1610651040,
394 'upload_date': '20210114',
395 },
396 'params': {
397 'skip_download': True,
398 },
18ca61c5
RA
399 }, {
400 # Twitch Clip Embed
401 'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
402 'only_matching': True,
10a5091e
RA
403 }, {
404 # promo_video_website card
405 'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
406 'only_matching': True,
00dd0cd5 407 }, {
408 # promo_video_convo card
409 'url': 'https://twitter.com/poco_dandy/status/1047395834013384704',
410 'only_matching': True,
411 }, {
412 # appplayer card
413 'url': 'https://twitter.com/poco_dandy/status/1150646424461176832',
414 'only_matching': True,
30a074c2 415 }, {
416 # video_direct_message card
417 'url': 'https://twitter.com/qarev001/status/1348948114569269251',
418 'only_matching': True,
419 }, {
420 # poll2choice_video card
421 'url': 'https://twitter.com/CAF_Online/status/1349365911120195585',
422 'only_matching': True,
423 }, {
424 # poll3choice_video card
425 'url': 'https://twitter.com/SamsungMobileSA/status/1348609186725289984',
426 'only_matching': True,
427 }, {
428 # poll4choice_video card
429 'url': 'https://twitter.com/SouthamptonFC/status/1347577658079641604',
430 'only_matching': True,
cf5881fc 431 }]
f57f84f6 432
433 def _real_extract(self, url):
18ca61c5
RA
434 twid = self._match_id(url)
435 status = self._call_api(
436 'statuses/show/%s.json' % twid, twid, {
437 'cards_platform': 'Web-12',
438 'include_cards': 1,
439 'include_reply_count': 1,
440 'include_user_entities': 0,
441 'tweet_mode': 'extended',
442 })
575036b4 443
18ca61c5 444 title = description = status['full_text'].replace('\n', ' ')
575036b4 445 # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
b703ebee 446 title = re.sub(r'\s+(https?://[^ ]+)', '', title)
18ca61c5
RA
447 user = status.get('user') or {}
448 uploader = user.get('name')
449 if uploader:
450 title = '%s - %s' % (uploader, title)
451 uploader_id = user.get('screen_name')
452
453 tags = []
454 for hashtag in (try_get(status, lambda x: x['entities']['hashtags'], list) or []):
455 hashtag_text = hashtag.get('text')
456 if not hashtag_text:
457 continue
458 tags.append(hashtag_text)
575036b4 459
cf5881fc 460 info = {
18ca61c5
RA
461 'id': twid,
462 'title': title,
463 'description': description,
464 'uploader': uploader,
465 'timestamp': unified_timestamp(status.get('created_at')),
466 'uploader_id': uploader_id,
467 'uploader_url': 'https://twitter.com/' + uploader_id if uploader_id else None,
468 'like_count': int_or_none(status.get('favorite_count')),
469 'repost_count': int_or_none(status.get('retweet_count')),
470 'comment_count': int_or_none(status.get('reply_count')),
471 'age_limit': 18 if status.get('possibly_sensitive') else 0,
472 'tags': tags,
f57f84f6 473 }
cf5881fc 474
30a074c2 475 def extract_from_video_info(media):
18ca61c5
RA
476 video_info = media.get('video_info') or {}
477
478 formats = []
4bed4363 479 subtitles = {}
18ca61c5 480 for variant in video_info.get('variants', []):
4bed4363
F
481 fmts, subs = self._extract_variant_formats(variant, twid)
482 subtitles = self._merge_subtitles(subtitles, subs)
483 formats.extend(fmts)
18ca61c5
RA
484 self._sort_formats(formats)
485
486 thumbnails = []
487 media_url = media.get('media_url_https') or media.get('media_url')
488 if media_url:
489 def add_thumbnail(name, size):
490 thumbnails.append({
491 'id': name,
492 'url': update_url_query(media_url, {'name': name}),
493 'width': int_or_none(size.get('w') or size.get('width')),
494 'height': int_or_none(size.get('h') or size.get('height')),
495 })
496 for name, size in media.get('sizes', {}).items():
497 add_thumbnail(name, size)
498 add_thumbnail('orig', media.get('original_info') or {})
cf5881fc 499
0ae937a7 500 info.update({
18ca61c5 501 'formats': formats,
4bed4363 502 'subtitles': subtitles,
18ca61c5
RA
503 'thumbnails': thumbnails,
504 'duration': float_or_none(video_info.get('duration_millis'), 1000),
0ae937a7 505 })
30a074c2 506
507 media = try_get(status, lambda x: x['extended_entities']['media'][0])
508 if media and media.get('type') != 'photo':
509 extract_from_video_info(media)
18ca61c5
RA
510 else:
511 card = status.get('card')
512 if card:
513 binding_values = card['binding_values']
514
515 def get_binding_value(k):
516 o = binding_values.get(k) or {}
517 return try_get(o, lambda x: x[x['type'].lower() + '_value'])
518
519 card_name = card['name'].split(':')[-1]
00dd0cd5 520 if card_name == 'player':
521 info.update({
522 '_type': 'url',
523 'url': get_binding_value('player_url'),
524 })
525 elif card_name == 'periscope_broadcast':
526 info.update({
527 '_type': 'url',
528 'url': get_binding_value('url') or get_binding_value('player_url'),
529 'ie_key': PeriscopeIE.ie_key(),
530 })
531 elif card_name == 'broadcast':
532 info.update({
533 '_type': 'url',
534 'url': get_binding_value('broadcast_url'),
535 'ie_key': TwitterBroadcastIE.ie_key(),
536 })
537 elif card_name == 'summary':
538 info.update({
539 '_type': 'url',
540 'url': get_binding_value('card_url'),
541 })
30a074c2 542 elif card_name == 'unified_card':
543 media_entities = self._parse_json(get_binding_value('unified_card'), twid)['media_entities']
544 extract_from_video_info(next(iter(media_entities.values())))
545 # amplify, promo_video_website, promo_video_convo, appplayer,
546 # video_direct_message, poll2choice_video, poll3choice_video,
547 # poll4choice_video, ...
00dd0cd5 548 else:
10a5091e
RA
549 is_amplify = card_name == 'amplify'
550 vmap_url = get_binding_value('amplify_url_vmap') if is_amplify else get_binding_value('player_stream_url')
551 content_id = get_binding_value('%s_content_id' % (card_name if is_amplify else 'player'))
4bed4363 552 formats, subtitles = self._extract_formats_from_vmap_url(vmap_url, content_id or twid)
18ca61c5
RA
553 self._sort_formats(formats)
554
555 thumbnails = []
556 for suffix in ('_small', '', '_large', '_x_large', '_original'):
557 image = get_binding_value('player_image' + suffix) or {}
558 image_url = image.get('url')
559 if not image_url or '/player-placeholder' in image_url:
560 continue
561 thumbnails.append({
562 'id': suffix[1:] if suffix else 'medium',
563 'url': image_url,
564 'width': int_or_none(image.get('width')),
565 'height': int_or_none(image.get('height')),
566 })
567
568 info.update({
569 'formats': formats,
4bed4363 570 'subtitles': subtitles,
18ca61c5
RA
571 'thumbnails': thumbnails,
572 'duration': int_or_none(get_binding_value(
573 'content_duration_seconds')),
574 })
18ca61c5
RA
575 else:
576 expanded_url = try_get(status, lambda x: x['entities']['urls'][0]['expanded_url'])
577 if not expanded_url:
578 raise ExtractorError("There's no video in this tweet.")
579 info.update({
580 '_type': 'url',
581 'url': expanded_url,
582 })
583 return info
445d72b8
YCH
584
585
586class TwitterAmplifyIE(TwitterBaseIE):
587 IE_NAME = 'twitter:amplify'
25042f73 588 _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
445d72b8
YCH
589
590 _TEST = {
591 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
592 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
593 'info_dict': {
594 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
595 'ext': 'mp4',
596 'title': 'Twitter Video',
bdbf4ba4 597 'thumbnail': 're:^https?://.*',
445d72b8
YCH
598 },
599 }
600
601 def _real_extract(self, url):
602 video_id = self._match_id(url)
603 webpage = self._download_webpage(url, video_id)
604
605 vmap_url = self._html_search_meta(
606 'twitter:amplify:vmap', webpage, 'vmap url')
9be31e77 607 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
445d72b8 608
bdbf4ba4
YCH
609 thumbnails = []
610 thumbnail = self._html_search_meta(
611 'twitter:image:src', webpage, 'thumbnail', fatal=False)
612
613 def _find_dimension(target):
614 w = int_or_none(self._html_search_meta(
615 'twitter:%s:width' % target, webpage, fatal=False))
616 h = int_or_none(self._html_search_meta(
617 'twitter:%s:height' % target, webpage, fatal=False))
618 return w, h
619
620 if thumbnail:
621 thumbnail_w, thumbnail_h = _find_dimension('image')
622 thumbnails.append({
623 'url': thumbnail,
624 'width': thumbnail_w,
625 'height': thumbnail_h,
626 })
627
628 video_w, video_h = _find_dimension('player')
9be31e77 629 formats[0].update({
bdbf4ba4
YCH
630 'width': video_w,
631 'height': video_h,
9be31e77 632 })
bdbf4ba4 633
445d72b8
YCH
634 return {
635 'id': video_id,
636 'title': 'Twitter Video',
bdbf4ba4
YCH
637 'formats': formats,
638 'thumbnails': thumbnails,
445d72b8 639 }
18ca61c5
RA
640
641
642class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE):
643 IE_NAME = 'twitter:broadcast'
644 _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/broadcasts/(?P<id>[0-9a-zA-Z]{13})'
645
7b0b53ea
S
646 _TEST = {
647 # untitled Periscope video
648 'url': 'https://twitter.com/i/broadcasts/1yNGaQLWpejGj',
649 'info_dict': {
650 'id': '1yNGaQLWpejGj',
651 'ext': 'mp4',
652 'title': 'Andrea May Sahouri - Periscope Broadcast',
653 'uploader': 'Andrea May Sahouri',
654 'uploader_id': '1PXEdBZWpGwKe',
655 },
656 }
657
18ca61c5
RA
658 def _real_extract(self, url):
659 broadcast_id = self._match_id(url)
660 broadcast = self._call_api(
661 'broadcasts/show.json', broadcast_id,
662 {'ids': broadcast_id})['broadcasts'][broadcast_id]
663 info = self._parse_broadcast_data(broadcast, broadcast_id)
664 media_key = broadcast['media_key']
665 source = self._call_api(
666 'live_video_stream/status/' + media_key, media_key)['source']
667 m3u8_url = source.get('noRedirectPlaybackUrl') or source['location']
668 if '/live_video_stream/geoblocked/' in m3u8_url:
669 self.raise_geo_restricted()
670 m3u8_id = compat_parse_qs(compat_urllib_parse_urlparse(
671 m3u8_url).query).get('type', [None])[0]
672 state, width, height = self._extract_common_format_info(broadcast)
673 info['formats'] = self._extract_pscp_m3u8_formats(
674 m3u8_url, broadcast_id, m3u8_id, state, width, height)
675 return info
86b868c6
U
676
677
678class TwitterShortenerIE(TwitterBaseIE):
679 IE_NAME = 'twitter:shortener'
a537ab1a
U
680 _VALID_URL = r'https?://t.co/(?P<id>[^?]+)|tco:(?P<eid>[^?]+)'
681 _BASE_URL = 'https://t.co/'
86b868c6
U
682
683 def _real_extract(self, url):
a537ab1a
U
684 mobj = re.match(self._VALID_URL, url)
685 eid, id = mobj.group('eid', 'id')
686 if eid:
687 id = eid
688 url = self._BASE_URL + id
689 new_url = self._request_webpage(url, id, headers={'User-Agent': 'curl'}).geturl()
690 __UNSAFE_LINK = "https://twitter.com/safety/unsafe_link_warning?unsafe_link="
691 if new_url.startswith(__UNSAFE_LINK):
692 new_url = new_url.replace(__UNSAFE_LINK, "")
9e20a9c4 693 return self.url_result(new_url)