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