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.

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