vimeo.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import json
  2. import re
  3. import itertools
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. compat_urllib_parse,
  7. compat_urllib_request,
  8. clean_html,
  9. get_element_by_attribute,
  10. ExtractorError,
  11. std_headers,
  12. unsmuggle_url,
  13. )
  14. class VimeoIE(InfoExtractor):
  15. """Information extractor for vimeo.com."""
  16. # _VALID_URL matches Vimeo URLs
  17. _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]+)/?(?:[?].*)?$'
  18. _NETRC_MACHINE = 'vimeo'
  19. IE_NAME = u'vimeo'
  20. _TESTS = [
  21. {
  22. u'url': u'http://vimeo.com/56015672',
  23. u'file': u'56015672.mp4',
  24. u'md5': u'ae7a1d8b183758a0506b0622f37dfa14',
  25. u'info_dict': {
  26. u"upload_date": u"20121220",
  27. 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",
  28. u"uploader_id": u"user7108434",
  29. u"uploader": u"Filippo Valsorda",
  30. u"title": u"youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  31. },
  32. },
  33. {
  34. u'url': u'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  35. u'file': u'68093876.mp4',
  36. u'md5': u'3b5ca6aa22b60dfeeadf50b72e44ed82',
  37. u'note': u'Vimeo Pro video (#1197)',
  38. u'info_dict': {
  39. u'uploader_id': u'openstreetmapus',
  40. u'uploader': u'OpenStreetMap US',
  41. u'title': u'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  42. },
  43. },
  44. {
  45. u'url': u'http://player.vimeo.com/video/54469442',
  46. u'file': u'54469442.mp4',
  47. u'md5': u'619b811a4417aa4abe78dc653becf511',
  48. u'note': u'Videos that embed the url in the player page',
  49. u'info_dict': {
  50. u'title': u'Kathy Sierra: Building the minimum Badass User, Business of Software',
  51. u'uploader': u'The BLN & Business of Software',
  52. },
  53. }
  54. ]
  55. def _login(self):
  56. (username, password) = self._get_login_info()
  57. if username is None:
  58. return
  59. self.report_login()
  60. login_url = 'https://vimeo.com/log_in'
  61. webpage = self._download_webpage(login_url, None, False)
  62. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  63. data = compat_urllib_parse.urlencode({'email': username,
  64. 'password': password,
  65. 'action': 'login',
  66. 'service': 'vimeo',
  67. 'token': token,
  68. })
  69. login_request = compat_urllib_request.Request(login_url, data)
  70. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  71. login_request.add_header('Cookie', 'xsrft=%s' % token)
  72. self._download_webpage(login_request, None, False, u'Wrong login info')
  73. def _verify_video_password(self, url, video_id, webpage):
  74. password = self._downloader.params.get('videopassword', None)
  75. if password is None:
  76. raise ExtractorError(u'This video is protected by a password, use the --video-password option')
  77. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  78. data = compat_urllib_parse.urlencode({'password': password,
  79. 'token': token})
  80. # I didn't manage to use the password with https
  81. if url.startswith('https'):
  82. pass_url = url.replace('https','http')
  83. else:
  84. pass_url = url
  85. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  86. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  87. password_request.add_header('Cookie', 'xsrft=%s' % token)
  88. self._download_webpage(password_request, video_id,
  89. u'Verifying the password',
  90. u'Wrong password')
  91. def _real_initialize(self):
  92. self._login()
  93. def _real_extract(self, url, new_video=True):
  94. url, data = unsmuggle_url(url)
  95. headers = std_headers
  96. if data is not None:
  97. headers = headers.copy()
  98. headers.update(data)
  99. # Extract ID from URL
  100. mobj = re.match(self._VALID_URL, url)
  101. if mobj is None:
  102. raise ExtractorError(u'Invalid URL: %s' % url)
  103. video_id = mobj.group('id')
  104. if not mobj.group('proto'):
  105. url = 'https://' + url
  106. elif mobj.group('pro'):
  107. url = 'http://player.vimeo.com/video/' + video_id
  108. elif mobj.group('direct_link'):
  109. url = 'https://vimeo.com/' + video_id
  110. # Retrieve video webpage to extract further information
  111. request = compat_urllib_request.Request(url, None, headers)
  112. webpage = self._download_webpage(request, video_id)
  113. # Now we begin extracting as much information as we can from what we
  114. # retrieved. First we extract the information common to all extractors,
  115. # and latter we extract those that are Vimeo specific.
  116. self.report_extraction(video_id)
  117. # Extract the config JSON
  118. try:
  119. config_url = self._html_search_regex(
  120. r' data-config-url="(.+?)"', webpage, u'config URL')
  121. config_json = self._download_webpage(config_url, video_id)
  122. config = json.loads(config_json)
  123. except Exception as e:
  124. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  125. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  126. if re.search('If so please provide the correct password.', webpage):
  127. self._verify_video_password(url, video_id, webpage)
  128. return self._real_extract(url)
  129. else:
  130. raise ExtractorError(u'Unable to extract info section',
  131. cause=e)
  132. # Extract title
  133. video_title = config["video"]["title"]
  134. # Extract uploader and uploader_id
  135. video_uploader = config["video"]["owner"]["name"]
  136. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  137. # Extract video thumbnail
  138. video_thumbnail = config["video"].get("thumbnail")
  139. if video_thumbnail is None:
  140. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
  141. # Extract video description
  142. video_description = None
  143. try:
  144. video_description = get_element_by_attribute("itemprop", "description", webpage)
  145. if video_description: video_description = clean_html(video_description)
  146. except AssertionError as err:
  147. # On some pages like (http://player.vimeo.com/video/54469442) the
  148. # html tags are not closed, python 2.6 cannot handle it
  149. if err.args[0] == 'we should not get here!':
  150. pass
  151. else:
  152. raise
  153. # Extract upload date
  154. video_upload_date = None
  155. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  156. if mobj is not None:
  157. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  158. # Vimeo specific: extract request signature and timestamp
  159. sig = config['request']['signature']
  160. timestamp = config['request']['timestamp']
  161. # Vimeo specific: extract video codec and quality information
  162. # First consider quality, then codecs, then take everything
  163. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  164. files = { 'hd': [], 'sd': [], 'other': []}
  165. config_files = config["video"].get("files") or config["request"].get("files")
  166. for codec_name, codec_extension in codecs:
  167. for quality in config_files.get(codec_name, []):
  168. format_id = '-'.join((codec_name, quality)).lower()
  169. key = quality if quality in files else 'other'
  170. video_url = None
  171. if isinstance(config_files[codec_name], dict):
  172. file_info = config_files[codec_name][quality]
  173. video_url = file_info.get('url')
  174. else:
  175. file_info = {}
  176. if video_url is None:
  177. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  178. %(video_id, sig, timestamp, quality, codec_name.upper())
  179. files[key].append({
  180. 'ext': codec_extension,
  181. 'url': video_url,
  182. 'format_id': format_id,
  183. 'width': file_info.get('width'),
  184. 'height': file_info.get('height'),
  185. })
  186. formats = []
  187. for key in ('other', 'sd', 'hd'):
  188. formats += files[key]
  189. if len(formats) == 0:
  190. raise ExtractorError(u'No known codec found')
  191. return [{
  192. 'id': video_id,
  193. 'uploader': video_uploader,
  194. 'uploader_id': video_uploader_id,
  195. 'upload_date': video_upload_date,
  196. 'title': video_title,
  197. 'thumbnail': video_thumbnail,
  198. 'description': video_description,
  199. 'formats': formats,
  200. }]
  201. class VimeoChannelIE(InfoExtractor):
  202. IE_NAME = u'vimeo:channel'
  203. _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
  204. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  205. def _real_extract(self, url):
  206. mobj = re.match(self._VALID_URL, url)
  207. channel_id = mobj.group('id')
  208. video_ids = []
  209. for pagenum in itertools.count(1):
  210. webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
  211. channel_id, u'Downloading page %s' % pagenum)
  212. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  213. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  214. break
  215. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  216. for video_id in video_ids]
  217. channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
  218. webpage, u'channel title')
  219. return {'_type': 'playlist',
  220. 'id': channel_id,
  221. 'title': channel_title,
  222. 'entries': entries,
  223. }