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.

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