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