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