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.

138 lines
6.0 KiB

  1. import json
  2. import re
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. compat_urllib_parse,
  6. compat_urllib_request,
  7. clean_html,
  8. get_element_by_attribute,
  9. ExtractorError,
  10. std_headers,
  11. )
  12. class VimeoIE(InfoExtractor):
  13. """Information extractor for vimeo.com."""
  14. # _VALID_URL matches Vimeo URLs
  15. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  16. IE_NAME = u'vimeo'
  17. def _verify_video_password(self, url, video_id, webpage):
  18. password = self._downloader.params.get('videopassword', None)
  19. if password is None:
  20. raise ExtractorError(u'This video is protected by a password, use the --video-password option')
  21. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  22. data = compat_urllib_parse.urlencode({'password': password,
  23. 'token': token})
  24. # I didn't manage to use the password with https
  25. if url.startswith('https'):
  26. pass_url = url.replace('https','http')
  27. else:
  28. pass_url = url
  29. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  30. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  31. password_request.add_header('Cookie', 'xsrft=%s' % token)
  32. self._download_webpage(password_request, video_id,
  33. u'Verifying the password',
  34. u'Wrong password')
  35. def _real_extract(self, url, new_video=True):
  36. # Extract ID from URL
  37. mobj = re.match(self._VALID_URL, url)
  38. if mobj is None:
  39. raise ExtractorError(u'Invalid URL: %s' % url)
  40. video_id = mobj.group('id')
  41. if not mobj.group('proto'):
  42. url = 'https://' + url
  43. if mobj.group('direct_link') or mobj.group('pro'):
  44. url = 'https://vimeo.com/' + video_id
  45. # Retrieve video webpage to extract further information
  46. request = compat_urllib_request.Request(url, None, std_headers)
  47. webpage = self._download_webpage(request, video_id)
  48. # Now we begin extracting as much information as we can from what we
  49. # retrieved. First we extract the information common to all extractors,
  50. # and latter we extract those that are Vimeo specific.
  51. self.report_extraction(video_id)
  52. # Extract the config JSON
  53. try:
  54. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  55. config = json.loads(config)
  56. except:
  57. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  58. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  59. if re.search('If so please provide the correct password.', webpage):
  60. self._verify_video_password(url, video_id, webpage)
  61. return self._real_extract(url)
  62. else:
  63. raise ExtractorError(u'Unable to extract info section')
  64. # Extract title
  65. video_title = config["video"]["title"]
  66. # Extract uploader and uploader_id
  67. video_uploader = config["video"]["owner"]["name"]
  68. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  69. # Extract video thumbnail
  70. video_thumbnail = config["video"]["thumbnail"]
  71. # Extract video description
  72. video_description = get_element_by_attribute("itemprop", "description", webpage)
  73. if video_description: video_description = clean_html(video_description)
  74. else: video_description = u''
  75. # Extract upload date
  76. video_upload_date = None
  77. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  78. if mobj is not None:
  79. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  80. # Vimeo specific: extract request signature and timestamp
  81. sig = config['request']['signature']
  82. timestamp = config['request']['timestamp']
  83. # Vimeo specific: extract video codec and quality information
  84. # First consider quality, then codecs, then take everything
  85. # TODO bind to format param
  86. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  87. files = { 'hd': [], 'sd': [], 'other': []}
  88. for codec_name, codec_extension in codecs:
  89. if codec_name in config["video"]["files"]:
  90. if 'hd' in config["video"]["files"][codec_name]:
  91. files['hd'].append((codec_name, codec_extension, 'hd'))
  92. elif 'sd' in config["video"]["files"][codec_name]:
  93. files['sd'].append((codec_name, codec_extension, 'sd'))
  94. else:
  95. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  96. for quality in ('hd', 'sd', 'other'):
  97. if len(files[quality]) > 0:
  98. video_quality = files[quality][0][2]
  99. video_codec = files[quality][0][0]
  100. video_extension = files[quality][0][1]
  101. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  102. break
  103. else:
  104. raise ExtractorError(u'No known codec found')
  105. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  106. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  107. return [{
  108. 'id': video_id,
  109. 'url': video_url,
  110. 'uploader': video_uploader,
  111. 'uploader_id': video_uploader_id,
  112. 'upload_date': video_upload_date,
  113. 'title': video_title,
  114. 'ext': video_extension,
  115. 'thumbnail': video_thumbnail,
  116. 'description': video_description,
  117. }]