vimeo.py 11 KB

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