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