]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/vimeo.py
[vimeo] Fix video password verification for videos protected by Referer HTTP header
[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         # https://gettingthingsdone.com/workflowmap/
439         # vimeo embed with check-password page protected by Referer header
440     ]
441
442     @staticmethod
443     def _smuggle_referrer(url, referrer_url):
444         return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
445
446     @staticmethod
447     def _extract_urls(url, webpage):
448         urls = []
449         # Look for embedded (iframe) Vimeo player
450         for mobj in re.finditer(
451                 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/\d+.*?)\1',
452                 webpage):
453             urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
454         PLAIN_EMBED_RE = (
455             # Look for embedded (swf embed) Vimeo player
456             r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
457             # Look more for non-standard embedded Vimeo player
458             r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
459         )
460         for embed_re in PLAIN_EMBED_RE:
461             for mobj in re.finditer(embed_re, webpage):
462                 urls.append(mobj.group('url'))
463         return urls
464
465     @staticmethod
466     def _extract_url(url, webpage):
467         urls = VimeoIE._extract_urls(url, webpage)
468         return urls[0] if urls else None
469
470     def _verify_player_video_password(self, url, video_id, headers):
471         password = self._downloader.params.get('videopassword')
472         if password is None:
473             raise ExtractorError('This video is protected by a password, use the --video-password option')
474         data = urlencode_postdata({
475             'password': base64.b64encode(password.encode()),
476         })
477         headers = merge_dicts(headers, {
478             'Content-Type': 'application/x-www-form-urlencoded',
479         })
480         checked = self._download_json(
481             url + '/check-password', video_id,
482             'Verifying the password', data=data, headers=headers)
483         if checked is False:
484             raise ExtractorError('Wrong video password', expected=True)
485         return checked
486
487     def _real_initialize(self):
488         self._login()
489
490     def _real_extract(self, url):
491         url, data = unsmuggle_url(url, {})
492         headers = std_headers.copy()
493         if 'http_headers' in data:
494             headers.update(data['http_headers'])
495         if 'Referer' not in headers:
496             headers['Referer'] = url
497
498         channel_id = self._search_regex(
499             r'vimeo\.com/channels/([^/]+)', url, 'channel id', default=None)
500
501         # Extract ID from URL
502         mobj = re.match(self._VALID_URL, url)
503         video_id = mobj.group('id')
504         orig_url = url
505         if mobj.group('pro') or mobj.group('player'):
506             url = 'https://player.vimeo.com/video/' + video_id
507         elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
508             url = 'https://vimeo.com/' + video_id
509
510         # Retrieve video webpage to extract further information
511         request = sanitized_Request(url, headers=headers)
512         try:
513             webpage, urlh = self._download_webpage_handle(request, video_id)
514             redirect_url = compat_str(urlh.geturl())
515             # Some URLs redirect to ondemand can't be extracted with
516             # this extractor right away thus should be passed through
517             # ondemand extractor (e.g. https://vimeo.com/73445910)
518             if VimeoOndemandIE.suitable(redirect_url):
519                 return self.url_result(redirect_url, VimeoOndemandIE.ie_key())
520         except ExtractorError as ee:
521             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
522                 errmsg = ee.cause.read()
523                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
524                     raise ExtractorError(
525                         'Cannot download embed-only video without embedding '
526                         'URL. Please call youtube-dl with the URL of the page '
527                         'that embeds this video.',
528                         expected=True)
529             raise
530
531         # Now we begin extracting as much information as we can from what we
532         # retrieved. First we extract the information common to all extractors,
533         # and latter we extract those that are Vimeo specific.
534         self.report_extraction(video_id)
535
536         vimeo_config = self._search_regex(
537             r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
538             'vimeo config', default=None)
539         if vimeo_config:
540             seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
541             if seed_status.get('state') == 'failed':
542                 raise ExtractorError(
543                     '%s said: %s' % (self.IE_NAME, seed_status['title']),
544                     expected=True)
545
546         cc_license = None
547         timestamp = None
548
549         # Extract the config JSON
550         try:
551             try:
552                 config_url = self._html_search_regex(
553                     r' data-config-url="(.+?)"', webpage,
554                     'config URL', default=None)
555                 if not config_url:
556                     # Sometimes new react-based page is served instead of old one that require
557                     # different config URL extraction approach (see
558                     # https://github.com/rg3/youtube-dl/pull/7209)
559                     vimeo_clip_page_config = self._search_regex(
560                         r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
561                         'vimeo clip page config')
562                     page_config = self._parse_json(vimeo_clip_page_config, video_id)
563                     config_url = page_config['player']['config_url']
564                     cc_license = page_config.get('cc_license')
565                     timestamp = try_get(
566                         page_config, lambda x: x['clip']['uploaded_on'],
567                         compat_str)
568                 config_json = self._download_webpage(config_url, video_id)
569                 config = json.loads(config_json)
570             except RegexNotFoundError:
571                 # For pro videos or player.vimeo.com urls
572                 # We try to find out to which variable is assigned the config dic
573                 m_variable_name = re.search(r'(\w)\.video\.id', webpage)
574                 if m_variable_name is not None:
575                     config_re = [r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))]
576                 else:
577                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
578                 config_re.append(r'\bvar\s+r\s*=\s*({.+?})\s*;')
579                 config_re.append(r'\bconfig\s*=\s*({.+?})\s*;')
580                 config = self._search_regex(config_re, webpage, 'info section',
581                                             flags=re.DOTALL)
582                 config = json.loads(config)
583         except Exception as e:
584             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
585                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
586
587             if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
588                 if '_video_password_verified' in data:
589                     raise ExtractorError('video password verification failed!')
590                 self._verify_video_password(redirect_url, video_id, webpage)
591                 return self._real_extract(
592                     smuggle_url(redirect_url, {'_video_password_verified': 'verified'}))
593             else:
594                 raise ExtractorError('Unable to extract info section',
595                                      cause=e)
596         else:
597             if config.get('view') == 4:
598                 config = self._verify_player_video_password(redirect_url, video_id, headers)
599
600         vod = config.get('video', {}).get('vod', {})
601
602         def is_rented():
603             if '>You rented this title.<' in webpage:
604                 return True
605             if config.get('user', {}).get('purchased'):
606                 return True
607             for purchase_option in vod.get('purchase_options', []):
608                 if purchase_option.get('purchased'):
609                     return True
610                 label = purchase_option.get('label_string')
611                 if label and (label.startswith('You rented this') or label.endswith(' remaining')):
612                     return True
613             return False
614
615         if is_rented() and vod.get('is_trailer'):
616             feature_id = vod.get('feature_id')
617             if feature_id and not data.get('force_feature_id', False):
618                 return self.url_result(smuggle_url(
619                     'https://player.vimeo.com/player/%s' % feature_id,
620                     {'force_feature_id': True}), 'Vimeo')
621
622         # Extract video description
623
624         video_description = self._html_search_regex(
625             r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
626             webpage, 'description', default=None)
627         if not video_description:
628             video_description = self._html_search_meta(
629                 'description', webpage, default=None)
630         if not video_description and mobj.group('pro'):
631             orig_webpage = self._download_webpage(
632                 orig_url, video_id,
633                 note='Downloading webpage for description',
634                 fatal=False)
635             if orig_webpage:
636                 video_description = self._html_search_meta(
637                     'description', orig_webpage, default=None)
638         if not video_description and not mobj.group('player'):
639             self._downloader.report_warning('Cannot find video description')
640
641         # Extract upload date
642         if not timestamp:
643             timestamp = self._search_regex(
644                 r'<time[^>]+datetime="([^"]+)"', webpage,
645                 'timestamp', default=None)
646
647         try:
648             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
649             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
650             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
651         except RegexNotFoundError:
652             # This info is only available in vimeo.com/{id} urls
653             view_count = None
654             like_count = None
655             comment_count = None
656
657         formats = []
658         download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
659             'X-Requested-With': 'XMLHttpRequest'})
660         download_data = self._download_json(download_request, video_id, fatal=False)
661         if download_data:
662             source_file = download_data.get('source_file')
663             if isinstance(source_file, dict):
664                 download_url = source_file.get('download_url')
665                 if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
666                     source_name = source_file.get('public_name', 'Original')
667                     if self._is_valid_url(download_url, video_id, '%s video' % source_name):
668                         ext = (try_get(
669                             source_file, lambda x: x['extension'],
670                             compat_str) or determine_ext(
671                             download_url, None) or 'mp4').lower()
672                         formats.append({
673                             'url': download_url,
674                             'ext': ext,
675                             'width': int_or_none(source_file.get('width')),
676                             'height': int_or_none(source_file.get('height')),
677                             'filesize': parse_filesize(source_file.get('size')),
678                             'format_id': source_name,
679                             'preference': 1,
680                         })
681
682         info_dict_config = self._parse_config(config, video_id)
683         formats.extend(info_dict_config['formats'])
684         self._vimeo_sort_formats(formats)
685
686         json_ld = self._search_json_ld(webpage, video_id, default={})
687
688         if not cc_license:
689             cc_license = self._search_regex(
690                 r'<link[^>]+rel=["\']license["\'][^>]+href=(["\'])(?P<license>(?:(?!\1).)+)\1',
691                 webpage, 'license', default=None, group='license')
692
693         channel_url = 'https://vimeo.com/channels/%s' % channel_id if channel_id else None
694
695         info_dict = {
696             'id': video_id,
697             'formats': formats,
698             'timestamp': unified_timestamp(timestamp),
699             'description': video_description,
700             'webpage_url': url,
701             'view_count': view_count,
702             'like_count': like_count,
703             'comment_count': comment_count,
704             'license': cc_license,
705             'channel_id': channel_id,
706             'channel_url': channel_url,
707         }
708
709         info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
710
711         return info_dict
712
713
714 class VimeoOndemandIE(VimeoBaseInfoExtractor):
715     IE_NAME = 'vimeo:ondemand'
716     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
717     _TESTS = [{
718         # ondemand video not available via https://vimeo.com/id
719         'url': 'https://vimeo.com/ondemand/20704',
720         'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
721         'info_dict': {
722             'id': '105442900',
723             'ext': 'mp4',
724             'title': 'המעבדה - במאי יותם פלדמן',
725             'uploader': 'גם סרטים',
726             'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
727             'uploader_id': 'gumfilms',
728         },
729         'params': {
730             'format': 'best[protocol=https]',
731         },
732     }, {
733         # requires Referer to be passed along with og:video:url
734         'url': 'https://vimeo.com/ondemand/36938/126682985',
735         'info_dict': {
736             'id': '126682985',
737             'ext': 'mp4',
738             'title': 'Rävlock, rätt läte på rätt plats',
739             'uploader': 'Lindroth & Norin',
740             'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
741             'uploader_id': 'user14430847',
742         },
743         'params': {
744             'skip_download': True,
745         },
746     }, {
747         'url': 'https://vimeo.com/ondemand/nazmaalik',
748         'only_matching': True,
749     }, {
750         'url': 'https://vimeo.com/ondemand/141692381',
751         'only_matching': True,
752     }, {
753         'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
754         'only_matching': True,
755     }]
756
757     def _real_extract(self, url):
758         video_id = self._match_id(url)
759         webpage = self._download_webpage(url, video_id)
760         return self.url_result(
761             # Some videos require Referer to be passed along with og:video:url
762             # similarly to generic vimeo embeds (e.g.
763             # https://vimeo.com/ondemand/36938/126682985).
764             VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
765             VimeoIE.ie_key())
766
767
768 class VimeoChannelIE(VimeoBaseInfoExtractor):
769     IE_NAME = 'vimeo:channel'
770     _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
771     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
772     _TITLE = None
773     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
774     _TESTS = [{
775         'url': 'https://vimeo.com/channels/tributes',
776         'info_dict': {
777             'id': 'tributes',
778             'title': 'Vimeo Tributes',
779         },
780         'playlist_mincount': 25,
781     }]
782
783     def _page_url(self, base_url, pagenum):
784         return '%s/videos/page:%d/' % (base_url, pagenum)
785
786     def _extract_list_title(self, webpage):
787         return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
788
789     def _login_list_password(self, page_url, list_id, webpage):
790         login_form = self._search_regex(
791             r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
792             webpage, 'login form', default=None)
793         if not login_form:
794             return webpage
795
796         password = self._downloader.params.get('videopassword')
797         if password is None:
798             raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
799         fields = self._hidden_inputs(login_form)
800         token, vuid = self._extract_xsrft_and_vuid(webpage)
801         fields['token'] = token
802         fields['password'] = password
803         post = urlencode_postdata(fields)
804         password_path = self._search_regex(
805             r'action="([^"]+)"', login_form, 'password URL')
806         password_url = compat_urlparse.urljoin(page_url, password_path)
807         password_request = sanitized_Request(password_url, post)
808         password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
809         self._set_vimeo_cookie('vuid', vuid)
810         self._set_vimeo_cookie('xsrft', token)
811
812         return self._download_webpage(
813             password_request, list_id,
814             'Verifying the password', 'Wrong password')
815
816     def _title_and_entries(self, list_id, base_url):
817         for pagenum in itertools.count(1):
818             page_url = self._page_url(base_url, pagenum)
819             webpage = self._download_webpage(
820                 page_url, list_id,
821                 'Downloading page %s' % pagenum)
822
823             if pagenum == 1:
824                 webpage = self._login_list_password(page_url, list_id, webpage)
825                 yield self._extract_list_title(webpage)
826
827             # Try extracting href first since not all videos are available via
828             # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
829             clips = re.findall(
830                 r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
831             if clips:
832                 for video_id, video_url, video_title in clips:
833                     yield self.url_result(
834                         compat_urlparse.urljoin(base_url, video_url),
835                         VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
836             # More relaxed fallback
837             else:
838                 for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
839                     yield self.url_result(
840                         'https://vimeo.com/%s' % video_id,
841                         VimeoIE.ie_key(), video_id=video_id)
842
843             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
844                 break
845
846     def _extract_videos(self, list_id, base_url):
847         title_and_entries = self._title_and_entries(list_id, base_url)
848         list_title = next(title_and_entries)
849         return self.playlist_result(title_and_entries, list_id, list_title)
850
851     def _real_extract(self, url):
852         mobj = re.match(self._VALID_URL, url)
853         channel_id = mobj.group('id')
854         return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
855
856
857 class VimeoUserIE(VimeoChannelIE):
858     IE_NAME = 'vimeo:user'
859     _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
860     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
861     _TESTS = [{
862         'url': 'https://vimeo.com/nkistudio/videos',
863         'info_dict': {
864             'title': 'Nki',
865             'id': 'nkistudio',
866         },
867         'playlist_mincount': 66,
868     }]
869
870     def _real_extract(self, url):
871         mobj = re.match(self._VALID_URL, url)
872         name = mobj.group('name')
873         return self._extract_videos(name, 'https://vimeo.com/%s' % name)
874
875
876 class VimeoAlbumIE(VimeoChannelIE):
877     IE_NAME = 'vimeo:album'
878     _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
879     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
880     _TESTS = [{
881         'url': 'https://vimeo.com/album/2632481',
882         'info_dict': {
883             'id': '2632481',
884             'title': 'Staff Favorites: November 2013',
885         },
886         'playlist_mincount': 13,
887     }, {
888         'note': 'Password-protected album',
889         'url': 'https://vimeo.com/album/3253534',
890         'info_dict': {
891             'title': 'test',
892             'id': '3253534',
893         },
894         'playlist_count': 1,
895         'params': {
896             'videopassword': 'youtube-dl',
897         }
898     }, {
899         'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
900         'only_matching': True,
901     }, {
902         # TODO: respect page number
903         'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
904         'only_matching': True,
905     }]
906
907     def _page_url(self, base_url, pagenum):
908         return '%s/page:%d/' % (base_url, pagenum)
909
910     def _real_extract(self, url):
911         album_id = self._match_id(url)
912         return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
913
914
915 class VimeoGroupsIE(VimeoAlbumIE):
916     IE_NAME = 'vimeo:group'
917     _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
918     _TESTS = [{
919         'url': 'https://vimeo.com/groups/rolexawards',
920         'info_dict': {
921             'id': 'rolexawards',
922             'title': 'Rolex Awards for Enterprise',
923         },
924         'playlist_mincount': 73,
925     }]
926
927     def _extract_list_title(self, webpage):
928         return self._og_search_title(webpage)
929
930     def _real_extract(self, url):
931         mobj = re.match(self._VALID_URL, url)
932         name = mobj.group('name')
933         return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
934
935
936 class VimeoReviewIE(VimeoBaseInfoExtractor):
937     IE_NAME = 'vimeo:review'
938     IE_DESC = 'Review pages on vimeo'
939     _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
940     _TESTS = [{
941         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
942         'md5': 'c507a72f780cacc12b2248bb4006d253',
943         'info_dict': {
944             'id': '75524534',
945             'ext': 'mp4',
946             'title': "DICK HARDWICK 'Comedian'",
947             'uploader': 'Richard Hardwick',
948             'uploader_id': 'user21297594',
949         }
950     }, {
951         'note': 'video player needs Referer',
952         'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
953         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
954         'info_dict': {
955             'id': '91613211',
956             'ext': 'mp4',
957             'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
958             'uploader': 'DevWeek Events',
959             'duration': 2773,
960             'thumbnail': r're:^https?://.*\.jpg$',
961             'uploader_id': 'user22258446',
962         }
963     }, {
964         'note': 'Password protected',
965         'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
966         'info_dict': {
967             'id': '138823582',
968             'ext': 'mp4',
969             'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
970             'uploader': 'TMB',
971             'uploader_id': 'user37284429',
972         },
973         'params': {
974             'videopassword': 'holygrail',
975         },
976         'skip': 'video gone',
977     }]
978
979     def _real_initialize(self):
980         self._login()
981
982     def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
983         webpage = self._download_webpage(webpage_url, video_id)
984         config_url = self._html_search_regex(
985             r'data-config-url=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
986             'config URL', default=None, group='url')
987         if not config_url:
988             data = self._parse_json(self._search_regex(
989                 r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
990                 default=NO_DEFAULT if video_password_verified else '{}'), video_id)
991             config_url = data.get('vimeo_esi', {}).get('config', {}).get('configUrl')
992         if config_url is None:
993             self._verify_video_password(webpage_url, video_id, webpage)
994             config_url = self._get_config_url(
995                 webpage_url, video_id, video_password_verified=True)
996         return config_url
997
998     def _real_extract(self, url):
999         video_id = self._match_id(url)
1000         config_url = self._get_config_url(url, video_id)
1001         config = self._download_json(config_url, video_id)
1002         info_dict = self._parse_config(config, video_id)
1003         self._vimeo_sort_formats(info_dict['formats'])
1004         info_dict['id'] = video_id
1005         return info_dict
1006
1007
1008 class VimeoWatchLaterIE(VimeoChannelIE):
1009     IE_NAME = 'vimeo:watchlater'
1010     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
1011     _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
1012     _TITLE = 'Watch Later'
1013     _LOGIN_REQUIRED = True
1014     _TESTS = [{
1015         'url': 'https://vimeo.com/watchlater',
1016         'only_matching': True,
1017     }]
1018
1019     def _real_initialize(self):
1020         self._login()
1021
1022     def _page_url(self, base_url, pagenum):
1023         url = '%s/page:%d/' % (base_url, pagenum)
1024         request = sanitized_Request(url)
1025         # Set the header to get a partial html page with the ids,
1026         # the normal page doesn't contain them.
1027         request.add_header('X-Requested-With', 'XMLHttpRequest')
1028         return request
1029
1030     def _real_extract(self, url):
1031         return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
1032
1033
1034 class VimeoLikesIE(InfoExtractor):
1035     _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
1036     IE_NAME = 'vimeo:likes'
1037     IE_DESC = 'Vimeo user likes'
1038     _TESTS = [{
1039         'url': 'https://vimeo.com/user755559/likes/',
1040         'playlist_mincount': 293,
1041         'info_dict': {
1042             'id': 'user755559_likes',
1043             'description': 'See all the videos urza likes',
1044             'title': 'Videos urza likes',
1045         },
1046     }, {
1047         'url': 'https://vimeo.com/stormlapse/likes',
1048         'only_matching': True,
1049     }]
1050
1051     def _real_extract(self, url):
1052         user_id = self._match_id(url)
1053         webpage = self._download_webpage(url, user_id)
1054         page_count = self._int(
1055             self._search_regex(
1056                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
1057                     .*?</a></li>\s*<li\s+class="pagination_next">
1058                 ''', webpage, 'page count', default=1),
1059             'page count', fatal=True)
1060         PAGE_SIZE = 12
1061         title = self._html_search_regex(
1062             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
1063         description = self._html_search_meta('description', webpage)
1064
1065         def _get_page(idx):
1066             page_url = 'https://vimeo.com/%s/likes/page:%d/sort:date' % (
1067                 user_id, idx + 1)
1068             webpage = self._download_webpage(
1069                 page_url, user_id,
1070                 note='Downloading page %d/%d' % (idx + 1, page_count))
1071             video_list = self._search_regex(
1072                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
1073                 webpage, 'video content')
1074             paths = re.findall(
1075                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
1076             for path in paths:
1077                 yield {
1078                     '_type': 'url',
1079                     'url': compat_urlparse.urljoin(page_url, path),
1080                 }
1081
1082         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
1083
1084         return {
1085             '_type': 'playlist',
1086             'id': '%s_likes' % user_id,
1087             'title': title,
1088             'description': description,
1089             'entries': pl,
1090         }
1091
1092
1093 class VHXEmbedIE(InfoExtractor):
1094     IE_NAME = 'vhx:embed'
1095     _VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
1096
1097     def _call_api(self, video_id, access_token, path='', query=None):
1098         return self._download_json(
1099             'https://api.vhx.tv/videos/' + video_id + path, video_id, headers={
1100                 'Authorization': 'Bearer ' + access_token,
1101             }, query=query)
1102
1103     def _real_extract(self, url):
1104         video_id = self._match_id(url)
1105         webpage = self._download_webpage(url, video_id)
1106         credentials = self._parse_json(self._search_regex(
1107             r'(?s)credentials\s*:\s*({.+?}),', webpage,
1108             'config'), video_id, js_to_json)
1109         access_token = credentials['access_token']
1110
1111         query = {}
1112         for k, v in credentials.items():
1113             if k in ('authorization', 'authUserToken', 'ticket') and v and v != 'undefined':
1114                 if k == 'authUserToken':
1115                     query['auth_user_token'] = v
1116                 else:
1117                     query[k] = v
1118         files = self._call_api(video_id, access_token, '/files', query)
1119
1120         formats = []
1121         for f in files:
1122             href = try_get(f, lambda x: x['_links']['source']['href'])
1123             if not href:
1124                 continue
1125             method = f.get('method')
1126             if method == 'hls':
1127                 formats.extend(self._extract_m3u8_formats(
1128                     href, video_id, 'mp4', 'm3u8_native',
1129                     m3u8_id='hls', fatal=False))
1130             elif method == 'dash':
1131                 formats.extend(self._extract_mpd_formats(
1132                     href, video_id, mpd_id='dash', fatal=False))
1133             else:
1134                 fmt = {
1135                     'filesize': int_or_none(try_get(f, lambda x: x['size']['bytes'])),
1136                     'format_id': 'http',
1137                     'preference': 1,
1138                     'url': href,
1139                     'vcodec': f.get('codec'),
1140                 }
1141                 quality = f.get('quality')
1142                 if quality:
1143                     fmt.update({
1144                         'format_id': 'http-' + quality,
1145                         'height': int_or_none(self._search_regex(r'(\d+)p', quality, 'height', default=None)),
1146                     })
1147                 formats.append(fmt)
1148         self._sort_formats(formats)
1149
1150         video_data = self._call_api(video_id, access_token)
1151         title = video_data.get('title') or video_data['name']
1152
1153         subtitles = {}
1154         for subtitle in try_get(video_data, lambda x: x['tracks']['subtitles'], list) or []:
1155             lang = subtitle.get('srclang') or subtitle.get('label')
1156             for _link in subtitle.get('_links', {}).values():
1157                 href = _link.get('href')
1158                 if not href:
1159                     continue
1160                 subtitles.setdefault(lang, []).append({
1161                     'url': href,
1162                 })
1163
1164         q = qualities(['small', 'medium', 'large', 'source'])
1165         thumbnails = []
1166         for thumbnail_id, thumbnail_url in video_data.get('thumbnail', {}).items():
1167             thumbnails.append({
1168                 'id': thumbnail_id,
1169                 'url': thumbnail_url,
1170                 'preference': q(thumbnail_id),
1171             })
1172
1173         return {
1174             'id': video_id,
1175             'title': title,
1176             'description': video_data.get('description'),
1177             'duration': int_or_none(try_get(video_data, lambda x: x['duration']['seconds'])),
1178             'formats': formats,
1179             'subtitles': subtitles,
1180             'thumbnails': thumbnails,
1181             'timestamp': unified_timestamp(video_data.get('created_at')),
1182             'view_count': int_or_none(video_data.get('plays_count')),
1183         }