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.

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