You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

593 lines
24 KiB

  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. }, {
  301. 'url': 'https://twitter.com/i/web/status/910031516746514432',
  302. 'info_dict': {
  303. 'id': '910031516746514432',
  304. 'ext': 'mp4',
  305. '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.',
  306. 'thumbnail': r're:^https?://.*\.jpg',
  307. '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',
  308. 'uploader': 'Préfet de Guadeloupe',
  309. 'uploader_id': 'Prefet971',
  310. 'duration': 47.48,
  311. 'timestamp': 1505803395,
  312. 'upload_date': '20170919',
  313. },
  314. 'params': {
  315. 'skip_download': True, # requires ffmpeg
  316. },
  317. }, {
  318. # card via api.twitter.com/1.1/videos/tweet/config
  319. 'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
  320. 'info_dict': {
  321. 'id': '1001551623938805763',
  322. 'ext': 'mp4',
  323. 'title': 're:.*?Shep is on a roll today.*?',
  324. 'thumbnail': r're:^https?://.*\.jpg',
  325. 'description': 'md5:37b9f2ff31720cef23b2bd42ee8a0f09',
  326. 'uploader': 'Lis Power',
  327. 'uploader_id': 'LisPower1',
  328. 'duration': 111.278,
  329. 'timestamp': 1527623489,
  330. 'upload_date': '20180529',
  331. },
  332. 'params': {
  333. 'skip_download': True, # requires ffmpeg
  334. },
  335. }, {
  336. 'url': 'https://twitter.com/foobar/status/1087791357756956680',
  337. 'info_dict': {
  338. 'id': '1087791357756956680',
  339. 'ext': 'mp4',
  340. '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!',
  341. 'thumbnail': r're:^https?://.*\.jpg',
  342. 'description': 'md5:6dfd341a3310fb97d80d2bf7145df976',
  343. 'uploader': 'Twitter',
  344. 'uploader_id': 'Twitter',
  345. 'duration': 61.567,
  346. 'timestamp': 1548184644,
  347. 'upload_date': '20190122',
  348. },
  349. }, {
  350. # not available in Periscope
  351. 'url': 'https://twitter.com/ViviEducation/status/1136534865145286656',
  352. 'info_dict': {
  353. 'id': '1vOGwqejwoWxB',
  354. 'ext': 'mp4',
  355. 'title': 'Vivi - Vivi founder @lior_rauchy announcing our new student feedback tool live at @EduTECH_AU #EduTECH2019',
  356. 'uploader': 'Vivi',
  357. 'uploader_id': '1eVjYOLGkGrQL',
  358. },
  359. 'add_ie': ['TwitterBroadcast'],
  360. }, {
  361. # Twitch Clip Embed
  362. 'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
  363. 'only_matching': True,
  364. }]
  365. def _real_extract(self, url):
  366. twid = self._match_id(url)
  367. status = self._call_api(
  368. 'statuses/show/%s.json' % twid, twid, {
  369. 'cards_platform': 'Web-12',
  370. 'include_cards': 1,
  371. 'include_reply_count': 1,
  372. 'include_user_entities': 0,
  373. 'tweet_mode': 'extended',
  374. })
  375. title = description = status['full_text'].replace('\n', ' ')
  376. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  377. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  378. user = status.get('user') or {}
  379. uploader = user.get('name')
  380. if uploader:
  381. title = '%s - %s' % (uploader, title)
  382. uploader_id = user.get('screen_name')
  383. tags = []
  384. for hashtag in (try_get(status, lambda x: x['entities']['hashtags'], list) or []):
  385. hashtag_text = hashtag.get('text')
  386. if not hashtag_text:
  387. continue
  388. tags.append(hashtag_text)
  389. info = {
  390. 'id': twid,
  391. 'title': title,
  392. 'description': description,
  393. 'uploader': uploader,
  394. 'timestamp': unified_timestamp(status.get('created_at')),
  395. 'uploader_id': uploader_id,
  396. 'uploader_url': 'https://twitter.com/' + uploader_id if uploader_id else None,
  397. 'like_count': int_or_none(status.get('favorite_count')),
  398. 'repost_count': int_or_none(status.get('retweet_count')),
  399. 'comment_count': int_or_none(status.get('reply_count')),
  400. 'age_limit': 18 if status.get('possibly_sensitive') else 0,
  401. 'tags': tags,
  402. }
  403. media = try_get(status, lambda x: x['extended_entities']['media'][0])
  404. if media and media.get('type') != 'photo':
  405. video_info = media.get('video_info') or {}
  406. formats = []
  407. for variant in video_info.get('variants', []):
  408. formats.extend(self._extract_variant_formats(variant, twid))
  409. self._sort_formats(formats)
  410. thumbnails = []
  411. media_url = media.get('media_url_https') or media.get('media_url')
  412. if media_url:
  413. def add_thumbnail(name, size):
  414. thumbnails.append({
  415. 'id': name,
  416. 'url': update_url_query(media_url, {'name': name}),
  417. 'width': int_or_none(size.get('w') or size.get('width')),
  418. 'height': int_or_none(size.get('h') or size.get('height')),
  419. })
  420. for name, size in media.get('sizes', {}).items():
  421. add_thumbnail(name, size)
  422. add_thumbnail('orig', media.get('original_info') or {})
  423. info.update({
  424. 'formats': formats,
  425. 'thumbnails': thumbnails,
  426. 'duration': float_or_none(video_info.get('duration_millis'), 1000),
  427. })
  428. else:
  429. card = status.get('card')
  430. if card:
  431. binding_values = card['binding_values']
  432. def get_binding_value(k):
  433. o = binding_values.get(k) or {}
  434. return try_get(o, lambda x: x[x['type'].lower() + '_value'])
  435. card_name = card['name'].split(':')[-1]
  436. if card_name == 'amplify':
  437. formats = self._extract_formats_from_vmap_url(
  438. get_binding_value('amplify_url_vmap'),
  439. get_binding_value('amplify_content_id') or twid)
  440. self._sort_formats(formats)
  441. thumbnails = []
  442. for suffix in ('_small', '', '_large', '_x_large', '_original'):
  443. image = get_binding_value('player_image' + suffix) or {}
  444. image_url = image.get('url')
  445. if not image_url or '/player-placeholder' in image_url:
  446. continue
  447. thumbnails.append({
  448. 'id': suffix[1:] if suffix else 'medium',
  449. 'url': image_url,
  450. 'width': int_or_none(image.get('width')),
  451. 'height': int_or_none(image.get('height')),
  452. })
  453. info.update({
  454. 'formats': formats,
  455. 'thumbnails': thumbnails,
  456. 'duration': int_or_none(get_binding_value(
  457. 'content_duration_seconds')),
  458. })
  459. elif card_name == 'player':
  460. info.update({
  461. '_type': 'url',
  462. 'url': get_binding_value('player_url'),
  463. })
  464. elif card_name == 'periscope_broadcast':
  465. info.update({
  466. '_type': 'url',
  467. 'url': get_binding_value('url') or get_binding_value('player_url'),
  468. 'ie_key': PeriscopeIE.ie_key(),
  469. })
  470. elif card_name == 'broadcast':
  471. info.update({
  472. '_type': 'url',
  473. 'url': get_binding_value('broadcast_url'),
  474. 'ie_key': TwitterBroadcastIE.ie_key(),
  475. })
  476. else:
  477. raise ExtractorError('Unsupported Twitter Card.')
  478. else:
  479. expanded_url = try_get(status, lambda x: x['entities']['urls'][0]['expanded_url'])
  480. if not expanded_url:
  481. raise ExtractorError("There's no video in this tweet.")
  482. info.update({
  483. '_type': 'url',
  484. 'url': expanded_url,
  485. })
  486. return info
  487. class TwitterAmplifyIE(TwitterBaseIE):
  488. IE_NAME = 'twitter:amplify'
  489. _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  490. _TEST = {
  491. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  492. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  493. 'info_dict': {
  494. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  495. 'ext': 'mp4',
  496. 'title': 'Twitter Video',
  497. 'thumbnail': 're:^https?://.*',
  498. },
  499. }
  500. def _real_extract(self, url):
  501. video_id = self._match_id(url)
  502. webpage = self._download_webpage(url, video_id)
  503. vmap_url = self._html_search_meta(
  504. 'twitter:amplify:vmap', webpage, 'vmap url')
  505. formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
  506. thumbnails = []
  507. thumbnail = self._html_search_meta(
  508. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  509. def _find_dimension(target):
  510. w = int_or_none(self._html_search_meta(
  511. 'twitter:%s:width' % target, webpage, fatal=False))
  512. h = int_or_none(self._html_search_meta(
  513. 'twitter:%s:height' % target, webpage, fatal=False))
  514. return w, h
  515. if thumbnail:
  516. thumbnail_w, thumbnail_h = _find_dimension('image')
  517. thumbnails.append({
  518. 'url': thumbnail,
  519. 'width': thumbnail_w,
  520. 'height': thumbnail_h,
  521. })
  522. video_w, video_h = _find_dimension('player')
  523. formats[0].update({
  524. 'width': video_w,
  525. 'height': video_h,
  526. })
  527. return {
  528. 'id': video_id,
  529. 'title': 'Twitter Video',
  530. 'formats': formats,
  531. 'thumbnails': thumbnails,
  532. }
  533. class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE):
  534. IE_NAME = 'twitter:broadcast'
  535. _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/broadcasts/(?P<id>[0-9a-zA-Z]{13})'
  536. def _real_extract(self, url):
  537. broadcast_id = self._match_id(url)
  538. broadcast = self._call_api(
  539. 'broadcasts/show.json', broadcast_id,
  540. {'ids': broadcast_id})['broadcasts'][broadcast_id]
  541. info = self._parse_broadcast_data(broadcast, broadcast_id)
  542. media_key = broadcast['media_key']
  543. source = self._call_api(
  544. 'live_video_stream/status/' + media_key, media_key)['source']
  545. m3u8_url = source.get('noRedirectPlaybackUrl') or source['location']
  546. if '/live_video_stream/geoblocked/' in m3u8_url:
  547. self.raise_geo_restricted()
  548. m3u8_id = compat_parse_qs(compat_urllib_parse_urlparse(
  549. m3u8_url).query).get('type', [None])[0]
  550. state, width, height = self._extract_common_format_info(broadcast)
  551. info['formats'] = self._extract_pscp_m3u8_formats(
  552. m3u8_url, broadcast_id, m3u8_id, state, width, height)
  553. return info