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