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