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