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.

514 lines
21 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 2012',
  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/channels/keypeele/75629013',
  118. 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
  119. 'note': 'Video is freely available via original URL '
  120. 'and protected with password when accessed via http://vimeo.com/75629013',
  121. 'info_dict': {
  122. 'id': '75629013',
  123. 'ext': 'mp4',
  124. 'title': 'Key & Peele: Terrorist Interrogation',
  125. 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
  126. 'uploader_id': 'atencio',
  127. 'uploader': 'Peter Atencio',
  128. 'duration': 187,
  129. },
  130. },
  131. {
  132. 'url': 'http://vimeo.com/76979871',
  133. 'md5': '3363dd6ffebe3784d56f4132317fd446',
  134. 'note': 'Video with subtitles',
  135. 'info_dict': {
  136. 'id': '76979871',
  137. 'ext': 'mp4',
  138. 'title': 'The New Vimeo Player (You Know, For Videos)',
  139. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  140. 'upload_date': '20131015',
  141. 'uploader_id': 'staff',
  142. 'uploader': 'Vimeo Staff',
  143. 'duration': 62,
  144. }
  145. },
  146. {
  147. 'note': 'video player needs Referer',
  148. 'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
  149. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  150. 'info_dict': {
  151. 'id': '91613211',
  152. 'ext': 'mp4',
  153. 'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
  154. 'uploader': 'DevWeek Events',
  155. 'duration': 2773,
  156. 'thumbnail': 're:^https?://.*\.jpg$',
  157. }
  158. }
  159. ]
  160. @classmethod
  161. def suitable(cls, url):
  162. if VimeoChannelIE.suitable(url):
  163. # Otherwise channel urls like http://vimeo.com/channels/31259 would
  164. # match
  165. return False
  166. else:
  167. return super(VimeoIE, cls).suitable(url)
  168. def _verify_video_password(self, url, video_id, webpage):
  169. password = self._downloader.params.get('videopassword', None)
  170. if password is None:
  171. raise ExtractorError('This video is protected by a password, use the --video-password option')
  172. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  173. data = compat_urllib_parse.urlencode({
  174. 'password': password,
  175. 'token': token,
  176. })
  177. # I didn't manage to use the password with https
  178. if url.startswith('https'):
  179. pass_url = url.replace('https', 'http')
  180. else:
  181. pass_url = url
  182. password_request = compat_urllib_request.Request(pass_url + '/password', data)
  183. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  184. password_request.add_header('Cookie', 'xsrft=%s' % token)
  185. self._download_webpage(password_request, video_id,
  186. 'Verifying the password',
  187. 'Wrong password')
  188. def _verify_player_video_password(self, url, video_id):
  189. password = self._downloader.params.get('videopassword', None)
  190. if password is None:
  191. raise ExtractorError('This video is protected by a password, use the --video-password option')
  192. data = compat_urllib_parse.urlencode({'password': password})
  193. pass_url = url + '/check-password'
  194. password_request = compat_urllib_request.Request(pass_url, data)
  195. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  196. return self._download_json(
  197. password_request, video_id,
  198. 'Verifying the password',
  199. 'Wrong password')
  200. def _real_initialize(self):
  201. self._login()
  202. def _real_extract(self, url):
  203. url, data = unsmuggle_url(url)
  204. headers = std_headers
  205. if data is not None:
  206. headers = headers.copy()
  207. headers.update(data)
  208. if 'Referer' not in headers:
  209. headers['Referer'] = url
  210. # Extract ID from URL
  211. mobj = re.match(self._VALID_URL, url)
  212. video_id = mobj.group('id')
  213. if mobj.group('pro') or mobj.group('player'):
  214. url = 'http://player.vimeo.com/video/' + video_id
  215. # Retrieve video webpage to extract further information
  216. request = compat_urllib_request.Request(url, None, headers)
  217. try:
  218. webpage = self._download_webpage(request, video_id)
  219. except ExtractorError as ee:
  220. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  221. errmsg = ee.cause.read()
  222. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  223. raise ExtractorError(
  224. 'Cannot download embed-only video without embedding '
  225. 'URL. Please call youtube-dl with the URL of the page '
  226. 'that embeds this video.',
  227. expected=True)
  228. raise
  229. # Now we begin extracting as much information as we can from what we
  230. # retrieved. First we extract the information common to all extractors,
  231. # and latter we extract those that are Vimeo specific.
  232. self.report_extraction(video_id)
  233. # Extract the config JSON
  234. try:
  235. try:
  236. config_url = self._html_search_regex(
  237. r' data-config-url="(.+?)"', webpage, 'config URL')
  238. config_json = self._download_webpage(config_url, video_id)
  239. config = json.loads(config_json)
  240. except RegexNotFoundError:
  241. # For pro videos or player.vimeo.com urls
  242. # We try to find out to which variable is assigned the config dic
  243. m_variable_name = re.search('(\w)\.video\.id', webpage)
  244. if m_variable_name is not None:
  245. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  246. else:
  247. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  248. config = self._search_regex(config_re, webpage, 'info section',
  249. flags=re.DOTALL)
  250. config = json.loads(config)
  251. except Exception as e:
  252. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  253. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  254. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  255. self._verify_video_password(url, video_id, webpage)
  256. return self._real_extract(url)
  257. else:
  258. raise ExtractorError('Unable to extract info section',
  259. cause=e)
  260. else:
  261. if config.get('view') == 4:
  262. config = self._verify_player_video_password(url, video_id)
  263. # Extract title
  264. video_title = config["video"]["title"]
  265. # Extract uploader and uploader_id
  266. video_uploader = config["video"]["owner"]["name"]
  267. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  268. # Extract video thumbnail
  269. video_thumbnail = config["video"].get("thumbnail")
  270. if video_thumbnail is None:
  271. video_thumbs = config["video"].get("thumbs")
  272. if video_thumbs and isinstance(video_thumbs, dict):
  273. _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
  274. # Extract video description
  275. video_description = None
  276. try:
  277. video_description = get_element_by_attribute("class", "description_wrapper", webpage)
  278. if video_description:
  279. video_description = clean_html(video_description)
  280. except AssertionError as err:
  281. # On some pages like (http://player.vimeo.com/video/54469442) the
  282. # html tags are not closed, python 2.6 cannot handle it
  283. if err.args[0] == 'we should not get here!':
  284. pass
  285. else:
  286. raise
  287. # Extract video duration
  288. video_duration = int_or_none(config["video"].get("duration"))
  289. # Extract upload date
  290. video_upload_date = None
  291. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  292. if mobj is not None:
  293. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  294. try:
  295. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  296. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  297. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  298. except RegexNotFoundError:
  299. # This info is only available in vimeo.com/{id} urls
  300. view_count = None
  301. like_count = None
  302. comment_count = None
  303. # Vimeo specific: extract request signature and timestamp
  304. sig = config['request']['signature']
  305. timestamp = config['request']['timestamp']
  306. # Vimeo specific: extract video codec and quality information
  307. # First consider quality, then codecs, then take everything
  308. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  309. files = {'hd': [], 'sd': [], 'other': []}
  310. config_files = config["video"].get("files") or config["request"].get("files")
  311. for codec_name, codec_extension in codecs:
  312. for quality in config_files.get(codec_name, []):
  313. format_id = '-'.join((codec_name, quality)).lower()
  314. key = quality if quality in files else 'other'
  315. video_url = None
  316. if isinstance(config_files[codec_name], dict):
  317. file_info = config_files[codec_name][quality]
  318. video_url = file_info.get('url')
  319. else:
  320. file_info = {}
  321. if video_url is None:
  322. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  323. % (video_id, sig, timestamp, quality, codec_name.upper())
  324. files[key].append({
  325. 'ext': codec_extension,
  326. 'url': video_url,
  327. 'format_id': format_id,
  328. 'width': file_info.get('width'),
  329. 'height': file_info.get('height'),
  330. })
  331. formats = []
  332. for key in ('other', 'sd', 'hd'):
  333. formats += files[key]
  334. if len(formats) == 0:
  335. raise ExtractorError('No known codec found')
  336. subtitles = {}
  337. text_tracks = config['request'].get('text_tracks')
  338. if text_tracks:
  339. for tt in text_tracks:
  340. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  341. video_subtitles = self.extract_subtitles(video_id, subtitles)
  342. if self._downloader.params.get('listsubtitles', False):
  343. self._list_available_subtitles(video_id, subtitles)
  344. return
  345. return {
  346. 'id': video_id,
  347. 'uploader': video_uploader,
  348. 'uploader_id': video_uploader_id,
  349. 'upload_date': video_upload_date,
  350. 'title': video_title,
  351. 'thumbnail': video_thumbnail,
  352. 'description': video_description,
  353. 'duration': video_duration,
  354. 'formats': formats,
  355. 'webpage_url': url,
  356. 'view_count': view_count,
  357. 'like_count': like_count,
  358. 'comment_count': comment_count,
  359. 'subtitles': video_subtitles,
  360. }
  361. class VimeoChannelIE(InfoExtractor):
  362. IE_NAME = 'vimeo:channel'
  363. _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)/?(\?.*)?$'
  364. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  365. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  366. def _page_url(self, base_url, pagenum):
  367. return '%s/videos/page:%d/' % (base_url, pagenum)
  368. def _extract_list_title(self, webpage):
  369. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  370. def _extract_videos(self, list_id, base_url):
  371. video_ids = []
  372. for pagenum in itertools.count(1):
  373. webpage = self._download_webpage(
  374. self._page_url(base_url, pagenum), list_id,
  375. 'Downloading page %s' % pagenum)
  376. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  377. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  378. break
  379. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  380. for video_id in video_ids]
  381. return {'_type': 'playlist',
  382. 'id': list_id,
  383. 'title': self._extract_list_title(webpage),
  384. 'entries': entries,
  385. }
  386. def _real_extract(self, url):
  387. mobj = re.match(self._VALID_URL, url)
  388. channel_id = mobj.group('id')
  389. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  390. class VimeoUserIE(VimeoChannelIE):
  391. IE_NAME = 'vimeo:user'
  392. _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
  393. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  394. @classmethod
  395. def suitable(cls, url):
  396. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  397. return False
  398. return super(VimeoUserIE, cls).suitable(url)
  399. def _real_extract(self, url):
  400. mobj = re.match(self._VALID_URL, url)
  401. name = mobj.group('name')
  402. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  403. class VimeoAlbumIE(VimeoChannelIE):
  404. IE_NAME = 'vimeo:album'
  405. _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
  406. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  407. def _page_url(self, base_url, pagenum):
  408. return '%s/page:%d/' % (base_url, pagenum)
  409. def _real_extract(self, url):
  410. mobj = re.match(self._VALID_URL, url)
  411. album_id = mobj.group('id')
  412. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  413. class VimeoGroupsIE(VimeoAlbumIE):
  414. IE_NAME = 'vimeo:group'
  415. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  416. def _extract_list_title(self, webpage):
  417. return self._og_search_title(webpage)
  418. def _real_extract(self, url):
  419. mobj = re.match(self._VALID_URL, url)
  420. name = mobj.group('name')
  421. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  422. class VimeoReviewIE(InfoExtractor):
  423. IE_NAME = 'vimeo:review'
  424. IE_DESC = 'Review pages on vimeo'
  425. _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  426. _TEST = {
  427. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  428. 'file': '75524534.mp4',
  429. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  430. 'info_dict': {
  431. 'title': "DICK HARDWICK 'Comedian'",
  432. 'uploader': 'Richard Hardwick',
  433. }
  434. }
  435. def _real_extract(self, url):
  436. mobj = re.match(self._VALID_URL, url)
  437. video_id = mobj.group('id')
  438. player_url = 'https://player.vimeo.com/player/' + video_id
  439. return self.url_result(player_url, 'Vimeo', video_id)
  440. class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
  441. IE_NAME = 'vimeo:watchlater'
  442. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  443. _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
  444. _LOGIN_REQUIRED = True
  445. _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
  446. def _real_initialize(self):
  447. self._login()
  448. def _page_url(self, base_url, pagenum):
  449. url = '%s/page:%d/' % (base_url, pagenum)
  450. request = compat_urllib_request.Request(url)
  451. # Set the header to get a partial html page with the ids,
  452. # the normal page doesn't contain them.
  453. request.add_header('X-Requested-With', 'XMLHttpRequest')
  454. return request
  455. def _real_extract(self, url):
  456. return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')