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