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.

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