]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/vimeo.py
[vimeo] fix album 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     qualities,
27     RegexNotFoundError,
28     sanitized_Request,
29     smuggle_url,
30     std_headers,
31     try_get,
32     unified_timestamp,
33     unsmuggle_url,
34     urlencode_postdata,
35     unescapeHTML,
36 )
37
38
39 class VimeoBaseInfoExtractor(InfoExtractor):
40     _NETRC_MACHINE = 'vimeo'
41     _LOGIN_REQUIRED = False
42     _LOGIN_URL = 'https://vimeo.com/log_in'
43
44     def _login(self):
45         username, password = self._get_login_info()
46         if username is None:
47             if self._LOGIN_REQUIRED:
48                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
49             return
50         webpage = self._download_webpage(
51             self._LOGIN_URL, None, 'Downloading login page')
52         token, vuid = self._extract_xsrft_and_vuid(webpage)
53         data = {
54             'action': 'login',
55             'email': username,
56             'password': password,
57             'service': 'vimeo',
58             'token': token,
59         }
60         self._set_vimeo_cookie('vuid', vuid)
61         try:
62             self._download_webpage(
63                 self._LOGIN_URL, None, 'Logging in',
64                 data=urlencode_postdata(data), headers={
65                     'Content-Type': 'application/x-www-form-urlencoded',
66                     'Referer': self._LOGIN_URL,
67                 })
68         except ExtractorError as e:
69             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 418:
70                 raise ExtractorError(
71                     'Unable to log in: bad username or password',
72                     expected=True)
73             raise ExtractorError('Unable to log in')
74
75     def _verify_video_password(self, url, video_id, webpage):
76         password = self._downloader.params.get('videopassword')
77         if password is None:
78             raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
79         token, vuid = self._extract_xsrft_and_vuid(webpage)
80         data = urlencode_postdata({
81             'password': password,
82             'token': token,
83         })
84         if url.startswith('http://'):
85             # vimeo only supports https now, but the user can give an http url
86             url = url.replace('http://', 'https://')
87         password_request = sanitized_Request(url + '/password', data)
88         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
89         password_request.add_header('Referer', url)
90         self._set_vimeo_cookie('vuid', vuid)
91         return self._download_webpage(
92             password_request, video_id,
93             'Verifying the password', 'Wrong password')
94
95     def _extract_xsrft_and_vuid(self, webpage):
96         xsrft = self._search_regex(
97             r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
98             webpage, 'login token', group='xsrft')
99         vuid = self._search_regex(
100             r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
101             webpage, 'vuid', group='vuid')
102         return xsrft, vuid
103
104     def _extract_vimeo_config(self, webpage, video_id, *args, **kwargs):
105         vimeo_config = self._search_regex(
106             r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));',
107             webpage, 'vimeo config', *args, **compat_kwargs(kwargs))
108         if vimeo_config:
109             return self._parse_json(vimeo_config, video_id)
110
111     def _set_vimeo_cookie(self, name, value):
112         self._set_cookie('vimeo.com', name, value)
113
114     def _vimeo_sort_formats(self, formats):
115         # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
116         # at the same time without actual units specified. This lead to wrong sorting.
117         self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
118
119     def _parse_config(self, config, video_id):
120         video_data = config['video']
121         video_title = video_data['title']
122         live_event = video_data.get('live_event') or {}
123         is_live = live_event.get('status') == 'started'
124
125         formats = []
126         config_files = video_data.get('files') or config['request'].get('files', {})
127         for f in config_files.get('progressive', []):
128             video_url = f.get('url')
129             if not video_url:
130                 continue
131             formats.append({
132                 'url': video_url,
133                 'format_id': 'http-%s' % f.get('quality'),
134                 'width': int_or_none(f.get('width')),
135                 'height': int_or_none(f.get('height')),
136                 'fps': int_or_none(f.get('fps')),
137                 'tbr': int_or_none(f.get('bitrate')),
138             })
139
140         # TODO: fix handling of 308 status code returned for live archive manifest requests
141         for files_type in ('hls', 'dash'):
142             for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
143                 manifest_url = cdn_data.get('url')
144                 if not manifest_url:
145                     continue
146                 format_id = '%s-%s' % (files_type, cdn_name)
147                 if files_type == 'hls':
148                     formats.extend(self._extract_m3u8_formats(
149                         manifest_url, video_id, 'mp4',
150                         'm3u8' if is_live else 'm3u8_native', m3u8_id=format_id,
151                         note='Downloading %s m3u8 information' % cdn_name,
152                         fatal=False))
153                 elif files_type == 'dash':
154                     mpd_pattern = r'/%s/(?:sep/)?video/' % video_id
155                     mpd_manifest_urls = []
156                     if re.search(mpd_pattern, manifest_url):
157                         for suffix, repl in (('', 'video'), ('_sep', 'sep/video')):
158                             mpd_manifest_urls.append((format_id + suffix, re.sub(
159                                 mpd_pattern, '/%s/%s/' % (video_id, repl), manifest_url)))
160                     else:
161                         mpd_manifest_urls = [(format_id, manifest_url)]
162                     for f_id, m_url in mpd_manifest_urls:
163                         if 'json=1' in m_url:
164                             real_m_url = (self._download_json(m_url, video_id, fatal=False) or {}).get('url')
165                             if real_m_url:
166                                 m_url = real_m_url
167                         mpd_formats = self._extract_mpd_formats(
168                             m_url.replace('/master.json', '/master.mpd'), video_id, f_id,
169                             'Downloading %s MPD information' % cdn_name,
170                             fatal=False)
171                         for f in mpd_formats:
172                             if f.get('vcodec') == 'none':
173                                 f['preference'] = -50
174                             elif f.get('acodec') == 'none':
175                                 f['preference'] = -40
176                         formats.extend(mpd_formats)
177
178         live_archive = live_event.get('archive') or {}
179         live_archive_source_url = live_archive.get('source_url')
180         if live_archive_source_url and live_archive.get('status') == 'done':
181             formats.append({
182                 'format_id': 'live-archive-source',
183                 'url': live_archive_source_url,
184                 'preference': 1,
185             })
186
187         subtitles = {}
188         text_tracks = config['request'].get('text_tracks')
189         if text_tracks:
190             for tt in text_tracks:
191                 subtitles[tt['lang']] = [{
192                     'ext': 'vtt',
193                     'url': 'https://vimeo.com' + tt['url'],
194                 }]
195
196         thumbnails = []
197         if not is_live:
198             for key, thumb in video_data.get('thumbs', {}).items():
199                 thumbnails.append({
200                     'id': key,
201                     'width': int_or_none(key),
202                     'url': thumb,
203                 })
204             thumbnail = video_data.get('thumbnail')
205             if thumbnail:
206                 thumbnails.append({
207                     'url': thumbnail,
208                 })
209
210         owner = video_data.get('owner') or {}
211         video_uploader_url = owner.get('url')
212
213         return {
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             'id': video_id,
734             'formats': formats,
735             'timestamp': unified_timestamp(timestamp),
736             'description': video_description,
737             'webpage_url': url,
738             'view_count': view_count,
739             'like_count': like_count,
740             'comment_count': comment_count,
741             'license': cc_license,
742             'channel_id': channel_id,
743             'channel_url': channel_url,
744         }
745
746         info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
747
748         return info_dict
749
750
751 class VimeoOndemandIE(VimeoBaseInfoExtractor):
752     IE_NAME = 'vimeo:ondemand'
753     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
754     _TESTS = [{
755         # ondemand video not available via https://vimeo.com/id
756         'url': 'https://vimeo.com/ondemand/20704',
757         'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
758         'info_dict': {
759             'id': '105442900',
760             'ext': 'mp4',
761             'title': 'המעבדה - במאי יותם פלדמן',
762             'uploader': 'גם סרטים',
763             'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
764             'uploader_id': 'gumfilms',
765         },
766         'params': {
767             'format': 'best[protocol=https]',
768         },
769     }, {
770         # requires Referer to be passed along with og:video:url
771         'url': 'https://vimeo.com/ondemand/36938/126682985',
772         'info_dict': {
773             'id': '126682985',
774             'ext': 'mp4',
775             'title': 'Rävlock, rätt läte på rätt plats',
776             'uploader': 'Lindroth & Norin',
777             'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
778             'uploader_id': 'user14430847',
779         },
780         'params': {
781             'skip_download': True,
782         },
783     }, {
784         'url': 'https://vimeo.com/ondemand/nazmaalik',
785         'only_matching': True,
786     }, {
787         'url': 'https://vimeo.com/ondemand/141692381',
788         'only_matching': True,
789     }, {
790         'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
791         'only_matching': True,
792     }]
793
794     def _real_extract(self, url):
795         video_id = self._match_id(url)
796         webpage = self._download_webpage(url, video_id)
797         return self.url_result(
798             # Some videos require Referer to be passed along with og:video:url
799             # similarly to generic vimeo embeds (e.g.
800             # https://vimeo.com/ondemand/36938/126682985).
801             VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
802             VimeoIE.ie_key())
803
804
805 class VimeoChannelIE(VimeoBaseInfoExtractor):
806     IE_NAME = 'vimeo:channel'
807     _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
808     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
809     _TITLE = None
810     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
811     _TESTS = [{
812         'url': 'https://vimeo.com/channels/tributes',
813         'info_dict': {
814             'id': 'tributes',
815             'title': 'Vimeo Tributes',
816         },
817         'playlist_mincount': 25,
818     }]
819
820     def _page_url(self, base_url, pagenum):
821         return '%s/videos/page:%d/' % (base_url, pagenum)
822
823     def _extract_list_title(self, webpage):
824         return self._TITLE or self._html_search_regex(
825             self._TITLE_RE, webpage, 'list title', fatal=False)
826
827     def _login_list_password(self, page_url, list_id, webpage):
828         login_form = self._search_regex(
829             r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
830             webpage, 'login form', default=None)
831         if not login_form:
832             return webpage
833
834         password = self._downloader.params.get('videopassword')
835         if password is None:
836             raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
837         fields = self._hidden_inputs(login_form)
838         token, vuid = self._extract_xsrft_and_vuid(webpage)
839         fields['token'] = token
840         fields['password'] = password
841         post = urlencode_postdata(fields)
842         password_path = self._search_regex(
843             r'action="([^"]+)"', login_form, 'password URL')
844         password_url = compat_urlparse.urljoin(page_url, password_path)
845         password_request = sanitized_Request(password_url, post)
846         password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
847         self._set_vimeo_cookie('vuid', vuid)
848         self._set_vimeo_cookie('xsrft', token)
849
850         return self._download_webpage(
851             password_request, list_id,
852             'Verifying the password', 'Wrong password')
853
854     def _title_and_entries(self, list_id, base_url):
855         for pagenum in itertools.count(1):
856             page_url = self._page_url(base_url, pagenum)
857             webpage = self._download_webpage(
858                 page_url, list_id,
859                 'Downloading page %s' % pagenum)
860
861             if pagenum == 1:
862                 webpage = self._login_list_password(page_url, list_id, webpage)
863                 yield self._extract_list_title(webpage)
864
865             # Try extracting href first since not all videos are available via
866             # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
867             clips = re.findall(
868                 r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
869             if clips:
870                 for video_id, video_url, video_title in clips:
871                     yield self.url_result(
872                         compat_urlparse.urljoin(base_url, video_url),
873                         VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
874             # More relaxed fallback
875             else:
876                 for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
877                     yield self.url_result(
878                         'https://vimeo.com/%s' % video_id,
879                         VimeoIE.ie_key(), video_id=video_id)
880
881             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
882                 break
883
884     def _extract_videos(self, list_id, base_url):
885         title_and_entries = self._title_and_entries(list_id, base_url)
886         list_title = next(title_and_entries)
887         return self.playlist_result(title_and_entries, list_id, list_title)
888
889     def _real_extract(self, url):
890         mobj = re.match(self._VALID_URL, url)
891         channel_id = mobj.group('id')
892         return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
893
894
895 class VimeoUserIE(VimeoChannelIE):
896     IE_NAME = 'vimeo:user'
897     _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
898     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
899     _TESTS = [{
900         'url': 'https://vimeo.com/nkistudio/videos',
901         'info_dict': {
902             'title': 'Nki',
903             'id': 'nkistudio',
904         },
905         'playlist_mincount': 66,
906     }]
907
908     def _real_extract(self, url):
909         mobj = re.match(self._VALID_URL, url)
910         name = mobj.group('name')
911         return self._extract_videos(name, 'https://vimeo.com/%s' % name)
912
913
914 class VimeoAlbumIE(VimeoChannelIE):
915     IE_NAME = 'vimeo:album'
916     _VALID_URL = r'https://vimeo\.com/(?:album|showcase)/(?P<id>\d+)(?:$|[?#]|/(?!video))'
917     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
918     _TESTS = [{
919         'url': 'https://vimeo.com/album/2632481',
920         'info_dict': {
921             'id': '2632481',
922             'title': 'Staff Favorites: November 2013',
923         },
924         'playlist_mincount': 13,
925     }, {
926         'note': 'Password-protected album',
927         'url': 'https://vimeo.com/album/3253534',
928         'info_dict': {
929             'title': 'test',
930             'id': '3253534',
931         },
932         'playlist_count': 1,
933         'params': {
934             'videopassword': 'youtube-dl',
935         }
936     }]
937     _PAGE_SIZE = 100
938
939     def _fetch_page(self, album_id, authorizaion, hashed_pass, page):
940         api_page = page + 1
941         query = {
942             'fields': 'link',
943             'page': api_page,
944             'per_page': self._PAGE_SIZE,
945         }
946         if hashed_pass:
947             query['_hashed_pass'] = hashed_pass
948         videos = self._download_json(
949             'https://api.vimeo.com/albums/%s/videos' % album_id,
950             album_id, 'Downloading page %d' % api_page, query=query, headers={
951                 'Authorization': 'jwt ' + authorizaion,
952             })['data']
953         for video in videos:
954             link = video.get('link')
955             if not link:
956                 continue
957             yield self.url_result(link, VimeoIE.ie_key(), VimeoIE._match_id(link))
958
959     def _real_extract(self, url):
960         album_id = self._match_id(url)
961         webpage = self._download_webpage(url, album_id)
962         webpage = self._login_list_password(url, album_id, webpage)
963         api_config = self._extract_vimeo_config(webpage, album_id)['api']
964         entries = OnDemandPagedList(functools.partial(
965             self._fetch_page, album_id, api_config['jwt'],
966             api_config.get('hashed_pass')), self._PAGE_SIZE)
967         return self.playlist_result(entries, album_id, self._html_search_regex(
968             r'<title>\s*(.+?)(?:\s+on Vimeo)?</title>', webpage, 'title', fatal=False))
969
970
971 class VimeoGroupsIE(VimeoAlbumIE):
972     IE_NAME = 'vimeo:group'
973     _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
974     _TESTS = [{
975         'url': 'https://vimeo.com/groups/rolexawards',
976         'info_dict': {
977             'id': 'rolexawards',
978             'title': 'Rolex Awards for Enterprise',
979         },
980         'playlist_mincount': 73,
981     }]
982
983     def _extract_list_title(self, webpage):
984         return self._og_search_title(webpage, fatal=False)
985
986     def _real_extract(self, url):
987         mobj = re.match(self._VALID_URL, url)
988         name = mobj.group('name')
989         return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
990
991
992 class VimeoReviewIE(VimeoBaseInfoExtractor):
993     IE_NAME = 'vimeo:review'
994     IE_DESC = 'Review pages on vimeo'
995     _VALID_URL = r'(?P<url>https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)/[0-9a-f]{10})'
996     _TESTS = [{
997         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
998         'md5': 'c507a72f780cacc12b2248bb4006d253',
999         'info_dict': {
1000             'id': '75524534',
1001             'ext': 'mp4',
1002             'title': "DICK HARDWICK 'Comedian'",
1003             'uploader': 'Richard Hardwick',
1004             'uploader_id': 'user21297594',
1005         }
1006     }, {
1007         'note': 'video player needs Referer',
1008         'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
1009         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
1010         'info_dict': {
1011             'id': '91613211',
1012             'ext': 'mp4',
1013             'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
1014             'uploader': 'DevWeek Events',
1015             'duration': 2773,
1016             'thumbnail': r're:^https?://.*\.jpg$',
1017             'uploader_id': 'user22258446',
1018         }
1019     }, {
1020         'note': 'Password protected',
1021         'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
1022         'info_dict': {
1023             'id': '138823582',
1024             'ext': 'mp4',
1025             'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
1026             'uploader': 'TMB',
1027             'uploader_id': 'user37284429',
1028         },
1029         'params': {
1030             'videopassword': 'holygrail',
1031         },
1032         'skip': 'video gone',
1033     }]
1034
1035     def _real_initialize(self):
1036         self._login()
1037
1038     def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
1039         webpage = self._download_webpage(webpage_url, video_id)
1040         config_url = self._html_search_regex(
1041             r'data-config-url=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
1042             'config URL', default=None, group='url')
1043         if not config_url:
1044             data = self._parse_json(self._search_regex(
1045                 r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
1046                 default=NO_DEFAULT if video_password_verified else '{}'), video_id)
1047             config = data.get('vimeo_esi', {}).get('config', {})
1048             config_url = config.get('configUrl') or try_get(config, lambda x: x['clipData']['configUrl'])
1049         if config_url is None:
1050             self._verify_video_password(webpage_url, video_id, webpage)
1051             config_url = self._get_config_url(
1052                 webpage_url, video_id, video_password_verified=True)
1053         return config_url
1054
1055     def _real_extract(self, url):
1056         page_url, video_id = re.match(self._VALID_URL, url).groups()
1057         config_url = self._get_config_url(url, video_id)
1058         config = self._download_json(config_url, video_id)
1059         info_dict = self._parse_config(config, video_id)
1060         source_format = self._extract_original_format(page_url, video_id)
1061         if source_format:
1062             info_dict['formats'].append(source_format)
1063         self._vimeo_sort_formats(info_dict['formats'])
1064         info_dict['id'] = video_id
1065         return info_dict
1066
1067
1068 class VimeoWatchLaterIE(VimeoChannelIE):
1069     IE_NAME = 'vimeo:watchlater'
1070     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
1071     _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
1072     _TITLE = 'Watch Later'
1073     _LOGIN_REQUIRED = True
1074     _TESTS = [{
1075         'url': 'https://vimeo.com/watchlater',
1076         'only_matching': True,
1077     }]
1078
1079     def _real_initialize(self):
1080         self._login()
1081
1082     def _page_url(self, base_url, pagenum):
1083         url = '%s/page:%d/' % (base_url, pagenum)
1084         request = sanitized_Request(url)
1085         # Set the header to get a partial html page with the ids,
1086         # the normal page doesn't contain them.
1087         request.add_header('X-Requested-With', 'XMLHttpRequest')
1088         return request
1089
1090     def _real_extract(self, url):
1091         return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
1092
1093
1094 class VimeoLikesIE(VimeoChannelIE):
1095     _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
1096     IE_NAME = 'vimeo:likes'
1097     IE_DESC = 'Vimeo user likes'
1098     _TESTS = [{
1099         'url': 'https://vimeo.com/user755559/likes/',
1100         'playlist_mincount': 293,
1101         'info_dict': {
1102             'id': 'user755559',
1103             'title': 'urza’s Likes',
1104         },
1105     }, {
1106         'url': 'https://vimeo.com/stormlapse/likes',
1107         'only_matching': True,
1108     }]
1109
1110     def _page_url(self, base_url, pagenum):
1111         return '%s/page:%d/' % (base_url, pagenum)
1112
1113     def _real_extract(self, url):
1114         user_id = self._match_id(url)
1115         return self._extract_videos(user_id, 'https://vimeo.com/%s/likes' % user_id)
1116
1117
1118 class VHXEmbedIE(InfoExtractor):
1119     IE_NAME = 'vhx:embed'
1120     _VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
1121
1122     def _call_api(self, video_id, access_token, path='', query=None):
1123         return self._download_json(
1124             'https://api.vhx.tv/videos/' + video_id + path, video_id, headers={
1125                 'Authorization': 'Bearer ' + access_token,
1126             }, query=query)
1127
1128     def _real_extract(self, url):
1129         video_id = self._match_id(url)
1130         webpage = self._download_webpage(url, video_id)
1131         credentials = self._parse_json(self._search_regex(
1132             r'(?s)credentials\s*:\s*({.+?}),', webpage,
1133             'config'), video_id, js_to_json)
1134         access_token = credentials['access_token']
1135
1136         query = {}
1137         for k, v in credentials.items():
1138             if k in ('authorization', 'authUserToken', 'ticket') and v and v != 'undefined':
1139                 if k == 'authUserToken':
1140                     query['auth_user_token'] = v
1141                 else:
1142                     query[k] = v
1143         files = self._call_api(video_id, access_token, '/files', query)
1144
1145         formats = []
1146         for f in files:
1147             href = try_get(f, lambda x: x['_links']['source']['href'])
1148             if not href:
1149                 continue
1150             method = f.get('method')
1151             if method == 'hls':
1152                 formats.extend(self._extract_m3u8_formats(
1153                     href, video_id, 'mp4', 'm3u8_native',
1154                     m3u8_id='hls', fatal=False))
1155             elif method == 'dash':
1156                 formats.extend(self._extract_mpd_formats(
1157                     href, video_id, mpd_id='dash', fatal=False))
1158             else:
1159                 fmt = {
1160                     'filesize': int_or_none(try_get(f, lambda x: x['size']['bytes'])),
1161                     'format_id': 'http',
1162                     'preference': 1,
1163                     'url': href,
1164                     'vcodec': f.get('codec'),
1165                 }
1166                 quality = f.get('quality')
1167                 if quality:
1168                     fmt.update({
1169                         'format_id': 'http-' + quality,
1170                         'height': int_or_none(self._search_regex(r'(\d+)p', quality, 'height', default=None)),
1171                     })
1172                 formats.append(fmt)
1173         self._sort_formats(formats)
1174
1175         video_data = self._call_api(video_id, access_token)
1176         title = video_data.get('title') or video_data['name']
1177
1178         subtitles = {}
1179         for subtitle in try_get(video_data, lambda x: x['tracks']['subtitles'], list) or []:
1180             lang = subtitle.get('srclang') or subtitle.get('label')
1181             for _link in subtitle.get('_links', {}).values():
1182                 href = _link.get('href')
1183                 if not href:
1184                     continue
1185                 subtitles.setdefault(lang, []).append({
1186                     'url': href,
1187                 })
1188
1189         q = qualities(['small', 'medium', 'large', 'source'])
1190         thumbnails = []
1191         for thumbnail_id, thumbnail_url in video_data.get('thumbnail', {}).items():
1192             thumbnails.append({
1193                 'id': thumbnail_id,
1194                 'url': thumbnail_url,
1195                 'preference': q(thumbnail_id),
1196             })
1197
1198         return {
1199             'id': video_id,
1200             'title': title,
1201             'description': video_data.get('description'),
1202             'duration': int_or_none(try_get(video_data, lambda x: x['duration']['seconds'])),
1203             'formats': formats,
1204             'subtitles': subtitles,
1205             'thumbnails': thumbnails,
1206             'timestamp': unified_timestamp(video_data.get('created_at')),
1207             'view_count': int_or_none(video_data.get('plays_count')),
1208         }