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.

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