logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

twitter.py (28035B)


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