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.

531 lines
21 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import itertools
  6. from .common import InfoExtractor
  7. from .subtitles import SubtitlesInfoExtractor
  8. from ..utils import (
  9. compat_HTTPError,
  10. compat_urllib_parse,
  11. compat_urllib_request,
  12. clean_html,
  13. get_element_by_attribute,
  14. ExtractorError,
  15. RegexNotFoundError,
  16. std_headers,
  17. unsmuggle_url,
  18. urlencode_postdata,
  19. int_or_none,
  20. )
  21. class VimeoBaseInfoExtractor(InfoExtractor):
  22. _NETRC_MACHINE = 'vimeo'
  23. _LOGIN_REQUIRED = False
  24. def _login(self):
  25. (username, password) = self._get_login_info()
  26. if username is None:
  27. if self._LOGIN_REQUIRED:
  28. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  29. return
  30. self.report_login()
  31. login_url = 'https://vimeo.com/log_in'
  32. webpage = self._download_webpage(login_url, None, False)
  33. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  34. data = urlencode_postdata({
  35. 'email': username,
  36. 'password': password,
  37. 'action': 'login',
  38. 'service': 'vimeo',
  39. 'token': token,
  40. })
  41. login_request = compat_urllib_request.Request(login_url, data)
  42. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  43. login_request.add_header('Cookie', 'xsrft=%s' % token)
  44. self._download_webpage(login_request, None, False, 'Wrong login info')
  45. class VimeoIE(VimeoBaseInfoExtractor, SubtitlesInfoExtractor):
  46. """Information extractor for vimeo.com."""
  47. # _VALID_URL matches Vimeo URLs
  48. _VALID_URL = r'''(?x)
  49. (?P<proto>(?:https?:)?//)?
  50. (?:(?:www|(?P<player>player))\.)?
  51. vimeo(?P<pro>pro)?\.com/
  52. (?!channels/[^/?#]+/?(?:$|[?#])|album/)
  53. (?:.*?/)?
  54. (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
  55. (?:videos?/)?
  56. (?P<id>[0-9]+)
  57. /?(?:[?&].*)?(?:[#].*)?$'''
  58. IE_NAME = 'vimeo'
  59. _TESTS = [
  60. {
  61. 'url': 'http://vimeo.com/56015672#at=0',
  62. 'md5': '8879b6cc097e987f02484baf890129e5',
  63. 'info_dict': {
  64. 'id': '56015672',
  65. 'ext': 'mp4',
  66. "upload_date": "20121220",
  67. "description": "This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  68. "uploader_id": "user7108434",
  69. "uploader": "Filippo Valsorda",
  70. "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  71. "duration": 10,
  72. },
  73. },
  74. {
  75. 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  76. 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
  77. 'note': 'Vimeo Pro video (#1197)',
  78. 'info_dict': {
  79. 'id': '68093876',
  80. 'ext': 'mp4',
  81. 'uploader_id': 'openstreetmapus',
  82. 'uploader': 'OpenStreetMap US',
  83. 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  84. 'duration': 1595,
  85. },
  86. },
  87. {
  88. 'url': 'http://player.vimeo.com/video/54469442',
  89. 'md5': '619b811a4417aa4abe78dc653becf511',
  90. 'note': 'Videos that embed the url in the player page',
  91. 'info_dict': {
  92. 'id': '54469442',
  93. 'ext': 'mp4',
  94. 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
  95. 'uploader': 'The BLN & Business of Software',
  96. 'uploader_id': 'theblnbusinessofsoftware',
  97. 'duration': 3610,
  98. },
  99. },
  100. {
  101. 'url': 'http://vimeo.com/68375962',
  102. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  103. 'note': 'Video protected with password',
  104. 'info_dict': {
  105. 'id': '68375962',
  106. 'ext': 'mp4',
  107. 'title': 'youtube-dl password protected test video',
  108. 'upload_date': '20130614',
  109. 'uploader_id': 'user18948128',
  110. 'uploader': 'Jaime Marquínez Ferrándiz',
  111. 'duration': 10,
  112. },
  113. 'params': {
  114. 'videopassword': 'youtube-dl',
  115. },
  116. },
  117. {
  118. 'url': 'http://vimeo.com/channels/keypeele/75629013',
  119. 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
  120. 'note': 'Video is freely available via original URL '
  121. 'and protected with password when accessed via http://vimeo.com/75629013',
  122. 'info_dict': {
  123. 'id': '75629013',
  124. 'ext': 'mp4',
  125. 'title': 'Key & Peele: Terrorist Interrogation',
  126. 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
  127. 'uploader_id': 'atencio',
  128. 'uploader': 'Peter Atencio',
  129. 'duration': 187,
  130. },
  131. },
  132. {
  133. 'url': 'http://vimeo.com/76979871',
  134. 'md5': '3363dd6ffebe3784d56f4132317fd446',
  135. 'note': 'Video with subtitles',
  136. 'info_dict': {
  137. 'id': '76979871',
  138. 'ext': 'mp4',
  139. 'title': 'The New Vimeo Player (You Know, For Videos)',
  140. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  141. 'upload_date': '20131015',
  142. 'uploader_id': 'staff',
  143. 'uploader': 'Vimeo Staff',
  144. 'duration': 62,
  145. }
  146. },
  147. ]
  148. def _verify_video_password(self, url, video_id, webpage):
  149. password = self._downloader.params.get('videopassword', None)
  150. if password is None:
  151. raise ExtractorError('This video is protected by a password, use the --video-password option')
  152. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  153. data = compat_urllib_parse.urlencode({
  154. 'password': password,
  155. 'token': token,
  156. })
  157. # I didn't manage to use the password with https
  158. if url.startswith('https'):
  159. pass_url = url.replace('https', 'http')
  160. else:
  161. pass_url = url
  162. password_request = compat_urllib_request.Request(pass_url + '/password', data)
  163. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  164. password_request.add_header('Cookie', 'xsrft=%s' % token)
  165. self._download_webpage(password_request, video_id,
  166. 'Verifying the password',
  167. 'Wrong password')
  168. def _verify_player_video_password(self, url, video_id):
  169. password = self._downloader.params.get('videopassword', None)
  170. if password is None:
  171. raise ExtractorError('This video is protected by a password, use the --video-password option')
  172. data = compat_urllib_parse.urlencode({'password': password})
  173. pass_url = url + '/check-password'
  174. password_request = compat_urllib_request.Request(pass_url, data)
  175. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  176. return self._download_json(
  177. password_request, video_id,
  178. 'Verifying the password',
  179. 'Wrong password')
  180. def _real_initialize(self):
  181. self._login()
  182. def _real_extract(self, url):
  183. url, data = unsmuggle_url(url)
  184. headers = std_headers
  185. if data is not None:
  186. headers = headers.copy()
  187. headers.update(data)
  188. if 'Referer' not in headers:
  189. headers['Referer'] = url
  190. # Extract ID from URL
  191. mobj = re.match(self._VALID_URL, url)
  192. video_id = mobj.group('id')
  193. if mobj.group('pro') or mobj.group('player'):
  194. url = 'http://player.vimeo.com/video/' + video_id
  195. # Retrieve video webpage to extract further information
  196. request = compat_urllib_request.Request(url, None, headers)
  197. try:
  198. webpage = self._download_webpage(request, video_id)
  199. except ExtractorError as ee:
  200. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  201. errmsg = ee.cause.read()
  202. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  203. raise ExtractorError(
  204. 'Cannot download embed-only video without embedding '
  205. 'URL. Please call youtube-dl with the URL of the page '
  206. 'that embeds this video.',
  207. expected=True)
  208. raise
  209. # Now we begin extracting as much information as we can from what we
  210. # retrieved. First we extract the information common to all extractors,
  211. # and latter we extract those that are Vimeo specific.
  212. self.report_extraction(video_id)
  213. # Extract the config JSON
  214. try:
  215. try:
  216. config_url = self._html_search_regex(
  217. r' data-config-url="(.+?)"', webpage, 'config URL')
  218. config_json = self._download_webpage(config_url, video_id)
  219. config = json.loads(config_json)
  220. except RegexNotFoundError:
  221. # For pro videos or player.vimeo.com urls
  222. # We try to find out to which variable is assigned the config dic
  223. m_variable_name = re.search('(\w)\.video\.id', webpage)
  224. if m_variable_name is not None:
  225. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  226. else:
  227. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  228. config = self._search_regex(config_re, webpage, 'info section',
  229. flags=re.DOTALL)
  230. config = json.loads(config)
  231. except Exception as e:
  232. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  233. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  234. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  235. self._verify_video_password(url, video_id, webpage)
  236. return self._real_extract(url)
  237. else:
  238. raise ExtractorError('Unable to extract info section',
  239. cause=e)
  240. else:
  241. if config.get('view') == 4:
  242. config = self._verify_player_video_password(url, video_id)
  243. # Extract title
  244. video_title = config["video"]["title"]
  245. # Extract uploader and uploader_id
  246. video_uploader = config["video"]["owner"]["name"]
  247. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  248. # Extract video thumbnail
  249. video_thumbnail = config["video"].get("thumbnail")
  250. if video_thumbnail is None:
  251. video_thumbs = config["video"].get("thumbs")
  252. if video_thumbs and isinstance(video_thumbs, dict):
  253. _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
  254. # Extract video description
  255. video_description = None
  256. try:
  257. video_description = get_element_by_attribute("class", "description_wrapper", webpage)
  258. if video_description:
  259. video_description = clean_html(video_description)
  260. except AssertionError as err:
  261. # On some pages like (http://player.vimeo.com/video/54469442) the
  262. # html tags are not closed, python 2.6 cannot handle it
  263. if err.args[0] == 'we should not get here!':
  264. pass
  265. else:
  266. raise
  267. # Extract video duration
  268. video_duration = int_or_none(config["video"].get("duration"))
  269. # Extract upload date
  270. video_upload_date = None
  271. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  272. if mobj is not None:
  273. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  274. try:
  275. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  276. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  277. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  278. except RegexNotFoundError:
  279. # This info is only available in vimeo.com/{id} urls
  280. view_count = None
  281. like_count = None
  282. comment_count = None
  283. # Vimeo specific: extract request signature and timestamp
  284. sig = config['request']['signature']
  285. timestamp = config['request']['timestamp']
  286. # Vimeo specific: extract video codec and quality information
  287. # First consider quality, then codecs, then take everything
  288. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  289. files = {'hd': [], 'sd': [], 'other': []}
  290. config_files = config["video"].get("files") or config["request"].get("files")
  291. for codec_name, codec_extension in codecs:
  292. for quality in config_files.get(codec_name, []):
  293. format_id = '-'.join((codec_name, quality)).lower()
  294. key = quality if quality in files else 'other'
  295. video_url = None
  296. if isinstance(config_files[codec_name], dict):
  297. file_info = config_files[codec_name][quality]
  298. video_url = file_info.get('url')
  299. else:
  300. file_info = {}
  301. if video_url is None:
  302. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  303. % (video_id, sig, timestamp, quality, codec_name.upper())
  304. files[key].append({
  305. 'ext': codec_extension,
  306. 'url': video_url,
  307. 'format_id': format_id,
  308. 'width': file_info.get('width'),
  309. 'height': file_info.get('height'),
  310. })
  311. formats = []
  312. for key in ('other', 'sd', 'hd'):
  313. formats += files[key]
  314. if len(formats) == 0:
  315. raise ExtractorError('No known codec found')
  316. subtitles = {}
  317. text_tracks = config['request'].get('text_tracks')
  318. if text_tracks:
  319. for tt in text_tracks:
  320. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  321. video_subtitles = self.extract_subtitles(video_id, subtitles)
  322. if self._downloader.params.get('listsubtitles', False):
  323. self._list_available_subtitles(video_id, subtitles)
  324. return
  325. return {
  326. 'id': video_id,
  327. 'uploader': video_uploader,
  328. 'uploader_id': video_uploader_id,
  329. 'upload_date': video_upload_date,
  330. 'title': video_title,
  331. 'thumbnail': video_thumbnail,
  332. 'description': video_description,
  333. 'duration': video_duration,
  334. 'formats': formats,
  335. 'webpage_url': url,
  336. 'view_count': view_count,
  337. 'like_count': like_count,
  338. 'comment_count': comment_count,
  339. 'subtitles': video_subtitles,
  340. }
  341. class VimeoChannelIE(InfoExtractor):
  342. IE_NAME = 'vimeo:channel'
  343. _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
  344. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  345. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  346. _TESTS = [{
  347. 'url': 'http://vimeo.com/channels/tributes',
  348. 'info_dict': {
  349. 'title': 'Vimeo Tributes',
  350. },
  351. 'playlist_mincount': 25,
  352. }]
  353. def _page_url(self, base_url, pagenum):
  354. return '%s/videos/page:%d/' % (base_url, pagenum)
  355. def _extract_list_title(self, webpage):
  356. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  357. def _extract_videos(self, list_id, base_url):
  358. video_ids = []
  359. for pagenum in itertools.count(1):
  360. webpage = self._download_webpage(
  361. self._page_url(base_url, pagenum), list_id,
  362. 'Downloading page %s' % pagenum)
  363. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  364. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  365. break
  366. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  367. for video_id in video_ids]
  368. return {'_type': 'playlist',
  369. 'id': list_id,
  370. 'title': self._extract_list_title(webpage),
  371. 'entries': entries,
  372. }
  373. def _real_extract(self, url):
  374. mobj = re.match(self._VALID_URL, url)
  375. channel_id = mobj.group('id')
  376. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  377. class VimeoUserIE(VimeoChannelIE):
  378. IE_NAME = 'vimeo:user'
  379. _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  380. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  381. _TESTS = [{
  382. 'url': 'http://vimeo.com/nkistudio/videos',
  383. 'info_dict': {
  384. 'title': 'Nki',
  385. },
  386. 'playlist_mincount': 66,
  387. }]
  388. def _real_extract(self, url):
  389. mobj = re.match(self._VALID_URL, url)
  390. name = mobj.group('name')
  391. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  392. class VimeoAlbumIE(VimeoChannelIE):
  393. IE_NAME = 'vimeo:album'
  394. _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
  395. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  396. _TESTS = [{
  397. 'url': 'http://vimeo.com/album/2632481',
  398. 'info_dict': {
  399. 'title': 'Staff Favorites: November 2013',
  400. },
  401. 'playlist_mincount': 13,
  402. }]
  403. def _page_url(self, base_url, pagenum):
  404. return '%s/page:%d/' % (base_url, pagenum)
  405. def _real_extract(self, url):
  406. mobj = re.match(self._VALID_URL, url)
  407. album_id = mobj.group('id')
  408. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  409. class VimeoGroupsIE(VimeoAlbumIE):
  410. IE_NAME = 'vimeo:group'
  411. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  412. _TESTS = [{
  413. 'url': 'http://vimeo.com/groups/rolexawards',
  414. 'info_dict': {
  415. 'title': 'Rolex Awards for Enterprise',
  416. },
  417. 'playlist_mincount': 73,
  418. }]
  419. def _extract_list_title(self, webpage):
  420. return self._og_search_title(webpage)
  421. def _real_extract(self, url):
  422. mobj = re.match(self._VALID_URL, url)
  423. name = mobj.group('name')
  424. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  425. class VimeoReviewIE(InfoExtractor):
  426. IE_NAME = 'vimeo:review'
  427. IE_DESC = 'Review pages on vimeo'
  428. _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  429. _TESTS = [{
  430. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  431. 'file': '75524534.mp4',
  432. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  433. 'info_dict': {
  434. 'title': "DICK HARDWICK 'Comedian'",
  435. 'uploader': 'Richard Hardwick',
  436. }
  437. }, {
  438. 'note': 'video player needs Referer',
  439. 'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
  440. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  441. 'info_dict': {
  442. 'id': '91613211',
  443. 'ext': 'mp4',
  444. 'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
  445. 'uploader': 'DevWeek Events',
  446. 'duration': 2773,
  447. 'thumbnail': 're:^https?://.*\.jpg$',
  448. }
  449. }]
  450. def _real_extract(self, url):
  451. mobj = re.match(self._VALID_URL, url)
  452. video_id = mobj.group('id')
  453. player_url = 'https://player.vimeo.com/player/' + video_id
  454. return self.url_result(player_url, 'Vimeo', video_id)
  455. class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
  456. IE_NAME = 'vimeo:watchlater'
  457. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  458. _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
  459. _LOGIN_REQUIRED = True
  460. _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
  461. _TESTS = [{
  462. 'url': 'http://vimeo.com/home/watchlater',
  463. 'only_matching': True,
  464. }]
  465. def _real_initialize(self):
  466. self._login()
  467. def _page_url(self, base_url, pagenum):
  468. url = '%s/page:%d/' % (base_url, pagenum)
  469. request = compat_urllib_request.Request(url)
  470. # Set the header to get a partial html page with the ids,
  471. # the normal page doesn't contain them.
  472. request.add_header('X-Requested-With', 'XMLHttpRequest')
  473. return request
  474. def _real_extract(self, url):
  475. return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')