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