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.

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