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.

417 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_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
  207. # Extract video description
  208. video_description = None
  209. try:
  210. video_description = get_element_by_attribute("itemprop", "description", webpage)
  211. if video_description: video_description = clean_html(video_description)
  212. except AssertionError as err:
  213. # On some pages like (http://player.vimeo.com/video/54469442) the
  214. # html tags are not closed, python 2.6 cannot handle it
  215. if err.args[0] == 'we should not get here!':
  216. pass
  217. else:
  218. raise
  219. # Extract upload date
  220. video_upload_date = None
  221. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  222. if mobj is not None:
  223. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  224. try:
  225. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  226. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  227. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  228. except RegexNotFoundError:
  229. # This info is only available in vimeo.com/{id} urls
  230. view_count = None
  231. like_count = None
  232. comment_count = None
  233. # Vimeo specific: extract request signature and timestamp
  234. sig = config['request']['signature']
  235. timestamp = config['request']['timestamp']
  236. # Vimeo specific: extract video codec and quality information
  237. # First consider quality, then codecs, then take everything
  238. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  239. files = {'hd': [], 'sd': [], 'other': []}
  240. config_files = config["video"].get("files") or config["request"].get("files")
  241. for codec_name, codec_extension in codecs:
  242. for quality in config_files.get(codec_name, []):
  243. format_id = '-'.join((codec_name, quality)).lower()
  244. key = quality if quality in files else 'other'
  245. video_url = None
  246. if isinstance(config_files[codec_name], dict):
  247. file_info = config_files[codec_name][quality]
  248. video_url = file_info.get('url')
  249. else:
  250. file_info = {}
  251. if video_url is None:
  252. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  253. %(video_id, sig, timestamp, quality, codec_name.upper())
  254. files[key].append({
  255. 'ext': codec_extension,
  256. 'url': video_url,
  257. 'format_id': format_id,
  258. 'width': file_info.get('width'),
  259. 'height': file_info.get('height'),
  260. })
  261. formats = []
  262. for key in ('other', 'sd', 'hd'):
  263. formats += files[key]
  264. if len(formats) == 0:
  265. raise ExtractorError('No known codec found')
  266. subtitles = {}
  267. text_tracks = config['request'].get('text_tracks')
  268. if text_tracks:
  269. for tt in text_tracks:
  270. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  271. video_subtitles = self.extract_subtitles(video_id, subtitles)
  272. if self._downloader.params.get('listsubtitles', False):
  273. self._list_available_subtitles(video_id, subtitles)
  274. return
  275. return {
  276. 'id': video_id,
  277. 'uploader': video_uploader,
  278. 'uploader_id': video_uploader_id,
  279. 'upload_date': video_upload_date,
  280. 'title': video_title,
  281. 'thumbnail': video_thumbnail,
  282. 'description': video_description,
  283. 'formats': formats,
  284. 'webpage_url': url,
  285. 'view_count': view_count,
  286. 'like_count': like_count,
  287. 'comment_count': comment_count,
  288. 'subtitles': video_subtitles,
  289. }
  290. class VimeoChannelIE(InfoExtractor):
  291. IE_NAME = 'vimeo:channel'
  292. _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)'
  293. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  294. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  295. def _page_url(self, base_url, pagenum):
  296. return '%s/videos/page:%d/' % (base_url, pagenum)
  297. def _extract_list_title(self, webpage):
  298. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  299. def _extract_videos(self, list_id, base_url):
  300. video_ids = []
  301. for pagenum in itertools.count(1):
  302. webpage = self._download_webpage(
  303. self._page_url(base_url, pagenum) ,list_id,
  304. 'Downloading page %s' % pagenum)
  305. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  306. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  307. break
  308. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  309. for video_id in video_ids]
  310. return {'_type': 'playlist',
  311. 'id': list_id,
  312. 'title': self._extract_list_title(webpage),
  313. 'entries': entries,
  314. }
  315. def _real_extract(self, url):
  316. mobj = re.match(self._VALID_URL, url)
  317. channel_id = mobj.group('id')
  318. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  319. class VimeoUserIE(VimeoChannelIE):
  320. IE_NAME = 'vimeo:user'
  321. _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
  322. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  323. @classmethod
  324. def suitable(cls, url):
  325. if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
  326. return False
  327. return super(VimeoUserIE, cls).suitable(url)
  328. def _real_extract(self, url):
  329. mobj = re.match(self._VALID_URL, url)
  330. name = mobj.group('name')
  331. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  332. class VimeoAlbumIE(VimeoChannelIE):
  333. IE_NAME = 'vimeo:album'
  334. _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
  335. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  336. def _page_url(self, base_url, pagenum):
  337. return '%s/page:%d/' % (base_url, pagenum)
  338. def _real_extract(self, url):
  339. mobj = re.match(self._VALID_URL, url)
  340. album_id = mobj.group('id')
  341. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  342. class VimeoGroupsIE(VimeoAlbumIE):
  343. IE_NAME = 'vimeo:group'
  344. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  345. def _extract_list_title(self, webpage):
  346. return self._og_search_title(webpage)
  347. def _real_extract(self, url):
  348. mobj = re.match(self._VALID_URL, url)
  349. name = mobj.group('name')
  350. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  351. class VimeoReviewIE(InfoExtractor):
  352. IE_NAME = 'vimeo:review'
  353. IE_DESC = 'Review pages on vimeo'
  354. _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  355. _TEST = {
  356. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  357. 'file': '75524534.mp4',
  358. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  359. 'info_dict': {
  360. 'title': "DICK HARDWICK 'Comedian'",
  361. 'uploader': 'Richard Hardwick',
  362. }
  363. }
  364. def _real_extract(self, url):
  365. mobj = re.match(self._VALID_URL, url)
  366. video_id = mobj.group('id')
  367. player_url = 'https://player.vimeo.com/player/' + video_id
  368. return self.url_result(player_url, 'Vimeo', video_id)