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.

440 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. @classmethod
  100. def suitable(cls, url):
  101. if VimeoChannelIE.suitable(url):
  102. # Otherwise channel urls like http://vimeo.com/channels/31259 would
  103. # match
  104. return False
  105. else:
  106. return super(VimeoIE, cls).suitable(url)
  107. def _login(self):
  108. (username, password) = self._get_login_info()
  109. if username is None:
  110. return
  111. self.report_login()
  112. login_url = 'https://vimeo.com/log_in'
  113. webpage = self._download_webpage(login_url, None, False)
  114. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  115. data = compat_urllib_parse.urlencode({'email': username,
  116. 'password': password,
  117. 'action': 'login',
  118. 'service': 'vimeo',
  119. 'token': token,
  120. })
  121. login_request = compat_urllib_request.Request(login_url, data)
  122. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  123. login_request.add_header('Cookie', 'xsrft=%s' % token)
  124. self._download_webpage(login_request, None, False, 'Wrong login info')
  125. def _verify_video_password(self, url, video_id, webpage):
  126. password = self._downloader.params.get('videopassword', None)
  127. if password is None:
  128. raise ExtractorError('This video is protected by a password, use the --video-password option')
  129. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  130. data = compat_urllib_parse.urlencode({'password': password,
  131. 'token': token})
  132. # I didn't manage to use the password with https
  133. if url.startswith('https'):
  134. pass_url = url.replace('https','http')
  135. else:
  136. pass_url = url
  137. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  138. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  139. password_request.add_header('Cookie', 'xsrft=%s' % token)
  140. self._download_webpage(password_request, video_id,
  141. 'Verifying the password',
  142. 'Wrong password')
  143. def _verify_player_video_password(self, url, video_id):
  144. password = self._downloader.params.get('videopassword', None)
  145. if password is None:
  146. raise ExtractorError('This video is protected by a password, use the --video-password option')
  147. data = compat_urllib_parse.urlencode({'password': password})
  148. pass_url = url + '/check-password'
  149. password_request = compat_urllib_request.Request(pass_url, data)
  150. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  151. return self._download_json(
  152. password_request, video_id,
  153. 'Verifying the password',
  154. 'Wrong password')
  155. def _real_initialize(self):
  156. self._login()
  157. def _real_extract(self, url):
  158. url, data = unsmuggle_url(url)
  159. headers = std_headers
  160. if data is not None:
  161. headers = headers.copy()
  162. headers.update(data)
  163. # Extract ID from URL
  164. mobj = re.match(self._VALID_URL, url)
  165. video_id = mobj.group('id')
  166. if mobj.group('pro') or mobj.group('player'):
  167. url = 'http://player.vimeo.com/video/' + video_id
  168. else:
  169. url = 'https://vimeo.com/' + video_id
  170. # Retrieve video webpage to extract further information
  171. request = compat_urllib_request.Request(url, None, headers)
  172. try:
  173. webpage = self._download_webpage(request, video_id)
  174. except ExtractorError as ee:
  175. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  176. errmsg = ee.cause.read()
  177. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  178. raise ExtractorError(
  179. 'Cannot download embed-only video without embedding '
  180. 'URL. Please call youtube-dl with the URL of the page '
  181. 'that embeds this video.',
  182. expected=True)
  183. raise
  184. # Now we begin extracting as much information as we can from what we
  185. # retrieved. First we extract the information common to all extractors,
  186. # and latter we extract those that are Vimeo specific.
  187. self.report_extraction(video_id)
  188. # Extract the config JSON
  189. try:
  190. try:
  191. config_url = self._html_search_regex(
  192. r' data-config-url="(.+?)"', webpage, 'config URL')
  193. config_json = self._download_webpage(config_url, video_id)
  194. config = json.loads(config_json)
  195. except RegexNotFoundError:
  196. # For pro videos or player.vimeo.com urls
  197. # We try to find out to which variable is assigned the config dic
  198. m_variable_name = re.search('(\w)\.video\.id', webpage)
  199. if m_variable_name is not None:
  200. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  201. else:
  202. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  203. config = self._search_regex(config_re, webpage, 'info section',
  204. flags=re.DOTALL)
  205. config = json.loads(config)
  206. except Exception as e:
  207. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  208. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  209. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  210. self._verify_video_password(url, video_id, webpage)
  211. return self._real_extract(url)
  212. else:
  213. raise ExtractorError('Unable to extract info section',
  214. cause=e)
  215. else:
  216. if config.get('view') == 4:
  217. config = self._verify_player_video_password(url, video_id)
  218. # Extract title
  219. video_title = config["video"]["title"]
  220. # Extract uploader and uploader_id
  221. video_uploader = config["video"]["owner"]["name"]
  222. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  223. # Extract video thumbnail
  224. video_thumbnail = config["video"].get("thumbnail")
  225. if video_thumbnail is None:
  226. video_thumbs = config["video"].get("thumbs")
  227. if video_thumbs and isinstance(video_thumbs, dict):
  228. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in video_thumbs.items())[-1]
  229. # Extract video description
  230. video_description = None
  231. try:
  232. video_description = get_element_by_attribute("itemprop", "description", webpage)
  233. if video_description: video_description = clean_html(video_description)
  234. except AssertionError as err:
  235. # On some pages like (http://player.vimeo.com/video/54469442) the
  236. # html tags are not closed, python 2.6 cannot handle it
  237. if err.args[0] == 'we should not get here!':
  238. pass
  239. else:
  240. raise
  241. # Extract upload date
  242. video_upload_date = None
  243. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  244. if mobj is not None:
  245. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  246. try:
  247. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  248. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  249. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  250. except RegexNotFoundError:
  251. # This info is only available in vimeo.com/{id} urls
  252. view_count = None
  253. like_count = None
  254. comment_count = None
  255. # Vimeo specific: extract request signature and timestamp
  256. sig = config['request']['signature']
  257. timestamp = config['request']['timestamp']
  258. # Vimeo specific: extract video codec and quality information
  259. # First consider quality, then codecs, then take everything
  260. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  261. files = {'hd': [], 'sd': [], 'other': []}
  262. config_files = config["video"].get("files") or config["request"].get("files")
  263. for codec_name, codec_extension in codecs:
  264. for quality in config_files.get(codec_name, []):
  265. format_id = '-'.join((codec_name, quality)).lower()
  266. key = quality if quality in files else 'other'
  267. video_url = None
  268. if isinstance(config_files[codec_name], dict):
  269. file_info = config_files[codec_name][quality]
  270. video_url = file_info.get('url')
  271. else:
  272. file_info = {}
  273. if video_url is None:
  274. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  275. %(video_id, sig, timestamp, quality, codec_name.upper())
  276. files[key].append({
  277. 'ext': codec_extension,
  278. 'url': video_url,
  279. 'format_id': format_id,
  280. 'width': file_info.get('width'),
  281. 'height': file_info.get('height'),
  282. })
  283. formats = []
  284. for key in ('other', 'sd', 'hd'):
  285. formats += files[key]
  286. if len(formats) == 0:
  287. raise ExtractorError('No known codec found')
  288. subtitles = {}
  289. text_tracks = config['request'].get('text_tracks')
  290. if text_tracks:
  291. for tt in text_tracks:
  292. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  293. video_subtitles = self.extract_subtitles(video_id, subtitles)
  294. if self._downloader.params.get('listsubtitles', False):
  295. self._list_available_subtitles(video_id, subtitles)
  296. return
  297. return {
  298. 'id': video_id,
  299. 'uploader': video_uploader,
  300. 'uploader_id': video_uploader_id,
  301. 'upload_date': video_upload_date,
  302. 'title': video_title,
  303. 'thumbnail': video_thumbnail,
  304. 'description': video_description,
  305. 'formats': formats,
  306. 'webpage_url': url,
  307. 'view_count': view_count,
  308. 'like_count': like_count,
  309. 'comment_count': comment_count,
  310. 'subtitles': video_subtitles,
  311. }
  312. class VimeoChannelIE(InfoExtractor):
  313. IE_NAME = 'vimeo:channel'
  314. _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)/?(\?.*)?$'
  315. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  316. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  317. def _page_url(self, base_url, pagenum):
  318. return '%s/videos/page:%d/' % (base_url, pagenum)
  319. def _extract_list_title(self, webpage):
  320. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  321. def _extract_videos(self, list_id, base_url):
  322. video_ids = []
  323. for pagenum in itertools.count(1):
  324. webpage = self._download_webpage(
  325. self._page_url(base_url, pagenum) ,list_id,
  326. 'Downloading page %s' % pagenum)
  327. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  328. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  329. break
  330. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  331. for video_id in video_ids]
  332. return {'_type': 'playlist',
  333. 'id': list_id,
  334. 'title': self._extract_list_title(webpage),
  335. 'entries': entries,
  336. }
  337. def _real_extract(self, url):
  338. mobj = re.match(self._VALID_URL, url)
  339. channel_id = mobj.group('id')
  340. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  341. class VimeoUserIE(VimeoChannelIE):
  342. IE_NAME = 'vimeo:user'
  343. _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
  344. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  345. @classmethod
  346. def suitable(cls, url):
  347. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  348. return False
  349. return super(VimeoUserIE, cls).suitable(url)
  350. def _real_extract(self, url):
  351. mobj = re.match(self._VALID_URL, url)
  352. name = mobj.group('name')
  353. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  354. class VimeoAlbumIE(VimeoChannelIE):
  355. IE_NAME = 'vimeo:album'
  356. _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
  357. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  358. def _page_url(self, base_url, pagenum):
  359. return '%s/page:%d/' % (base_url, pagenum)
  360. def _real_extract(self, url):
  361. mobj = re.match(self._VALID_URL, url)
  362. album_id = mobj.group('id')
  363. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  364. class VimeoGroupsIE(VimeoAlbumIE):
  365. IE_NAME = 'vimeo:group'
  366. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  367. def _extract_list_title(self, webpage):
  368. return self._og_search_title(webpage)
  369. def _real_extract(self, url):
  370. mobj = re.match(self._VALID_URL, url)
  371. name = mobj.group('name')
  372. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  373. class VimeoReviewIE(InfoExtractor):
  374. IE_NAME = 'vimeo:review'
  375. IE_DESC = 'Review pages on vimeo'
  376. _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  377. _TEST = {
  378. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  379. 'file': '75524534.mp4',
  380. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  381. 'info_dict': {
  382. 'title': "DICK HARDWICK 'Comedian'",
  383. 'uploader': 'Richard Hardwick',
  384. }
  385. }
  386. def _real_extract(self, url):
  387. mobj = re.match(self._VALID_URL, url)
  388. video_id = mobj.group('id')
  389. player_url = 'https://player.vimeo.com/player/' + video_id
  390. return self.url_result(player_url, 'Vimeo', video_id)