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.

495 lines
19 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')) 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/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
  213. _TEMPLATE_URL = 'https://twitter.com/%s/status/%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. },
  225. 'params': {
  226. 'skip_download': True, # requires ffmpeg
  227. },
  228. }, {
  229. 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
  230. 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
  231. 'info_dict': {
  232. 'id': '657991469417025536',
  233. 'ext': 'mp4',
  234. 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
  235. 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
  236. 'thumbnail': r're:^https?://.*\.png',
  237. 'uploader': 'Gifs',
  238. 'uploader_id': 'giphz',
  239. },
  240. 'expected_warnings': ['height', 'width'],
  241. 'skip': 'Account suspended',
  242. }, {
  243. 'url': 'https://twitter.com/starwars/status/665052190608723968',
  244. 'md5': '39b7199856dee6cd4432e72c74bc69d4',
  245. 'info_dict': {
  246. 'id': '665052190608723968',
  247. 'ext': 'mp4',
  248. 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
  249. 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
  250. 'uploader_id': 'starwars',
  251. 'uploader': 'Star Wars',
  252. },
  253. }, {
  254. 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
  255. 'info_dict': {
  256. 'id': '705235433198714880',
  257. 'ext': 'mp4',
  258. 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
  259. 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
  260. 'uploader_id': 'BTNBrentYarina',
  261. 'uploader': 'Brent Yarina',
  262. },
  263. 'params': {
  264. # The same video as https://twitter.com/i/videos/tweet/705235433198714880
  265. # Test case of TwitterCardIE
  266. 'skip_download': True,
  267. },
  268. }, {
  269. 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
  270. 'md5': '',
  271. 'info_dict': {
  272. 'id': '700207533655363584',
  273. 'ext': 'mp4',
  274. 'title': 'Donte - BEAT PROD: @suhmeduh #Damndaniel',
  275. 'description': 'Donte on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
  276. 'thumbnail': r're:^https?://.*\.jpg',
  277. 'uploader': 'Donte',
  278. 'uploader_id': 'jaydingeer',
  279. },
  280. 'params': {
  281. 'skip_download': True, # requires ffmpeg
  282. },
  283. }, {
  284. 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
  285. 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
  286. 'info_dict': {
  287. 'id': 'MIOxnrUteUd',
  288. 'ext': 'mp4',
  289. 'title': 'FilmDrunk - Vine of the day',
  290. 'description': 'FilmDrunk on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
  291. 'uploader': 'FilmDrunk',
  292. 'uploader_id': 'Filmdrunk',
  293. 'timestamp': 1402826626,
  294. 'upload_date': '20140615',
  295. },
  296. 'add_ie': ['Vine'],
  297. }, {
  298. 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
  299. 'info_dict': {
  300. 'id': '719944021058060289',
  301. 'ext': 'mp4',
  302. 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
  303. 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
  304. 'uploader_id': 'captainamerica',
  305. 'uploader': 'Captain America',
  306. },
  307. 'params': {
  308. 'skip_download': True, # requires ffmpeg
  309. },
  310. }, {
  311. 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
  312. 'info_dict': {
  313. 'id': '1zqKVVlkqLaKB',
  314. 'ext': 'mp4',
  315. 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
  316. 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
  317. 'upload_date': '20160923',
  318. 'uploader_id': 'OPP_HSD',
  319. 'uploader': 'Sgt Kerry Schmidt',
  320. 'timestamp': 1474613214,
  321. },
  322. 'add_ie': ['Periscope'],
  323. }, {
  324. # has mp4 formats via mobile API
  325. 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
  326. 'info_dict': {
  327. 'id': '852138619213144067',
  328. 'ext': 'mp4',
  329. 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
  330. 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
  331. 'uploader': 'عالم الأخبار',
  332. 'uploader_id': 'news_al3alm',
  333. },
  334. 'params': {
  335. 'format': 'best[format_id^=http-]',
  336. },
  337. }]
  338. def _real_extract(self, url):
  339. mobj = re.match(self._VALID_URL, url)
  340. user_id = mobj.group('user_id')
  341. twid = mobj.group('id')
  342. webpage, urlh = self._download_webpage_handle(
  343. self._TEMPLATE_URL % (user_id, twid), twid)
  344. if 'twitter.com/account/suspended' in urlh.geturl():
  345. raise ExtractorError('Account suspended by Twitter.', expected=True)
  346. username = remove_end(self._og_search_title(webpage), ' on Twitter')
  347. title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
  348. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  349. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  350. info = {
  351. 'uploader_id': user_id,
  352. 'uploader': username,
  353. 'webpage_url': url,
  354. 'description': '%s on Twitter: "%s"' % (username, description),
  355. 'title': username + ' - ' + title,
  356. }
  357. mobj = re.search(r'''(?x)
  358. <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
  359. <source[^>]+video-src="(?P<url>[^"]+)"
  360. ''', webpage)
  361. if mobj:
  362. more_info = mobj.group('more_info')
  363. height = int_or_none(self._search_regex(
  364. r'data-height="(\d+)"', more_info, 'height', fatal=False))
  365. width = int_or_none(self._search_regex(
  366. r'data-width="(\d+)"', more_info, 'width', fatal=False))
  367. thumbnail = self._search_regex(
  368. r'poster="([^"]+)"', more_info, 'poster', fatal=False)
  369. info.update({
  370. 'id': twid,
  371. 'url': mobj.group('url'),
  372. 'height': height,
  373. 'width': width,
  374. 'thumbnail': thumbnail,
  375. })
  376. return info
  377. twitter_card_url = None
  378. if 'class="PlayableMedia' in webpage:
  379. twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
  380. else:
  381. twitter_card_iframe_url = self._search_regex(
  382. r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
  383. webpage, 'Twitter card iframe URL', default=None, group='url')
  384. if twitter_card_iframe_url:
  385. twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
  386. if twitter_card_url:
  387. info.update({
  388. '_type': 'url_transparent',
  389. 'ie_key': 'TwitterCard',
  390. 'url': twitter_card_url,
  391. })
  392. return info
  393. raise ExtractorError('There\'s no video in this tweet.')
  394. class TwitterAmplifyIE(TwitterBaseIE):
  395. IE_NAME = 'twitter:amplify'
  396. _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  397. _TEST = {
  398. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  399. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  400. 'info_dict': {
  401. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  402. 'ext': 'mp4',
  403. 'title': 'Twitter Video',
  404. 'thumbnail': 're:^https?://.*',
  405. },
  406. }
  407. def _real_extract(self, url):
  408. video_id = self._match_id(url)
  409. webpage = self._download_webpage(url, video_id)
  410. vmap_url = self._html_search_meta(
  411. 'twitter:amplify:vmap', webpage, 'vmap url')
  412. formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
  413. thumbnails = []
  414. thumbnail = self._html_search_meta(
  415. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  416. def _find_dimension(target):
  417. w = int_or_none(self._html_search_meta(
  418. 'twitter:%s:width' % target, webpage, fatal=False))
  419. h = int_or_none(self._html_search_meta(
  420. 'twitter:%s:height' % target, webpage, fatal=False))
  421. return w, h
  422. if thumbnail:
  423. thumbnail_w, thumbnail_h = _find_dimension('image')
  424. thumbnails.append({
  425. 'url': thumbnail,
  426. 'width': thumbnail_w,
  427. 'height': thumbnail_h,
  428. })
  429. video_w, video_h = _find_dimension('player')
  430. formats[0].update({
  431. 'width': video_w,
  432. 'height': video_h,
  433. })
  434. return {
  435. 'id': video_id,
  436. 'title': 'Twitter Video',
  437. 'formats': formats,
  438. 'thumbnails': thumbnails,
  439. }