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