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.

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