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