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.

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