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