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.

419 lines
17 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import itertools
  6. from .common import InfoExtractor
  7. from .subtitles import SubtitlesInfoExtractor
  8. from ..utils import (
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. clean_html,
  12. get_element_by_attribute,
  13. ExtractorError,
  14. RegexNotFoundError,
  15. std_headers,
  16. unsmuggle_url,
  17. )
  18. class VimeoIE(SubtitlesInfoExtractor):
  19. """Information extractor for vimeo.com."""
  20. # _VALID_URL matches Vimeo URLs
  21. _VALID_URL = r'''(?x)
  22. (?P<proto>(?:https?:)?//)?
  23. (?:(?:www|(?P<player>player))\.)?
  24. vimeo(?P<pro>pro)?\.com/
  25. (?:.*?/)?
  26. (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
  27. (?:videos?/)?
  28. (?P<id>[0-9]+)
  29. /?(?:[?&].*)?(?:[#].*)?$'''
  30. _NETRC_MACHINE = 'vimeo'
  31. IE_NAME = 'vimeo'
  32. _TESTS = [
  33. {
  34. 'url': 'http://vimeo.com/56015672#at=0',
  35. 'md5': '8879b6cc097e987f02484baf890129e5',
  36. 'info_dict': {
  37. 'id': '56015672',
  38. 'ext': 'mp4',
  39. "upload_date": "20121220",
  40. "description": "This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  41. "uploader_id": "user7108434",
  42. "uploader": "Filippo Valsorda",
  43. "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  44. },
  45. },
  46. {
  47. 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  48. 'file': '68093876.mp4',
  49. 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
  50. 'note': 'Vimeo Pro video (#1197)',
  51. 'info_dict': {
  52. 'uploader_id': 'openstreetmapus',
  53. 'uploader': 'OpenStreetMap US',
  54. 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  55. },
  56. },
  57. {
  58. 'url': 'http://player.vimeo.com/video/54469442',
  59. 'file': '54469442.mp4',
  60. 'md5': '619b811a4417aa4abe78dc653becf511',
  61. 'note': 'Videos that embed the url in the player page',
  62. 'info_dict': {
  63. 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software',
  64. 'uploader': 'The BLN & Business of Software',
  65. 'uploader_id': 'theblnbusinessofsoftware',
  66. },
  67. },
  68. {
  69. 'url': 'http://vimeo.com/68375962',
  70. 'file': '68375962.mp4',
  71. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  72. 'note': 'Video protected with password',
  73. 'info_dict': {
  74. 'title': 'youtube-dl password protected test video',
  75. 'upload_date': '20130614',
  76. 'uploader_id': 'user18948128',
  77. 'uploader': 'Jaime Marquínez Ferrándiz',
  78. },
  79. 'params': {
  80. 'videopassword': 'youtube-dl',
  81. },
  82. },
  83. {
  84. 'url': 'http://vimeo.com/76979871',
  85. 'md5': '3363dd6ffebe3784d56f4132317fd446',
  86. 'note': 'Video with subtitles',
  87. 'info_dict': {
  88. 'id': '76979871',
  89. 'ext': 'mp4',
  90. 'title': 'The New Vimeo Player (You Know, For Videos)',
  91. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  92. 'upload_date': '20131015',
  93. 'uploader_id': 'staff',
  94. 'uploader': 'Vimeo Staff',
  95. }
  96. },
  97. ]
  98. def _login(self):
  99. (username, password) = self._get_login_info()
  100. if username is None:
  101. return
  102. self.report_login()
  103. login_url = 'https://vimeo.com/log_in'
  104. webpage = self._download_webpage(login_url, None, False)
  105. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  106. data = compat_urllib_parse.urlencode({'email': username,
  107. 'password': password,
  108. 'action': 'login',
  109. 'service': 'vimeo',
  110. 'token': token,
  111. })
  112. login_request = compat_urllib_request.Request(login_url, data)
  113. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  114. login_request.add_header('Cookie', 'xsrft=%s' % token)
  115. self._download_webpage(login_request, None, False, 'Wrong login info')
  116. def _verify_video_password(self, url, video_id, webpage):
  117. password = self._downloader.params.get('videopassword', None)
  118. if password is None:
  119. raise ExtractorError('This video is protected by a password, use the --video-password option')
  120. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  121. data = compat_urllib_parse.urlencode({'password': password,
  122. 'token': token})
  123. # I didn't manage to use the password with https
  124. if url.startswith('https'):
  125. pass_url = url.replace('https','http')
  126. else:
  127. pass_url = url
  128. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  129. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  130. password_request.add_header('Cookie', 'xsrft=%s' % token)
  131. self._download_webpage(password_request, video_id,
  132. 'Verifying the password',
  133. 'Wrong password')
  134. def _verify_player_video_password(self, url, video_id):
  135. password = self._downloader.params.get('videopassword', None)
  136. if password is None:
  137. raise ExtractorError('This video is protected by a password, use the --video-password option')
  138. data = compat_urllib_parse.urlencode({'password': password})
  139. pass_url = url + '/check-password'
  140. password_request = compat_urllib_request.Request(pass_url, data)
  141. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  142. return self._download_json(
  143. password_request, video_id,
  144. 'Verifying the password',
  145. 'Wrong password')
  146. def _real_initialize(self):
  147. self._login()
  148. def _real_extract(self, url):
  149. url, data = unsmuggle_url(url)
  150. headers = std_headers
  151. if data is not None:
  152. headers = headers.copy()
  153. headers.update(data)
  154. # Extract ID from URL
  155. mobj = re.match(self._VALID_URL, url)
  156. video_id = mobj.group('id')
  157. if mobj.group('pro') or mobj.group('player'):
  158. url = 'http://player.vimeo.com/video/' + video_id
  159. else:
  160. url = 'https://vimeo.com/' + video_id
  161. # Retrieve video webpage to extract further information
  162. request = compat_urllib_request.Request(url, None, headers)
  163. webpage = self._download_webpage(request, video_id)
  164. # Now we begin extracting as much information as we can from what we
  165. # retrieved. First we extract the information common to all extractors,
  166. # and latter we extract those that are Vimeo specific.
  167. self.report_extraction(video_id)
  168. # Extract the config JSON
  169. try:
  170. try:
  171. config_url = self._html_search_regex(
  172. r' data-config-url="(.+?)"', webpage, 'config URL')
  173. config_json = self._download_webpage(config_url, video_id)
  174. config = json.loads(config_json)
  175. except RegexNotFoundError:
  176. # For pro videos or player.vimeo.com urls
  177. # We try to find out to which variable is assigned the config dic
  178. m_variable_name = re.search('(\w)\.video\.id', webpage)
  179. if m_variable_name is not None:
  180. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  181. else:
  182. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  183. config = self._search_regex(config_re, webpage, 'info section',
  184. flags=re.DOTALL)
  185. config = json.loads(config)
  186. except Exception as e:
  187. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  188. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  189. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  190. self._verify_video_password(url, video_id, webpage)
  191. return self._real_extract(url)
  192. else:
  193. raise ExtractorError('Unable to extract info section',
  194. cause=e)
  195. else:
  196. if config.get('view') == 4:
  197. config = self._verify_player_video_password(url, video_id)
  198. # Extract title
  199. video_title = config["video"]["title"]
  200. # Extract uploader and uploader_id
  201. video_uploader = config["video"]["owner"]["name"]
  202. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  203. # Extract video thumbnail
  204. video_thumbnail = config["video"].get("thumbnail")
  205. if video_thumbnail is None:
  206. video_thumbs = config["video"].get("thumbs")
  207. if video_thumbs and isinstance(video_thumbs, dict):
  208. _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in video_thumbs.items())[-1]
  209. # Extract video description
  210. video_description = None
  211. try:
  212. video_description = get_element_by_attribute("itemprop", "description", webpage)
  213. if video_description: video_description = clean_html(video_description)
  214. except AssertionError as err:
  215. # On some pages like (http://player.vimeo.com/video/54469442) the
  216. # html tags are not closed, python 2.6 cannot handle it
  217. if err.args[0] == 'we should not get here!':
  218. pass
  219. else:
  220. raise
  221. # Extract upload date
  222. video_upload_date = None
  223. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  224. if mobj is not None:
  225. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  226. try:
  227. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  228. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  229. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  230. except RegexNotFoundError:
  231. # This info is only available in vimeo.com/{id} urls
  232. view_count = None
  233. like_count = None
  234. comment_count = None
  235. # Vimeo specific: extract request signature and timestamp
  236. sig = config['request']['signature']
  237. timestamp = config['request']['timestamp']
  238. # Vimeo specific: extract video codec and quality information
  239. # First consider quality, then codecs, then take everything
  240. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  241. files = {'hd': [], 'sd': [], 'other': []}
  242. config_files = config["video"].get("files") or config["request"].get("files")
  243. for codec_name, codec_extension in codecs:
  244. for quality in config_files.get(codec_name, []):
  245. format_id = '-'.join((codec_name, quality)).lower()
  246. key = quality if quality in files else 'other'
  247. video_url = None
  248. if isinstance(config_files[codec_name], dict):
  249. file_info = config_files[codec_name][quality]
  250. video_url = file_info.get('url')
  251. else:
  252. file_info = {}
  253. if video_url is None:
  254. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  255. %(video_id, sig, timestamp, quality, codec_name.upper())
  256. files[key].append({
  257. 'ext': codec_extension,
  258. 'url': video_url,
  259. 'format_id': format_id,
  260. 'width': file_info.get('width'),
  261. 'height': file_info.get('height'),
  262. })
  263. formats = []
  264. for key in ('other', 'sd', 'hd'):
  265. formats += files[key]
  266. if len(formats) == 0:
  267. raise ExtractorError('No known codec found')
  268. subtitles = {}
  269. text_tracks = config['request'].get('text_tracks')
  270. if text_tracks:
  271. for tt in text_tracks:
  272. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  273. video_subtitles = self.extract_subtitles(video_id, subtitles)
  274. if self._downloader.params.get('listsubtitles', False):
  275. self._list_available_subtitles(video_id, subtitles)
  276. return
  277. return {
  278. 'id': video_id,
  279. 'uploader': video_uploader,
  280. 'uploader_id': video_uploader_id,
  281. 'upload_date': video_upload_date,
  282. 'title': video_title,
  283. 'thumbnail': video_thumbnail,
  284. 'description': video_description,
  285. 'formats': formats,
  286. 'webpage_url': url,
  287. 'view_count': view_count,
  288. 'like_count': like_count,
  289. 'comment_count': comment_count,
  290. 'subtitles': video_subtitles,
  291. }
  292. class VimeoChannelIE(InfoExtractor):
  293. IE_NAME = 'vimeo:channel'
  294. _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)'
  295. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  296. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  297. def _page_url(self, base_url, pagenum):
  298. return '%s/videos/page:%d/' % (base_url, pagenum)
  299. def _extract_list_title(self, webpage):
  300. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  301. def _extract_videos(self, list_id, base_url):
  302. video_ids = []
  303. for pagenum in itertools.count(1):
  304. webpage = self._download_webpage(
  305. self._page_url(base_url, pagenum) ,list_id,
  306. 'Downloading page %s' % pagenum)
  307. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  308. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  309. break
  310. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  311. for video_id in video_ids]
  312. return {'_type': 'playlist',
  313. 'id': list_id,
  314. 'title': self._extract_list_title(webpage),
  315. 'entries': entries,
  316. }
  317. def _real_extract(self, url):
  318. mobj = re.match(self._VALID_URL, url)
  319. channel_id = mobj.group('id')
  320. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  321. class VimeoUserIE(VimeoChannelIE):
  322. IE_NAME = 'vimeo:user'
  323. _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
  324. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  325. @classmethod
  326. def suitable(cls, url):
  327. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  328. return False
  329. return super(VimeoUserIE, cls).suitable(url)
  330. def _real_extract(self, url):
  331. mobj = re.match(self._VALID_URL, url)
  332. name = mobj.group('name')
  333. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  334. class VimeoAlbumIE(VimeoChannelIE):
  335. IE_NAME = 'vimeo:album'
  336. _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
  337. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  338. def _page_url(self, base_url, pagenum):
  339. return '%s/page:%d/' % (base_url, pagenum)
  340. def _real_extract(self, url):
  341. mobj = re.match(self._VALID_URL, url)
  342. album_id = mobj.group('id')
  343. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  344. class VimeoGroupsIE(VimeoAlbumIE):
  345. IE_NAME = 'vimeo:group'
  346. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  347. def _extract_list_title(self, webpage):
  348. return self._og_search_title(webpage)
  349. def _real_extract(self, url):
  350. mobj = re.match(self._VALID_URL, url)
  351. name = mobj.group('name')
  352. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  353. class VimeoReviewIE(InfoExtractor):
  354. IE_NAME = 'vimeo:review'
  355. IE_DESC = 'Review pages on vimeo'
  356. _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  357. _TEST = {
  358. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  359. 'file': '75524534.mp4',
  360. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  361. 'info_dict': {
  362. 'title': "DICK HARDWICK 'Comedian'",
  363. 'uploader': 'Richard Hardwick',
  364. }
  365. }
  366. def _real_extract(self, url):
  367. mobj = re.match(self._VALID_URL, url)
  368. video_id = mobj.group('id')
  369. player_url = 'https://player.vimeo.com/player/' + video_id
  370. return self.url_result(player_url, 'Vimeo', video_id)