twitter.py 27 KB

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