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.

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