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