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.

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