[vimeo] Now VimeoIE doesn't match urls of channels with a numeric id (fixes #2552)
[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     @classmethod
106     def suitable(cls, url):
107         if VimeoChannelIE.suitable(url):
108             # Otherwise channel urls like http://vimeo.com/channels/31259 would
109             # match
110             return False
111         else:
112             return super(VimeoIE, cls).suitable(url)
113
114     def _login(self):
115         (username, password) = self._get_login_info()
116         if username is None:
117             return
118         self.report_login()
119         login_url = 'https://vimeo.com/log_in'
120         webpage = self._download_webpage(login_url, None, False)
121         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
122         data = compat_urllib_parse.urlencode({'email': username,
123                                               'password': password,
124                                               'action': 'login',
125                                               'service': 'vimeo',
126                                               'token': token,
127                                               })
128         login_request = compat_urllib_request.Request(login_url, data)
129         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
130         login_request.add_header('Cookie', 'xsrft=%s' % token)
131         self._download_webpage(login_request, None, False, 'Wrong login info')
132
133     def _verify_video_password(self, url, video_id, webpage):
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         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
138         data = compat_urllib_parse.urlencode({'password': password,
139                                               'token': token})
140         # I didn't manage to use the password with https
141         if url.startswith('https'):
142             pass_url = url.replace('https','http')
143         else:
144             pass_url = url
145         password_request = compat_urllib_request.Request(pass_url+'/password', data)
146         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
147         password_request.add_header('Cookie', 'xsrft=%s' % token)
148         self._download_webpage(password_request, video_id,
149                                'Verifying the password',
150                                'Wrong password')
151
152     def _verify_player_video_password(self, url, video_id):
153         password = self._downloader.params.get('videopassword', None)
154         if password is None:
155             raise ExtractorError('This video is protected by a password, use the --video-password option')
156         data = compat_urllib_parse.urlencode({'password': password})
157         pass_url = url + '/check-password'
158         password_request = compat_urllib_request.Request(pass_url, data)
159         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
160         return self._download_json(
161             password_request, video_id,
162             'Verifying the password',
163             'Wrong password')
164
165     def _real_initialize(self):
166         self._login()
167
168     def _real_extract(self, url):
169         url, data = unsmuggle_url(url)
170         headers = std_headers
171         if data is not None:
172             headers = headers.copy()
173             headers.update(data)
174
175         # Extract ID from URL
176         mobj = re.match(self._VALID_URL, url)
177         video_id = mobj.group('id')
178         if mobj.group('pro') or mobj.group('player'):
179             url = 'http://player.vimeo.com/video/' + video_id
180         else:
181             url = 'https://vimeo.com/' + video_id
182
183         # Retrieve video webpage to extract further information
184         request = compat_urllib_request.Request(url, None, headers)
185         try:
186             webpage = self._download_webpage(request, video_id)
187         except ExtractorError as ee:
188             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
189                 errmsg = ee.cause.read()
190                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
191                     raise ExtractorError(
192                         'Cannot download embed-only video without embedding '
193                         'URL. Please call youtube-dl with the URL of the page '
194                         'that embeds this video.',
195                         expected=True)
196             raise
197
198         # Now we begin extracting as much information as we can from what we
199         # retrieved. First we extract the information common to all extractors,
200         # and latter we extract those that are Vimeo specific.
201         self.report_extraction(video_id)
202
203         # Extract the config JSON
204         try:
205             try:
206                 config_url = self._html_search_regex(
207                     r' data-config-url="(.+?)"', webpage, 'config URL')
208                 config_json = self._download_webpage(config_url, video_id)
209                 config = json.loads(config_json)
210             except RegexNotFoundError:
211                 # For pro videos or player.vimeo.com urls
212                 # We try to find out to which variable is assigned the config dic
213                 m_variable_name = re.search('(\w)\.video\.id', webpage)
214                 if m_variable_name is not None:
215                     config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
216                 else:
217                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
218                 config = self._search_regex(config_re, webpage, 'info section',
219                     flags=re.DOTALL)
220                 config = json.loads(config)
221         except Exception as e:
222             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
223                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
224
225             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
226                 self._verify_video_password(url, video_id, webpage)
227                 return self._real_extract(url)
228             else:
229                 raise ExtractorError('Unable to extract info section',
230                                      cause=e)
231         else:
232             if config.get('view') == 4:
233                 config = self._verify_player_video_password(url, video_id)
234
235         # Extract title
236         video_title = config["video"]["title"]
237
238         # Extract uploader and uploader_id
239         video_uploader = config["video"]["owner"]["name"]
240         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
241
242         # Extract video thumbnail
243         video_thumbnail = config["video"].get("thumbnail")
244         if video_thumbnail is None:
245             video_thumbs = config["video"].get("thumbs")
246             if video_thumbs and isinstance(video_thumbs, dict):
247                 _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in video_thumbs.items())[-1]
248
249         # Extract video description
250         video_description = None
251         try:
252             video_description = get_element_by_attribute("itemprop", "description", webpage)
253             if video_description: video_description = clean_html(video_description)
254         except AssertionError as err:
255             # On some pages like (http://player.vimeo.com/video/54469442) the
256             # html tags are not closed, python 2.6 cannot handle it
257             if err.args[0] == 'we should not get here!':
258                 pass
259             else:
260                 raise
261
262         # Extract upload date
263         video_upload_date = None
264         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
265         if mobj is not None:
266             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
267
268         try:
269             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
270             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
271             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
272         except RegexNotFoundError:
273             # This info is only available in vimeo.com/{id} urls
274             view_count = None
275             like_count = None
276             comment_count = None
277
278         # Vimeo specific: extract request signature and timestamp
279         sig = config['request']['signature']
280         timestamp = config['request']['timestamp']
281
282         # Vimeo specific: extract video codec and quality information
283         # First consider quality, then codecs, then take everything
284         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
285         files = {'hd': [], 'sd': [], 'other': []}
286         config_files = config["video"].get("files") or config["request"].get("files")
287         for codec_name, codec_extension in codecs:
288             for quality in config_files.get(codec_name, []):
289                 format_id = '-'.join((codec_name, quality)).lower()
290                 key = quality if quality in files else 'other'
291                 video_url = None
292                 if isinstance(config_files[codec_name], dict):
293                     file_info = config_files[codec_name][quality]
294                     video_url = file_info.get('url')
295                 else:
296                     file_info = {}
297                 if video_url is None:
298                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
299                         %(video_id, sig, timestamp, quality, codec_name.upper())
300
301                 files[key].append({
302                     'ext': codec_extension,
303                     'url': video_url,
304                     'format_id': format_id,
305                     'width': file_info.get('width'),
306                     'height': file_info.get('height'),
307                 })
308         formats = []
309         for key in ('other', 'sd', 'hd'):
310             formats += files[key]
311         if len(formats) == 0:
312             raise ExtractorError('No known codec found')
313
314         subtitles = {}
315         text_tracks = config['request'].get('text_tracks')
316         if text_tracks:
317             for tt in text_tracks:
318                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
319
320         video_subtitles = self.extract_subtitles(video_id, subtitles)
321         if self._downloader.params.get('listsubtitles', False):
322             self._list_available_subtitles(video_id, subtitles)
323             return
324
325         return {
326             'id': video_id,
327             'uploader': video_uploader,
328             'uploader_id': video_uploader_id,
329             'upload_date': video_upload_date,
330             'title': video_title,
331             'thumbnail': video_thumbnail,
332             'description': video_description,
333             'formats': formats,
334             'webpage_url': url,
335             'view_count': view_count,
336             'like_count': like_count,
337             'comment_count': comment_count,
338             'subtitles': video_subtitles,
339         }
340
341
342 class VimeoChannelIE(InfoExtractor):
343     IE_NAME = 'vimeo:channel'
344     _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)/?(\?.*)?$'
345     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
346     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
347
348     def _page_url(self, base_url, pagenum):
349         return '%s/videos/page:%d/' % (base_url, pagenum)
350
351     def _extract_list_title(self, webpage):
352         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
353
354     def _extract_videos(self, list_id, base_url):
355         video_ids = []
356         for pagenum in itertools.count(1):
357             webpage = self._download_webpage(
358                 self._page_url(base_url, pagenum) ,list_id,
359                 'Downloading page %s' % pagenum)
360             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
361             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
362                 break
363
364         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
365                    for video_id in video_ids]
366         return {'_type': 'playlist',
367                 'id': list_id,
368                 'title': self._extract_list_title(webpage),
369                 'entries': entries,
370                 }
371
372     def _real_extract(self, url):
373         mobj = re.match(self._VALID_URL, url)
374         channel_id =  mobj.group('id')
375         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
376
377
378 class VimeoUserIE(VimeoChannelIE):
379     IE_NAME = 'vimeo:user'
380     _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
381     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
382
383     @classmethod
384     def suitable(cls, url):
385         if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
386             return False
387         return super(VimeoUserIE, cls).suitable(url)
388
389     def _real_extract(self, url):
390         mobj = re.match(self._VALID_URL, url)
391         name = mobj.group('name')
392         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
393
394
395 class VimeoAlbumIE(VimeoChannelIE):
396     IE_NAME = 'vimeo:album'
397     _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
398     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
399
400     def _page_url(self, base_url, pagenum):
401         return '%s/page:%d/' % (base_url, pagenum)
402
403     def _real_extract(self, url):
404         mobj = re.match(self._VALID_URL, url)
405         album_id = mobj.group('id')
406         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
407
408
409 class VimeoGroupsIE(VimeoAlbumIE):
410     IE_NAME = 'vimeo:group'
411     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
412
413     def _extract_list_title(self, webpage):
414         return self._og_search_title(webpage)
415
416     def _real_extract(self, url):
417         mobj = re.match(self._VALID_URL, url)
418         name = mobj.group('name')
419         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
420
421
422 class VimeoReviewIE(InfoExtractor):
423     IE_NAME = 'vimeo:review'
424     IE_DESC = 'Review pages on vimeo'
425     _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
426     _TEST = {
427         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
428         'file': '75524534.mp4',
429         'md5': 'c507a72f780cacc12b2248bb4006d253',
430         'info_dict': {
431             'title': "DICK HARDWICK 'Comedian'",
432             'uploader': 'Richard Hardwick',
433         }
434     }
435
436     def _real_extract(self, url):
437         mobj = re.match(self._VALID_URL, url)
438         video_id = mobj.group('id')
439         player_url = 'https://player.vimeo.com/player/' + video_id
440         return self.url_result(player_url, 'Vimeo', video_id)