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.

390 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. video_id = mobj.group('id')
  141. if mobj.group('pro') or mobj.group('player'):
  142. url = 'http://player.vimeo.com/video/' + video_id
  143. else:
  144. url = 'https://vimeo.com/' + video_id
  145. # Retrieve video webpage to extract further information
  146. request = compat_urllib_request.Request(url, None, headers)
  147. webpage = self._download_webpage(request, video_id)
  148. # Now we begin extracting as much information as we can from what we
  149. # retrieved. First we extract the information common to all extractors,
  150. # and latter we extract those that are Vimeo specific.
  151. self.report_extraction(video_id)
  152. # Extract the config JSON
  153. try:
  154. try:
  155. config_url = self._html_search_regex(
  156. r' data-config-url="(.+?)"', webpage, 'config URL')
  157. config_json = self._download_webpage(config_url, video_id)
  158. config = json.loads(config_json)
  159. except RegexNotFoundError:
  160. # For pro videos or player.vimeo.com urls
  161. # We try to find out to which variable is assigned the config dic
  162. m_variable_name = re.search('(\w)\.video\.id', webpage)
  163. if m_variable_name is not None:
  164. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  165. else:
  166. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  167. config = self._search_regex(config_re, webpage, 'info section',
  168. flags=re.DOTALL)
  169. config = json.loads(config)
  170. except Exception as e:
  171. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  172. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  173. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  174. self._verify_video_password(url, video_id, webpage)
  175. return self._real_extract(url)
  176. else:
  177. raise ExtractorError('Unable to extract info section',
  178. cause=e)
  179. else:
  180. if config.get('view') == 4:
  181. config = self._verify_player_video_password(url, video_id)
  182. # Extract title
  183. video_title = config["video"]["title"]
  184. # Extract uploader and uploader_id
  185. video_uploader = config["video"]["owner"]["name"]
  186. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  187. # Extract video thumbnail
  188. video_thumbnail = config["video"].get("thumbnail")
  189. if video_thumbnail is None:
  190. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
  191. # Extract video description
  192. video_description = None
  193. try:
  194. video_description = get_element_by_attribute("itemprop", "description", webpage)
  195. if video_description: video_description = clean_html(video_description)
  196. except AssertionError as err:
  197. # On some pages like (http://player.vimeo.com/video/54469442) the
  198. # html tags are not closed, python 2.6 cannot handle it
  199. if err.args[0] == 'we should not get here!':
  200. pass
  201. else:
  202. raise
  203. # Extract upload date
  204. video_upload_date = None
  205. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  206. if mobj is not None:
  207. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  208. try:
  209. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  210. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  211. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  212. except RegexNotFoundError:
  213. # This info is only available in vimeo.com/{id} urls
  214. view_count = None
  215. like_count = None
  216. comment_count = None
  217. # Vimeo specific: extract request signature and timestamp
  218. sig = config['request']['signature']
  219. timestamp = config['request']['timestamp']
  220. # Vimeo specific: extract video codec and quality information
  221. # First consider quality, then codecs, then take everything
  222. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  223. files = {'hd': [], 'sd': [], 'other': []}
  224. config_files = config["video"].get("files") or config["request"].get("files")
  225. for codec_name, codec_extension in codecs:
  226. for quality in config_files.get(codec_name, []):
  227. format_id = '-'.join((codec_name, quality)).lower()
  228. key = quality if quality in files else 'other'
  229. video_url = None
  230. if isinstance(config_files[codec_name], dict):
  231. file_info = config_files[codec_name][quality]
  232. video_url = file_info.get('url')
  233. else:
  234. file_info = {}
  235. if video_url is None:
  236. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  237. %(video_id, sig, timestamp, quality, codec_name.upper())
  238. files[key].append({
  239. 'ext': codec_extension,
  240. 'url': video_url,
  241. 'format_id': format_id,
  242. 'width': file_info.get('width'),
  243. 'height': file_info.get('height'),
  244. })
  245. formats = []
  246. for key in ('other', 'sd', 'hd'):
  247. formats += files[key]
  248. if len(formats) == 0:
  249. raise ExtractorError('No known codec found')
  250. return {
  251. 'id': video_id,
  252. 'uploader': video_uploader,
  253. 'uploader_id': video_uploader_id,
  254. 'upload_date': video_upload_date,
  255. 'title': video_title,
  256. 'thumbnail': video_thumbnail,
  257. 'description': video_description,
  258. 'formats': formats,
  259. 'webpage_url': url,
  260. 'view_count': view_count,
  261. 'like_count': like_count,
  262. 'comment_count': comment_count,
  263. }
  264. class VimeoChannelIE(InfoExtractor):
  265. IE_NAME = 'vimeo:channel'
  266. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  267. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  268. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  269. def _page_url(self, base_url, pagenum):
  270. return '%s/videos/page:%d/' % (base_url, pagenum)
  271. def _extract_list_title(self, webpage):
  272. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  273. def _extract_videos(self, list_id, base_url):
  274. video_ids = []
  275. for pagenum in itertools.count(1):
  276. webpage = self._download_webpage(
  277. self._page_url(base_url, pagenum) ,list_id,
  278. 'Downloading page %s' % pagenum)
  279. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  280. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  281. break
  282. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  283. for video_id in video_ids]
  284. return {'_type': 'playlist',
  285. 'id': list_id,
  286. 'title': self._extract_list_title(webpage),
  287. 'entries': entries,
  288. }
  289. def _real_extract(self, url):
  290. mobj = re.match(self._VALID_URL, url)
  291. channel_id = mobj.group('id')
  292. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  293. class VimeoUserIE(VimeoChannelIE):
  294. IE_NAME = 'vimeo:user'
  295. _VALID_URL = r'(?:https?://)?vimeo.\com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
  296. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  297. @classmethod
  298. def suitable(cls, url):
  299. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  300. return False
  301. return super(VimeoUserIE, cls).suitable(url)
  302. def _real_extract(self, url):
  303. mobj = re.match(self._VALID_URL, url)
  304. name = mobj.group('name')
  305. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  306. class VimeoAlbumIE(VimeoChannelIE):
  307. IE_NAME = 'vimeo:album'
  308. _VALID_URL = r'(?:https?://)?vimeo.\com/album/(?P<id>\d+)'
  309. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  310. def _page_url(self, base_url, pagenum):
  311. return '%s/page:%d/' % (base_url, pagenum)
  312. def _real_extract(self, url):
  313. mobj = re.match(self._VALID_URL, url)
  314. album_id = mobj.group('id')
  315. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  316. class VimeoGroupsIE(VimeoAlbumIE):
  317. IE_NAME = 'vimeo:group'
  318. _VALID_URL = r'(?:https?://)?vimeo.\com/groups/(?P<name>[^/]+)'
  319. def _extract_list_title(self, webpage):
  320. return self._og_search_title(webpage)
  321. def _real_extract(self, url):
  322. mobj = re.match(self._VALID_URL, url)
  323. name = mobj.group('name')
  324. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  325. class VimeoReviewIE(InfoExtractor):
  326. IE_NAME = 'vimeo:review'
  327. IE_DESC = 'Review pages on vimeo'
  328. _VALID_URL = r'(?:https?://)?vimeo.\com/[^/]+/review/(?P<id>[^/]+)'
  329. _TEST = {
  330. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  331. 'file': '75524534.mp4',
  332. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  333. 'info_dict': {
  334. 'title': "DICK HARDWICK 'Comedian'",
  335. 'uploader': 'Richard Hardwick',
  336. }
  337. }
  338. def _real_extract(self, url):
  339. mobj = re.match(self._VALID_URL, url)
  340. video_id = mobj.group('id')
  341. player_url = 'https://player.vimeo.com/player/' + video_id
  342. return self.url_result(player_url, 'Vimeo', video_id)