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.

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