[vimeo] Check source file URL (Closes #8187)
[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 ..compat import (
10     compat_HTTPError,
11     compat_urlparse,
12 )
13 from ..utils import (
14     determine_ext,
15     encode_dict,
16     ExtractorError,
17     InAdvancePagedList,
18     int_or_none,
19     RegexNotFoundError,
20     sanitized_Request,
21     smuggle_url,
22     std_headers,
23     unified_strdate,
24     unsmuggle_url,
25     urlencode_postdata,
26     unescapeHTML,
27     parse_filesize,
28 )
29
30
31 class VimeoBaseInfoExtractor(InfoExtractor):
32     _NETRC_MACHINE = 'vimeo'
33     _LOGIN_REQUIRED = False
34     _LOGIN_URL = 'https://vimeo.com/log_in'
35
36     def _login(self):
37         (username, password) = self._get_login_info()
38         if username is None:
39             if self._LOGIN_REQUIRED:
40                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
41             return
42         self.report_login()
43         webpage = self._download_webpage(self._LOGIN_URL, None, False)
44         token, vuid = self._extract_xsrft_and_vuid(webpage)
45         data = urlencode_postdata(encode_dict({
46             'action': 'login',
47             'email': username,
48             'password': password,
49             'service': 'vimeo',
50             'token': token,
51         }))
52         login_request = sanitized_Request(self._LOGIN_URL, data)
53         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
54         login_request.add_header('Referer', self._LOGIN_URL)
55         self._set_vimeo_cookie('vuid', vuid)
56         self._download_webpage(login_request, None, False, 'Wrong login info')
57
58     def _extract_xsrft_and_vuid(self, webpage):
59         xsrft = self._search_regex(
60             r'xsrft\s*[=:]\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
61             webpage, 'login token', group='xsrft')
62         vuid = self._search_regex(
63             r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
64             webpage, 'vuid', group='vuid')
65         return xsrft, vuid
66
67     def _set_vimeo_cookie(self, name, value):
68         self._set_cookie('vimeo.com', name, value)
69
70
71 class VimeoIE(VimeoBaseInfoExtractor):
72     """Information extractor for vimeo.com."""
73
74     # _VALID_URL matches Vimeo URLs
75     _VALID_URL = r'''(?x)
76         https?://
77         (?:(?:www|(?P<player>player))\.)?
78         vimeo(?P<pro>pro)?\.com/
79         (?!channels/[^/?#]+/?(?:$|[?#])|album/)
80         (?:.*?/)?
81         (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
82         (?:videos?/)?
83         (?P<id>[0-9]+)
84         /?(?:[?&].*)?(?:[#].*)?$'''
85     IE_NAME = 'vimeo'
86     _TESTS = [
87         {
88             'url': 'http://vimeo.com/56015672#at=0',
89             'md5': '8879b6cc097e987f02484baf890129e5',
90             'info_dict': {
91                 'id': '56015672',
92                 'ext': 'mp4',
93                 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
94                 'description': 'md5:2d3305bad981a06ff79f027f19865021',
95                 'upload_date': '20121220',
96                 'uploader_id': 'user7108434',
97                 'uploader': 'Filippo Valsorda',
98                 'duration': 10,
99             },
100         },
101         {
102             'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
103             'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
104             'note': 'Vimeo Pro video (#1197)',
105             'info_dict': {
106                 'id': '68093876',
107                 'ext': 'mp4',
108                 'uploader_id': 'openstreetmapus',
109                 'uploader': 'OpenStreetMap US',
110                 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
111                 'description': 'md5:fd69a7b8d8c34a4e1d2ec2e4afd6ec30',
112                 'duration': 1595,
113             },
114         },
115         {
116             'url': 'http://player.vimeo.com/video/54469442',
117             'md5': '619b811a4417aa4abe78dc653becf511',
118             'note': 'Videos that embed the url in the player page',
119             'info_dict': {
120                 'id': '54469442',
121                 'ext': 'mp4',
122                 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
123                 'uploader': 'The BLN & Business of Software',
124                 'uploader_id': 'theblnbusinessofsoftware',
125                 'duration': 3610,
126                 'description': None,
127             },
128         },
129         {
130             'url': 'http://vimeo.com/68375962',
131             'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
132             'note': 'Video protected with password',
133             'info_dict': {
134                 'id': '68375962',
135                 'ext': 'mp4',
136                 'title': 'youtube-dl password protected test video',
137                 'upload_date': '20130614',
138                 'uploader_id': 'user18948128',
139                 'uploader': 'Jaime Marquínez Ferrándiz',
140                 'duration': 10,
141                 'description': 'This is "youtube-dl password protected test video" by Jaime Marquínez Ferrándiz on Vimeo, the home for high quality videos and the people\u2026',
142             },
143             'params': {
144                 'videopassword': 'youtube-dl',
145             },
146         },
147         {
148             'url': 'http://vimeo.com/channels/keypeele/75629013',
149             'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
150             'note': 'Video is freely available via original URL '
151                     'and protected with password when accessed via http://vimeo.com/75629013',
152             'info_dict': {
153                 'id': '75629013',
154                 'ext': 'mp4',
155                 'title': 'Key & Peele: Terrorist Interrogation',
156                 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
157                 'uploader_id': 'atencio',
158                 'uploader': 'Peter Atencio',
159                 'upload_date': '20130927',
160                 'duration': 187,
161             },
162         },
163         {
164             'url': 'http://vimeo.com/76979871',
165             'note': 'Video with subtitles',
166             'info_dict': {
167                 'id': '76979871',
168                 'ext': 'mp4',
169                 'title': 'The New Vimeo Player (You Know, For Videos)',
170                 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
171                 'upload_date': '20131015',
172                 'uploader_id': 'staff',
173                 'uploader': 'Vimeo Staff',
174                 'duration': 62,
175             }
176         },
177         {
178             # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
179             'url': 'https://player.vimeo.com/video/98044508',
180             'note': 'The js code contains assignments to the same variable as the config',
181             'info_dict': {
182                 'id': '98044508',
183                 'ext': 'mp4',
184                 'title': 'Pier Solar OUYA Official Trailer',
185                 'uploader': 'Tulio Gonçalves',
186                 'uploader_id': 'user28849593',
187             },
188         },
189         {
190             # contains original format
191             'url': 'https://vimeo.com/33951933',
192             'md5': '53c688fa95a55bf4b7293d37a89c5c53',
193             'info_dict': {
194                 'id': '33951933',
195                 'ext': 'mp4',
196                 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
197                 'uploader': 'The DMCI',
198                 'uploader_id': 'dmci',
199                 'upload_date': '20111220',
200                 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
201             },
202         },
203         {
204             'url': 'https://vimeo.com/109815029',
205             'note': 'Video not completely processed, "failed" seed status',
206             'only_matching': True,
207         },
208         {
209             'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
210             'only_matching': True,
211         },
212     ]
213
214     @staticmethod
215     def _extract_vimeo_url(url, webpage):
216         # Look for embedded (iframe) Vimeo player
217         mobj = re.search(
218             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
219         if mobj:
220             player_url = unescapeHTML(mobj.group('url'))
221             surl = smuggle_url(player_url, {'http_headers': {'Referer': url}})
222             return surl
223         # Look for embedded (swf embed) Vimeo player
224         mobj = re.search(
225             r'<embed[^>]+?src="((?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
226         if mobj:
227             return mobj.group(1)
228
229     def _verify_video_password(self, url, video_id, webpage):
230         password = self._downloader.params.get('videopassword', None)
231         if password is None:
232             raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
233         token, vuid = self._extract_xsrft_and_vuid(webpage)
234         data = urlencode_postdata(encode_dict({
235             'password': password,
236             'token': token,
237         }))
238         if url.startswith('http://'):
239             # vimeo only supports https now, but the user can give an http url
240             url = url.replace('http://', 'https://')
241         password_request = sanitized_Request(url + '/password', data)
242         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
243         password_request.add_header('Referer', url)
244         self._set_vimeo_cookie('vuid', vuid)
245         return self._download_webpage(
246             password_request, video_id,
247             'Verifying the password', 'Wrong password')
248
249     def _verify_player_video_password(self, url, video_id):
250         password = self._downloader.params.get('videopassword', None)
251         if password is None:
252             raise ExtractorError('This video is protected by a password, use the --video-password option')
253         data = urlencode_postdata(encode_dict({'password': password}))
254         pass_url = url + '/check-password'
255         password_request = sanitized_Request(pass_url, data)
256         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
257         return self._download_json(
258             password_request, video_id,
259             'Verifying the password',
260             'Wrong password')
261
262     def _real_initialize(self):
263         self._login()
264
265     def _real_extract(self, url):
266         url, data = unsmuggle_url(url, {})
267         headers = std_headers
268         if 'http_headers' in data:
269             headers = headers.copy()
270             headers.update(data['http_headers'])
271         if 'Referer' not in headers:
272             headers['Referer'] = url
273
274         # Extract ID from URL
275         mobj = re.match(self._VALID_URL, url)
276         video_id = mobj.group('id')
277         orig_url = url
278         if mobj.group('pro') or mobj.group('player'):
279             url = 'https://player.vimeo.com/video/' + video_id
280         else:
281             url = 'https://vimeo.com/' + video_id
282
283         # Retrieve video webpage to extract further information
284         request = sanitized_Request(url, None, headers)
285         try:
286             webpage = self._download_webpage(request, video_id)
287         except ExtractorError as ee:
288             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
289                 errmsg = ee.cause.read()
290                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
291                     raise ExtractorError(
292                         'Cannot download embed-only video without embedding '
293                         'URL. Please call youtube-dl with the URL of the page '
294                         'that embeds this video.',
295                         expected=True)
296             raise
297
298         # Now we begin extracting as much information as we can from what we
299         # retrieved. First we extract the information common to all extractors,
300         # and latter we extract those that are Vimeo specific.
301         self.report_extraction(video_id)
302
303         vimeo_config = self._search_regex(
304             r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
305             'vimeo config', default=None)
306         if vimeo_config:
307             seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
308             if seed_status.get('state') == 'failed':
309                 raise ExtractorError(
310                     '%s said: %s' % (self.IE_NAME, seed_status['title']),
311                     expected=True)
312
313         # Extract the config JSON
314         try:
315             try:
316                 config_url = self._html_search_regex(
317                     r' data-config-url="(.+?)"', webpage,
318                     'config URL', default=None)
319                 if not config_url:
320                     # Sometimes new react-based page is served instead of old one that require
321                     # different config URL extraction approach (see
322                     # https://github.com/rg3/youtube-dl/pull/7209)
323                     vimeo_clip_page_config = self._search_regex(
324                         r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
325                         'vimeo clip page config')
326                     config_url = self._parse_json(
327                         vimeo_clip_page_config, video_id)['player']['config_url']
328                 config_json = self._download_webpage(config_url, video_id)
329                 config = json.loads(config_json)
330             except RegexNotFoundError:
331                 # For pro videos or player.vimeo.com urls
332                 # We try to find out to which variable is assigned the config dic
333                 m_variable_name = re.search('(\w)\.video\.id', webpage)
334                 if m_variable_name is not None:
335                     config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
336                 else:
337                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
338                 config = self._search_regex(config_re, webpage, 'info section',
339                                             flags=re.DOTALL)
340                 config = json.loads(config)
341         except Exception as e:
342             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
343                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
344
345             if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
346                 if '_video_password_verified' in data:
347                     raise ExtractorError('video password verification failed!')
348                 self._verify_video_password(url, video_id, webpage)
349                 return self._real_extract(
350                     smuggle_url(url, {'_video_password_verified': 'verified'}))
351             else:
352                 raise ExtractorError('Unable to extract info section',
353                                      cause=e)
354         else:
355             if config.get('view') == 4:
356                 config = self._verify_player_video_password(url, video_id)
357
358         if '>You rented this title.<' in webpage:
359             feature_id = config.get('video', {}).get('vod', {}).get('feature_id')
360             if feature_id and not data.get('force_feature_id', False):
361                 return self.url_result(smuggle_url(
362                     'https://player.vimeo.com/player/%s' % feature_id,
363                     {'force_feature_id': True}), 'Vimeo')
364
365         # Extract title
366         video_title = config["video"]["title"]
367
368         # Extract uploader and uploader_id
369         video_uploader = config["video"]["owner"]["name"]
370         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
371
372         # Extract video thumbnail
373         video_thumbnail = config["video"].get("thumbnail")
374         if video_thumbnail is None:
375             video_thumbs = config["video"].get("thumbs")
376             if video_thumbs and isinstance(video_thumbs, dict):
377                 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
378
379         # Extract video description
380
381         video_description = self._html_search_regex(
382             r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
383             webpage, 'description', default=None)
384         if not video_description:
385             video_description = self._html_search_meta(
386                 'description', webpage, default=None)
387         if not video_description and mobj.group('pro'):
388             orig_webpage = self._download_webpage(
389                 orig_url, video_id,
390                 note='Downloading webpage for description',
391                 fatal=False)
392             if orig_webpage:
393                 video_description = self._html_search_meta(
394                     'description', orig_webpage, default=None)
395         if not video_description and not mobj.group('player'):
396             self._downloader.report_warning('Cannot find video description')
397
398         # Extract video duration
399         video_duration = int_or_none(config["video"].get("duration"))
400
401         # Extract upload date
402         video_upload_date = None
403         mobj = re.search(r'<time[^>]+datetime="([^"]+)"', webpage)
404         if mobj is not None:
405             video_upload_date = unified_strdate(mobj.group(1))
406
407         try:
408             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
409             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
410             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
411         except RegexNotFoundError:
412             # This info is only available in vimeo.com/{id} urls
413             view_count = None
414             like_count = None
415             comment_count = None
416
417         formats = []
418         download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
419             'X-Requested-With': 'XMLHttpRequest'})
420         download_data = self._download_json(download_request, video_id, fatal=False)
421         if download_data:
422             source_file = download_data.get('source_file')
423             if isinstance(source_file, dict):
424                 download_url = source_file.get('download_url')
425                 if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
426                     source_name = source_file.get('public_name', 'Original')
427                     if self._is_valid_url(download_url, video_id, '%s video' % source_name):
428                         ext = source_file.get('extension', determine_ext(download_url)).lower(),
429                         formats.append({
430                             'url': download_url,
431                             'ext': ext,
432                             'width': int_or_none(source_file.get('width')),
433                             'height': int_or_none(source_file.get('height')),
434                             'filesize': parse_filesize(source_file.get('size')),
435                             'format_id': source_name,
436                             'preference': 1,
437                         })
438         config_files = config['video'].get('files') or config['request'].get('files', {})
439         for f in config_files.get('progressive', []):
440             video_url = f.get('url')
441             if not video_url:
442                 continue
443             formats.append({
444                 'url': video_url,
445                 'format_id': 'http-%s' % f.get('quality'),
446                 'width': int_or_none(f.get('width')),
447                 'height': int_or_none(f.get('height')),
448                 'fps': int_or_none(f.get('fps')),
449                 'tbr': int_or_none(f.get('bitrate')),
450             })
451         m3u8_url = config_files.get('hls', {}).get('url')
452         if m3u8_url:
453             formats.extend(self._extract_m3u8_formats(
454                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
455         # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
456         # at the same time without actual units specified. This lead to wrong sorting.
457         self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'format_id'))
458
459         subtitles = {}
460         text_tracks = config['request'].get('text_tracks')
461         if text_tracks:
462             for tt in text_tracks:
463                 subtitles[tt['lang']] = [{
464                     'ext': 'vtt',
465                     'url': 'https://vimeo.com' + tt['url'],
466                 }]
467
468         return {
469             'id': video_id,
470             'uploader': video_uploader,
471             'uploader_id': video_uploader_id,
472             'upload_date': video_upload_date,
473             'title': video_title,
474             'thumbnail': video_thumbnail,
475             'description': video_description,
476             'duration': video_duration,
477             'formats': formats,
478             'webpage_url': url,
479             'view_count': view_count,
480             'like_count': like_count,
481             'comment_count': comment_count,
482             'subtitles': subtitles,
483         }
484
485
486 class VimeoChannelIE(VimeoBaseInfoExtractor):
487     IE_NAME = 'vimeo:channel'
488     _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
489     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
490     _TITLE = None
491     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
492     _TESTS = [{
493         'url': 'https://vimeo.com/channels/tributes',
494         'info_dict': {
495             'id': 'tributes',
496             'title': 'Vimeo Tributes',
497         },
498         'playlist_mincount': 25,
499     }]
500
501     def _page_url(self, base_url, pagenum):
502         return '%s/videos/page:%d/' % (base_url, pagenum)
503
504     def _extract_list_title(self, webpage):
505         return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
506
507     def _login_list_password(self, page_url, list_id, webpage):
508         login_form = self._search_regex(
509             r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
510             webpage, 'login form', default=None)
511         if not login_form:
512             return webpage
513
514         password = self._downloader.params.get('videopassword', None)
515         if password is None:
516             raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
517         fields = self._hidden_inputs(login_form)
518         token, vuid = self._extract_xsrft_and_vuid(webpage)
519         fields['token'] = token
520         fields['password'] = password
521         post = urlencode_postdata(encode_dict(fields))
522         password_path = self._search_regex(
523             r'action="([^"]+)"', login_form, 'password URL')
524         password_url = compat_urlparse.urljoin(page_url, password_path)
525         password_request = sanitized_Request(password_url, post)
526         password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
527         self._set_vimeo_cookie('vuid', vuid)
528         self._set_vimeo_cookie('xsrft', token)
529
530         return self._download_webpage(
531             password_request, list_id,
532             'Verifying the password', 'Wrong password')
533
534     def _title_and_entries(self, list_id, base_url):
535         for pagenum in itertools.count(1):
536             page_url = self._page_url(base_url, pagenum)
537             webpage = self._download_webpage(
538                 page_url, list_id,
539                 'Downloading page %s' % pagenum)
540
541             if pagenum == 1:
542                 webpage = self._login_list_password(page_url, list_id, webpage)
543                 yield self._extract_list_title(webpage)
544
545             for video_id in re.findall(r'id="clip_(\d+?)"', webpage):
546                 yield self.url_result('https://vimeo.com/%s' % video_id, 'Vimeo')
547
548             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
549                 break
550
551     def _extract_videos(self, list_id, base_url):
552         title_and_entries = self._title_and_entries(list_id, base_url)
553         list_title = next(title_and_entries)
554         return self.playlist_result(title_and_entries, list_id, list_title)
555
556     def _real_extract(self, url):
557         mobj = re.match(self._VALID_URL, url)
558         channel_id = mobj.group('id')
559         return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
560
561
562 class VimeoUserIE(VimeoChannelIE):
563     IE_NAME = 'vimeo:user'
564     _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
565     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
566     _TESTS = [{
567         'url': 'https://vimeo.com/nkistudio/videos',
568         'info_dict': {
569             'title': 'Nki',
570             'id': 'nkistudio',
571         },
572         'playlist_mincount': 66,
573     }]
574
575     def _real_extract(self, url):
576         mobj = re.match(self._VALID_URL, url)
577         name = mobj.group('name')
578         return self._extract_videos(name, 'https://vimeo.com/%s' % name)
579
580
581 class VimeoAlbumIE(VimeoChannelIE):
582     IE_NAME = 'vimeo:album'
583     _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)'
584     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
585     _TESTS = [{
586         'url': 'https://vimeo.com/album/2632481',
587         'info_dict': {
588             'id': '2632481',
589             'title': 'Staff Favorites: November 2013',
590         },
591         'playlist_mincount': 13,
592     }, {
593         'note': 'Password-protected album',
594         'url': 'https://vimeo.com/album/3253534',
595         'info_dict': {
596             'title': 'test',
597             'id': '3253534',
598         },
599         'playlist_count': 1,
600         'params': {
601             'videopassword': 'youtube-dl',
602         }
603     }]
604
605     def _page_url(self, base_url, pagenum):
606         return '%s/page:%d/' % (base_url, pagenum)
607
608     def _real_extract(self, url):
609         album_id = self._match_id(url)
610         return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
611
612
613 class VimeoGroupsIE(VimeoAlbumIE):
614     IE_NAME = 'vimeo:group'
615     _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
616     _TESTS = [{
617         'url': 'https://vimeo.com/groups/rolexawards',
618         'info_dict': {
619             'id': 'rolexawards',
620             'title': 'Rolex Awards for Enterprise',
621         },
622         'playlist_mincount': 73,
623     }]
624
625     def _extract_list_title(self, webpage):
626         return self._og_search_title(webpage)
627
628     def _real_extract(self, url):
629         mobj = re.match(self._VALID_URL, url)
630         name = mobj.group('name')
631         return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
632
633
634 class VimeoReviewIE(InfoExtractor):
635     IE_NAME = 'vimeo:review'
636     IE_DESC = 'Review pages on vimeo'
637     _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
638     _TESTS = [{
639         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
640         'md5': 'c507a72f780cacc12b2248bb4006d253',
641         'info_dict': {
642             'id': '75524534',
643             'ext': 'mp4',
644             'title': "DICK HARDWICK 'Comedian'",
645             'uploader': 'Richard Hardwick',
646         }
647     }, {
648         'note': 'video player needs Referer',
649         'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
650         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
651         'info_dict': {
652             'id': '91613211',
653             'ext': 'mp4',
654             'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
655             'uploader': 'DevWeek Events',
656             'duration': 2773,
657             'thumbnail': 're:^https?://.*\.jpg$',
658         }
659     }]
660
661     def _real_extract(self, url):
662         mobj = re.match(self._VALID_URL, url)
663         video_id = mobj.group('id')
664         player_url = 'https://player.vimeo.com/player/' + video_id
665         return self.url_result(player_url, 'Vimeo', video_id)
666
667
668 class VimeoWatchLaterIE(VimeoChannelIE):
669     IE_NAME = 'vimeo:watchlater'
670     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
671     _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
672     _TITLE = 'Watch Later'
673     _LOGIN_REQUIRED = True
674     _TESTS = [{
675         'url': 'https://vimeo.com/watchlater',
676         'only_matching': True,
677     }]
678
679     def _real_initialize(self):
680         self._login()
681
682     def _page_url(self, base_url, pagenum):
683         url = '%s/page:%d/' % (base_url, pagenum)
684         request = sanitized_Request(url)
685         # Set the header to get a partial html page with the ids,
686         # the normal page doesn't contain them.
687         request.add_header('X-Requested-With', 'XMLHttpRequest')
688         return request
689
690     def _real_extract(self, url):
691         return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
692
693
694 class VimeoLikesIE(InfoExtractor):
695     _VALID_URL = r'https://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
696     IE_NAME = 'vimeo:likes'
697     IE_DESC = 'Vimeo user likes'
698     _TEST = {
699         'url': 'https://vimeo.com/user755559/likes/',
700         'playlist_mincount': 293,
701         "info_dict": {
702             'id': 'user755559_likes',
703             "description": "See all the videos urza likes",
704             "title": 'Videos urza likes',
705         },
706     }
707
708     def _real_extract(self, url):
709         user_id = self._match_id(url)
710         webpage = self._download_webpage(url, user_id)
711         page_count = self._int(
712             self._search_regex(
713                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
714                     .*?</a></li>\s*<li\s+class="pagination_next">
715                 ''', webpage, 'page count'),
716             'page count', fatal=True)
717         PAGE_SIZE = 12
718         title = self._html_search_regex(
719             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
720         description = self._html_search_meta('description', webpage)
721
722         def _get_page(idx):
723             page_url = 'https://vimeo.com/user%s/likes/page:%d/sort:date' % (
724                 user_id, idx + 1)
725             webpage = self._download_webpage(
726                 page_url, user_id,
727                 note='Downloading page %d/%d' % (idx + 1, page_count))
728             video_list = self._search_regex(
729                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
730                 webpage, 'video content')
731             paths = re.findall(
732                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
733             for path in paths:
734                 yield {
735                     '_type': 'url',
736                     'url': compat_urlparse.urljoin(page_url, path),
737                 }
738
739         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
740
741         return {
742             '_type': 'playlist',
743             'id': 'user%s_likes' % user_id,
744             'title': title,
745             'description': description,
746             'entries': pl,
747         }