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