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.

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