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.

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