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