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.

353 lines
14 KiB

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