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.

506 lines
20 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_urlparse
  6. from ..utils import (
  7. determine_ext,
  8. dict_get,
  9. ExtractorError,
  10. float_or_none,
  11. int_or_none,
  12. remove_end,
  13. try_get,
  14. xpath_text,
  15. )
  16. from .periscope import PeriscopeIE
  17. class TwitterBaseIE(InfoExtractor):
  18. def _extract_formats_from_vmap_url(self, vmap_url, video_id):
  19. vmap_data = self._download_xml(vmap_url, video_id)
  20. video_url = xpath_text(vmap_data, './/MediaFile').strip()
  21. if determine_ext(video_url) == 'm3u8':
  22. return self._extract_m3u8_formats(
  23. video_url, video_id, ext='mp4', m3u8_id='hls',
  24. entry_protocol='m3u8_native')
  25. return [{
  26. 'url': video_url,
  27. }]
  28. @staticmethod
  29. def _search_dimensions_in_video_url(a_format, video_url):
  30. m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
  31. if m:
  32. a_format.update({
  33. 'width': int(m.group('width')),
  34. 'height': int(m.group('height')),
  35. })
  36. class TwitterCardIE(TwitterBaseIE):
  37. IE_NAME = 'twitter:card'
  38. _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?P<path>cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
  39. _TESTS = [
  40. {
  41. 'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
  42. # MD5 checksums are different in different places
  43. 'info_dict': {
  44. 'id': '560070183650213889',
  45. 'ext': 'mp4',
  46. 'title': 'Twitter web player',
  47. 'thumbnail': r're:^https?://.*\.jpg$',
  48. 'duration': 30.033,
  49. },
  50. },
  51. {
  52. 'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
  53. 'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
  54. 'info_dict': {
  55. 'id': '623160978427936768',
  56. 'ext': 'mp4',
  57. 'title': 'Twitter web player',
  58. 'thumbnail': r're:^https?://.*(?:\bformat=|\.)jpg',
  59. },
  60. },
  61. {
  62. 'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
  63. 'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
  64. 'info_dict': {
  65. 'id': 'dq4Oj5quskI',
  66. 'ext': 'mp4',
  67. 'title': 'Ubuntu 11.10 Overview',
  68. 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
  69. 'upload_date': '20111013',
  70. 'uploader': 'OMG! Ubuntu!',
  71. 'uploader_id': 'omgubuntu',
  72. },
  73. 'add_ie': ['Youtube'],
  74. },
  75. {
  76. 'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
  77. 'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
  78. 'info_dict': {
  79. 'id': 'iBb2x00UVlv',
  80. 'ext': 'mp4',
  81. 'upload_date': '20151113',
  82. 'uploader_id': '1189339351084113920',
  83. 'uploader': 'ArsenalTerje',
  84. 'title': 'Vine by ArsenalTerje',
  85. 'timestamp': 1447451307,
  86. },
  87. 'add_ie': ['Vine'],
  88. }, {
  89. 'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
  90. 'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
  91. 'info_dict': {
  92. 'id': '705235433198714880',
  93. 'ext': 'mp4',
  94. 'title': 'Twitter web player',
  95. 'thumbnail': r're:^https?://.*',
  96. },
  97. }, {
  98. 'url': 'https://twitter.com/i/videos/752274308186120192',
  99. 'only_matching': True,
  100. },
  101. ]
  102. def _parse_media_info(self, media_info, video_id):
  103. formats = []
  104. for media_variant in media_info.get('variants', []):
  105. media_url = media_variant['url']
  106. if media_url.endswith('.m3u8'):
  107. formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
  108. elif media_url.endswith('.mpd'):
  109. formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
  110. else:
  111. tbr = int_or_none(dict_get(media_variant, ('bitRate', 'bitrate')), scale=1000)
  112. a_format = {
  113. 'url': media_url,
  114. 'format_id': 'http-%d' % tbr if tbr else 'http',
  115. 'tbr': tbr,
  116. }
  117. # Reported bitRate may be zero
  118. if not a_format['tbr']:
  119. del a_format['tbr']
  120. self._search_dimensions_in_video_url(a_format, media_url)
  121. formats.append(a_format)
  122. return formats
  123. def _extract_mobile_formats(self, username, video_id):
  124. webpage = self._download_webpage(
  125. 'https://mobile.twitter.com/%s/status/%s' % (username, video_id),
  126. video_id, 'Downloading mobile webpage',
  127. headers={
  128. # A recent mobile UA is necessary for `gt` cookie
  129. 'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
  130. })
  131. main_script_url = self._html_search_regex(
  132. r'<script[^>]+src="([^"]+main\.[^"]+)"', webpage, 'main script URL')
  133. main_script = self._download_webpage(
  134. main_script_url, video_id, 'Downloading main script')
  135. bearer_token = self._search_regex(
  136. r'BEARER_TOKEN\s*:\s*"([^"]+)"',
  137. main_script, 'bearer token')
  138. # https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
  139. api_data = self._download_json(
  140. 'https://api.twitter.com/1.1/statuses/show/%s.json' % video_id,
  141. video_id, 'Downloading API data',
  142. headers={
  143. 'Authorization': 'Bearer ' + bearer_token,
  144. })
  145. media_info = try_get(api_data, lambda o: o['extended_entities']['media'][0]['video_info']) or {}
  146. return self._parse_media_info(media_info, video_id)
  147. def _real_extract(self, url):
  148. path, video_id = re.search(self._VALID_URL, url).groups()
  149. config = None
  150. formats = []
  151. duration = None
  152. urls = [url]
  153. if path.startswith('cards/'):
  154. urls.append('https://twitter.com/i/videos/' + video_id)
  155. for u in urls:
  156. webpage = self._download_webpage(u, video_id)
  157. iframe_url = self._html_search_regex(
  158. r'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
  159. webpage, 'video iframe', default=None)
  160. if iframe_url:
  161. return self.url_result(iframe_url)
  162. config = self._parse_json(self._html_search_regex(
  163. r'data-(?:player-)?config="([^"]+)"', webpage,
  164. 'data player config', default='{}'),
  165. video_id)
  166. if config.get('source_type') == 'vine':
  167. return self.url_result(config['player_url'], 'Vine')
  168. periscope_url = PeriscopeIE._extract_url(webpage)
  169. if periscope_url:
  170. return self.url_result(periscope_url, PeriscopeIE.ie_key())
  171. video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
  172. if video_url:
  173. if determine_ext(video_url) == 'm3u8':
  174. formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
  175. else:
  176. f = {
  177. 'url': video_url,
  178. }
  179. self._search_dimensions_in_video_url(f, video_url)
  180. formats.append(f)
  181. vmap_url = config.get('vmapUrl') or config.get('vmap_url')
  182. if vmap_url:
  183. formats.extend(
  184. self._extract_formats_from_vmap_url(vmap_url, video_id))
  185. media_info = None
  186. for entity in config.get('status', {}).get('entities', []):
  187. if 'mediaInfo' in entity:
  188. media_info = entity['mediaInfo']
  189. if media_info:
  190. formats.extend(self._parse_media_info(media_info, video_id))
  191. duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
  192. username = config.get('user', {}).get('screen_name')
  193. if username:
  194. formats.extend(self._extract_mobile_formats(username, video_id))
  195. if formats:
  196. break
  197. self._remove_duplicate_formats(formats)
  198. self._sort_formats(formats)
  199. title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
  200. thumbnail = config.get('posterImageUrl') or config.get('image_src')
  201. duration = float_or_none(config.get('duration'), scale=1000) or duration
  202. return {
  203. 'id': video_id,
  204. 'title': title,
  205. 'thumbnail': thumbnail,
  206. 'duration': duration,
  207. 'formats': formats,
  208. }
  209. class TwitterIE(InfoExtractor):
  210. IE_NAME = 'twitter'
  211. _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
  212. _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
  213. _TEMPLATE_STATUSES_URL = 'https://twitter.com/statuses/%s'
  214. _TESTS = [{
  215. 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
  216. 'info_dict': {
  217. 'id': '643211948184596480',
  218. 'ext': 'mp4',
  219. 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
  220. 'thumbnail': r're:^https?://.*\.jpg',
  221. 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
  222. 'uploader': 'FREE THE NIPPLE',
  223. 'uploader_id': 'freethenipple',
  224. 'duration': 12.922,
  225. },
  226. }, {
  227. 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
  228. 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
  229. 'info_dict': {
  230. 'id': '657991469417025536',
  231. 'ext': 'mp4',
  232. 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
  233. 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
  234. 'thumbnail': r're:^https?://.*\.png',
  235. 'uploader': 'Gifs',
  236. 'uploader_id': 'giphz',
  237. },
  238. 'expected_warnings': ['height', 'width'],
  239. 'skip': 'Account suspended',
  240. }, {
  241. 'url': 'https://twitter.com/starwars/status/665052190608723968',
  242. 'info_dict': {
  243. 'id': '665052190608723968',
  244. 'ext': 'mp4',
  245. 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
  246. 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
  247. 'uploader_id': 'starwars',
  248. 'uploader': 'Star Wars',
  249. },
  250. }, {
  251. 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
  252. 'info_dict': {
  253. 'id': '705235433198714880',
  254. 'ext': 'mp4',
  255. 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
  256. 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
  257. 'uploader_id': 'BTNBrentYarina',
  258. 'uploader': 'Brent Yarina',
  259. },
  260. 'params': {
  261. # The same video as https://twitter.com/i/videos/tweet/705235433198714880
  262. # Test case of TwitterCardIE
  263. 'skip_download': True,
  264. },
  265. }, {
  266. 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
  267. 'info_dict': {
  268. 'id': '700207533655363584',
  269. 'ext': 'mp4',
  270. 'title': 'JG - BEAT PROD: @suhmeduh #Damndaniel',
  271. 'description': 'JG on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
  272. 'thumbnail': r're:^https?://.*\.jpg',
  273. 'uploader': 'JG',
  274. 'uploader_id': 'jaydingeer',
  275. 'duration': 30.0,
  276. },
  277. }, {
  278. 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
  279. 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
  280. 'info_dict': {
  281. 'id': 'MIOxnrUteUd',
  282. 'ext': 'mp4',
  283. 'title': 'Vince Mancini - Vine of the day',
  284. 'description': 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
  285. 'uploader': 'Vince Mancini',
  286. 'uploader_id': 'Filmdrunk',
  287. 'timestamp': 1402826626,
  288. 'upload_date': '20140615',
  289. },
  290. 'add_ie': ['Vine'],
  291. }, {
  292. 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
  293. 'info_dict': {
  294. 'id': '719944021058060289',
  295. 'ext': 'mp4',
  296. 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
  297. 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
  298. 'uploader_id': 'captainamerica',
  299. 'uploader': 'Captain America',
  300. 'duration': 3.17,
  301. },
  302. }, {
  303. 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
  304. 'info_dict': {
  305. 'id': '1zqKVVlkqLaKB',
  306. 'ext': 'mp4',
  307. 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
  308. 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
  309. 'upload_date': '20160923',
  310. 'uploader_id': 'OPP_HSD',
  311. 'uploader': 'Sgt Kerry Schmidt',
  312. 'timestamp': 1474613214,
  313. },
  314. 'add_ie': ['Periscope'],
  315. }, {
  316. # has mp4 formats via mobile API
  317. 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
  318. 'info_dict': {
  319. 'id': '852138619213144067',
  320. 'ext': 'mp4',
  321. 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
  322. 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
  323. 'uploader': 'عالم الأخبار',
  324. 'uploader_id': 'news_al3alm',
  325. 'duration': 277.4,
  326. },
  327. }, {
  328. 'url': 'https://twitter.com/i/web/status/910031516746514432',
  329. 'info_dict': {
  330. 'id': '910031516746514432',
  331. 'ext': 'mp4',
  332. '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.',
  333. 'thumbnail': r're:^https?://.*\.jpg',
  334. 'description': 'Préfet de Guadeloupe on Twitter: "[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"',
  335. 'uploader': 'Préfet de Guadeloupe',
  336. 'uploader_id': 'Prefet971',
  337. 'duration': 47.48,
  338. },
  339. 'params': {
  340. 'skip_download': True, # requires ffmpeg
  341. },
  342. }]
  343. def _real_extract(self, url):
  344. mobj = re.match(self._VALID_URL, url)
  345. user_id = mobj.group('user_id')
  346. twid = mobj.group('id')
  347. webpage, urlh = self._download_webpage_handle(
  348. self._TEMPLATE_STATUSES_URL % twid, twid)
  349. if 'twitter.com/account/suspended' in urlh.geturl():
  350. raise ExtractorError('Account suspended by Twitter.', expected=True)
  351. if user_id is None:
  352. mobj = re.match(self._VALID_URL, urlh.geturl())
  353. user_id = mobj.group('user_id')
  354. username = remove_end(self._og_search_title(webpage), ' on Twitter')
  355. title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
  356. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  357. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  358. info = {
  359. 'uploader_id': user_id,
  360. 'uploader': username,
  361. 'webpage_url': url,
  362. 'description': '%s on Twitter: "%s"' % (username, description),
  363. 'title': username + ' - ' + title,
  364. }
  365. mobj = re.search(r'''(?x)
  366. <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
  367. <source[^>]+video-src="(?P<url>[^"]+)"
  368. ''', webpage)
  369. if mobj:
  370. more_info = mobj.group('more_info')
  371. height = int_or_none(self._search_regex(
  372. r'data-height="(\d+)"', more_info, 'height', fatal=False))
  373. width = int_or_none(self._search_regex(
  374. r'data-width="(\d+)"', more_info, 'width', fatal=False))
  375. thumbnail = self._search_regex(
  376. r'poster="([^"]+)"', more_info, 'poster', fatal=False)
  377. info.update({
  378. 'id': twid,
  379. 'url': mobj.group('url'),
  380. 'height': height,
  381. 'width': width,
  382. 'thumbnail': thumbnail,
  383. })
  384. return info
  385. twitter_card_url = None
  386. if 'class="PlayableMedia' in webpage:
  387. twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
  388. else:
  389. twitter_card_iframe_url = self._search_regex(
  390. r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
  391. webpage, 'Twitter card iframe URL', default=None, group='url')
  392. if twitter_card_iframe_url:
  393. twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
  394. if twitter_card_url:
  395. info.update({
  396. '_type': 'url_transparent',
  397. 'ie_key': 'TwitterCard',
  398. 'url': twitter_card_url,
  399. })
  400. return info
  401. raise ExtractorError('There\'s no video in this tweet.')
  402. class TwitterAmplifyIE(TwitterBaseIE):
  403. IE_NAME = 'twitter:amplify'
  404. _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  405. _TEST = {
  406. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  407. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  408. 'info_dict': {
  409. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  410. 'ext': 'mp4',
  411. 'title': 'Twitter Video',
  412. 'thumbnail': 're:^https?://.*',
  413. },
  414. }
  415. def _real_extract(self, url):
  416. video_id = self._match_id(url)
  417. webpage = self._download_webpage(url, video_id)
  418. vmap_url = self._html_search_meta(
  419. 'twitter:amplify:vmap', webpage, 'vmap url')
  420. formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
  421. thumbnails = []
  422. thumbnail = self._html_search_meta(
  423. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  424. def _find_dimension(target):
  425. w = int_or_none(self._html_search_meta(
  426. 'twitter:%s:width' % target, webpage, fatal=False))
  427. h = int_or_none(self._html_search_meta(
  428. 'twitter:%s:height' % target, webpage, fatal=False))
  429. return w, h
  430. if thumbnail:
  431. thumbnail_w, thumbnail_h = _find_dimension('image')
  432. thumbnails.append({
  433. 'url': thumbnail,
  434. 'width': thumbnail_w,
  435. 'height': thumbnail_h,
  436. })
  437. video_w, video_h = _find_dimension('player')
  438. formats[0].update({
  439. 'width': video_w,
  440. 'height': video_h,
  441. })
  442. return {
  443. 'id': video_id,
  444. 'title': 'Twitter Video',
  445. 'formats': formats,
  446. 'thumbnails': thumbnails,
  447. }