]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/vimeo.py
[vimeo] Fix extraction for VimeoReview videos
[youtube-dl.git] / youtube_dl / extractor / vimeo.py
1 # encoding: 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_urlparse,
12 )
13 from ..utils import (
14     determine_ext,
15     ExtractorError,
16     InAdvancePagedList,
17     int_or_none,
18     RegexNotFoundError,
19     sanitized_Request,
20     smuggle_url,
21     std_headers,
22     unified_strdate,
23     unsmuggle_url,
24     urlencode_postdata,
25     unescapeHTML,
26     parse_filesize,
27 )
28
29
30 class VimeoBaseInfoExtractor(InfoExtractor):
31     _NETRC_MACHINE = 'vimeo'
32     _LOGIN_REQUIRED = False
33     _LOGIN_URL = 'https://vimeo.com/log_in'
34
35     def _login(self):
36         (username, password) = self._get_login_info()
37         if username is None:
38             if self._LOGIN_REQUIRED:
39                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
40             return
41         self.report_login()
42         webpage = self._download_webpage(self._LOGIN_URL, None, False)
43         token, vuid = self._extract_xsrft_and_vuid(webpage)
44         data = urlencode_postdata({
45             'action': 'login',
46             'email': username,
47             'password': password,
48             'service': 'vimeo',
49             'token': token,
50         })
51         login_request = sanitized_Request(self._LOGIN_URL, data)
52         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
53         login_request.add_header('Referer', self._LOGIN_URL)
54         self._set_vimeo_cookie('vuid', vuid)
55         self._download_webpage(login_request, None, False, 'Wrong login info')
56
57     def _extract_xsrft_and_vuid(self, webpage):
58         xsrft = self._search_regex(
59             r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
60             webpage, 'login token', group='xsrft')
61         vuid = self._search_regex(
62             r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
63             webpage, 'vuid', group='vuid')
64         return xsrft, vuid
65
66     def _set_vimeo_cookie(self, name, value):
67         self._set_cookie('vimeo.com', name, value)
68
69     def _vimeo_sort_formats(self, formats):
70         # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
71         # at the same time without actual units specified. This lead to wrong sorting.
72         self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'format_id'))
73
74     def _parse_config(self, config, video_id):
75         # Extract title
76         video_title = config['video']['title']
77
78         # Extract uploader, uploader_url and uploader_id
79         video_uploader = config['video'].get('owner', {}).get('name')
80         video_uploader_url = config['video'].get('owner', {}).get('url')
81         video_uploader_id = video_uploader_url.split('/')[-1] if video_uploader_url else None
82
83         # Extract video thumbnail
84         video_thumbnail = config['video'].get('thumbnail')
85         if video_thumbnail is None:
86             video_thumbs = config['video'].get('thumbs')
87             if video_thumbs and isinstance(video_thumbs, dict):
88                 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
89
90         # Extract video duration
91         video_duration = int_or_none(config['video'].get('duration'))
92
93         formats = []
94         config_files = config['video'].get('files') or config['request'].get('files', {})
95         for f in config_files.get('progressive', []):
96             video_url = f.get('url')
97             if not video_url:
98                 continue
99             formats.append({
100                 'url': video_url,
101                 'format_id': 'http-%s' % f.get('quality'),
102                 'width': int_or_none(f.get('width')),
103                 'height': int_or_none(f.get('height')),
104                 'fps': int_or_none(f.get('fps')),
105                 'tbr': int_or_none(f.get('bitrate')),
106             })
107         m3u8_url = config_files.get('hls', {}).get('url')
108         if m3u8_url:
109             formats.extend(self._extract_m3u8_formats(
110                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
111
112         subtitles = {}
113         text_tracks = config['request'].get('text_tracks')
114         if text_tracks:
115             for tt in text_tracks:
116                 subtitles[tt['lang']] = [{
117                     'ext': 'vtt',
118                     'url': 'https://vimeo.com' + tt['url'],
119                 }]
120
121         return {
122             'title': video_title,
123             'uploader': video_uploader,
124             'uploader_id': video_uploader_id,
125             'uploader_url': video_uploader_url,
126             'thumbnail': video_thumbnail,
127             'duration': video_duration,
128             'formats': formats,
129             'subtitles': subtitles,
130         }
131
132
133 class VimeoIE(VimeoBaseInfoExtractor):
134     """Information extractor for vimeo.com."""
135
136     # _VALID_URL matches Vimeo URLs
137     _VALID_URL = r'''(?x)
138                     https?://
139                         (?:
140                             (?:
141                                 www|
142                                 (?P<player>player)
143                             )
144                             \.
145                         )?
146                         vimeo(?P<pro>pro)?\.com/
147                         (?!channels/[^/?#]+/?(?:$|[?#])|[^/]+/review/|(?:album|ondemand)/)
148                         (?:.*?/)?
149                         (?:
150                             (?:
151                                 play_redirect_hls|
152                                 moogaloop\.swf)\?clip_id=
153                             )?
154                         (?:videos?/)?
155                         (?P<id>[0-9]+)
156                         (?:/[\da-f]+)?
157                         /?(?:[?&].*)?(?:[#].*)?$
158                     '''
159     IE_NAME = 'vimeo'
160     _TESTS = [
161         {
162             'url': 'http://vimeo.com/56015672#at=0',
163             'md5': '8879b6cc097e987f02484baf890129e5',
164             'info_dict': {
165                 'id': '56015672',
166                 'ext': 'mp4',
167                 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
168                 'description': 'md5:2d3305bad981a06ff79f027f19865021',
169                 'upload_date': '20121220',
170                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/user7108434',
171                 'uploader_id': 'user7108434',
172                 'uploader': 'Filippo Valsorda',
173                 'duration': 10,
174             },
175         },
176         {
177             'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
178             'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
179             'note': 'Vimeo Pro video (#1197)',
180             'info_dict': {
181                 'id': '68093876',
182                 'ext': 'mp4',
183                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
184                 'uploader_id': 'openstreetmapus',
185                 'uploader': 'OpenStreetMap US',
186                 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
187                 'description': 'md5:fd69a7b8d8c34a4e1d2ec2e4afd6ec30',
188                 'duration': 1595,
189             },
190         },
191         {
192             'url': 'http://player.vimeo.com/video/54469442',
193             'md5': '619b811a4417aa4abe78dc653becf511',
194             'note': 'Videos that embed the url in the player page',
195             'info_dict': {
196                 'id': '54469442',
197                 'ext': 'mp4',
198                 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
199                 'uploader': 'The BLN & Business of Software',
200                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
201                 'uploader_id': 'theblnbusinessofsoftware',
202                 'duration': 3610,
203                 'description': None,
204             },
205         },
206         {
207             'url': 'http://vimeo.com/68375962',
208             'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
209             'note': 'Video protected with password',
210             'info_dict': {
211                 'id': '68375962',
212                 'ext': 'mp4',
213                 'title': 'youtube-dl password protected test video',
214                 'upload_date': '20130614',
215                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/user18948128',
216                 'uploader_id': 'user18948128',
217                 'uploader': 'Jaime Marquínez Ferrándiz',
218                 'duration': 10,
219                 'description': 'This is "youtube-dl password protected test video" by  on Vimeo, the home for high quality videos and the people who love them.',
220             },
221             'params': {
222                 'videopassword': 'youtube-dl',
223             },
224         },
225         {
226             'url': 'http://vimeo.com/channels/keypeele/75629013',
227             'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
228             'note': 'Video is freely available via original URL '
229                     'and protected with password when accessed via http://vimeo.com/75629013',
230             'info_dict': {
231                 'id': '75629013',
232                 'ext': 'mp4',
233                 'title': 'Key & Peele: Terrorist Interrogation',
234                 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
235                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/atencio',
236                 'uploader_id': 'atencio',
237                 'uploader': 'Peter Atencio',
238                 'upload_date': '20130927',
239                 'duration': 187,
240             },
241         },
242         {
243             'url': 'http://vimeo.com/76979871',
244             'note': 'Video with subtitles',
245             'info_dict': {
246                 'id': '76979871',
247                 'ext': 'mp4',
248                 'title': 'The New Vimeo Player (You Know, For Videos)',
249                 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
250                 'upload_date': '20131015',
251                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/staff',
252                 'uploader_id': 'staff',
253                 'uploader': 'Vimeo Staff',
254                 'duration': 62,
255             }
256         },
257         {
258             # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
259             'url': 'https://player.vimeo.com/video/98044508',
260             'note': 'The js code contains assignments to the same variable as the config',
261             'info_dict': {
262                 'id': '98044508',
263                 'ext': 'mp4',
264                 'title': 'Pier Solar OUYA Official Trailer',
265                 'uploader': 'Tulio Gonçalves',
266                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/user28849593',
267                 'uploader_id': 'user28849593',
268             },
269         },
270         {
271             # contains original format
272             'url': 'https://vimeo.com/33951933',
273             'md5': '53c688fa95a55bf4b7293d37a89c5c53',
274             'info_dict': {
275                 'id': '33951933',
276                 'ext': 'mp4',
277                 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
278                 'uploader': 'The DMCI',
279                 'uploader_url': 're:https?://(?:www\.)?vimeo\.com/dmci',
280                 'uploader_id': 'dmci',
281                 'upload_date': '20111220',
282                 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
283             },
284         },
285         {
286             'url': 'https://vimeo.com/109815029',
287             'note': 'Video not completely processed, "failed" seed status',
288             'only_matching': True,
289         },
290         {
291             'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
292             'only_matching': True,
293         },
294         {
295             # source file returns 403: Forbidden
296             'url': 'https://vimeo.com/7809605',
297             'only_matching': True,
298         },
299         {
300             'url': 'https://vimeo.com/160743502/abd0e13fb4',
301             'only_matching': True,
302         }
303     ]
304
305     @staticmethod
306     def _extract_vimeo_url(url, webpage):
307         # Look for embedded (iframe) Vimeo player
308         mobj = re.search(
309             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
310         if mobj:
311             player_url = unescapeHTML(mobj.group('url'))
312             surl = smuggle_url(player_url, {'http_headers': {'Referer': url}})
313             return surl
314         # Look for embedded (swf embed) Vimeo player
315         mobj = re.search(
316             r'<embed[^>]+?src="((?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
317         if mobj:
318             return mobj.group(1)
319
320     def _verify_video_password(self, url, video_id, webpage):
321         password = self._downloader.params.get('videopassword')
322         if password is None:
323             raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
324         token, vuid = self._extract_xsrft_and_vuid(webpage)
325         data = urlencode_postdata({
326             'password': password,
327             'token': token,
328         })
329         if url.startswith('http://'):
330             # vimeo only supports https now, but the user can give an http url
331             url = url.replace('http://', 'https://')
332         password_request = sanitized_Request(url + '/password', data)
333         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
334         password_request.add_header('Referer', url)
335         self._set_vimeo_cookie('vuid', vuid)
336         return self._download_webpage(
337             password_request, video_id,
338             'Verifying the password', 'Wrong password')
339
340     def _verify_player_video_password(self, url, video_id):
341         password = self._downloader.params.get('videopassword')
342         if password is None:
343             raise ExtractorError('This video is protected by a password, use the --video-password option')
344         data = urlencode_postdata({'password': password})
345         pass_url = url + '/check-password'
346         password_request = sanitized_Request(pass_url, data)
347         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
348         password_request.add_header('Referer', url)
349         return self._download_json(
350             password_request, video_id,
351             'Verifying the password', 'Wrong password')
352
353     def _real_initialize(self):
354         self._login()
355
356     def _real_extract(self, url):
357         url, data = unsmuggle_url(url, {})
358         headers = std_headers.copy()
359         if 'http_headers' in data:
360             headers.update(data['http_headers'])
361         if 'Referer' not in headers:
362             headers['Referer'] = url
363
364         # Extract ID from URL
365         mobj = re.match(self._VALID_URL, url)
366         video_id = mobj.group('id')
367         orig_url = url
368         if mobj.group('pro') or mobj.group('player'):
369             url = 'https://player.vimeo.com/video/' + video_id
370         else:
371             url = 'https://vimeo.com/' + video_id
372
373         # Retrieve video webpage to extract further information
374         request = sanitized_Request(url, headers=headers)
375         try:
376             webpage = self._download_webpage(request, video_id)
377         except ExtractorError as ee:
378             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
379                 errmsg = ee.cause.read()
380                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
381                     raise ExtractorError(
382                         'Cannot download embed-only video without embedding '
383                         'URL. Please call youtube-dl with the URL of the page '
384                         'that embeds this video.',
385                         expected=True)
386             raise
387
388         # Now we begin extracting as much information as we can from what we
389         # retrieved. First we extract the information common to all extractors,
390         # and latter we extract those that are Vimeo specific.
391         self.report_extraction(video_id)
392
393         vimeo_config = self._search_regex(
394             r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
395             'vimeo config', default=None)
396         if vimeo_config:
397             seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
398             if seed_status.get('state') == 'failed':
399                 raise ExtractorError(
400                     '%s said: %s' % (self.IE_NAME, seed_status['title']),
401                     expected=True)
402
403         # Extract the config JSON
404         try:
405             try:
406                 config_url = self._html_search_regex(
407                     r' data-config-url="(.+?)"', webpage,
408                     'config URL', default=None)
409                 if not config_url:
410                     # Sometimes new react-based page is served instead of old one that require
411                     # different config URL extraction approach (see
412                     # https://github.com/rg3/youtube-dl/pull/7209)
413                     vimeo_clip_page_config = self._search_regex(
414                         r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
415                         'vimeo clip page config')
416                     config_url = self._parse_json(
417                         vimeo_clip_page_config, video_id)['player']['config_url']
418                 config_json = self._download_webpage(config_url, video_id)
419                 config = json.loads(config_json)
420             except RegexNotFoundError:
421                 # For pro videos or player.vimeo.com urls
422                 # We try to find out to which variable is assigned the config dic
423                 m_variable_name = re.search('(\w)\.video\.id', webpage)
424                 if m_variable_name is not None:
425                     config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
426                 else:
427                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
428                 config = self._search_regex(config_re, webpage, 'info section',
429                                             flags=re.DOTALL)
430                 config = json.loads(config)
431         except Exception as e:
432             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
433                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
434
435             if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
436                 if '_video_password_verified' in data:
437                     raise ExtractorError('video password verification failed!')
438                 self._verify_video_password(url, video_id, webpage)
439                 return self._real_extract(
440                     smuggle_url(url, {'_video_password_verified': 'verified'}))
441             else:
442                 raise ExtractorError('Unable to extract info section',
443                                      cause=e)
444         else:
445             if config.get('view') == 4:
446                 config = self._verify_player_video_password(url, video_id)
447
448         if '>You rented this title.<' in webpage:
449             feature_id = config.get('video', {}).get('vod', {}).get('feature_id')
450             if feature_id and not data.get('force_feature_id', False):
451                 return self.url_result(smuggle_url(
452                     'https://player.vimeo.com/player/%s' % feature_id,
453                     {'force_feature_id': True}), 'Vimeo')
454
455         # Extract video description
456
457         video_description = self._html_search_regex(
458             r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
459             webpage, 'description', default=None)
460         if not video_description:
461             video_description = self._html_search_meta(
462                 'description', webpage, default=None)
463         if not video_description and mobj.group('pro'):
464             orig_webpage = self._download_webpage(
465                 orig_url, video_id,
466                 note='Downloading webpage for description',
467                 fatal=False)
468             if orig_webpage:
469                 video_description = self._html_search_meta(
470                     'description', orig_webpage, default=None)
471         if not video_description and not mobj.group('player'):
472             self._downloader.report_warning('Cannot find video description')
473
474         # Extract upload date
475         video_upload_date = None
476         mobj = re.search(r'<time[^>]+datetime="([^"]+)"', webpage)
477         if mobj is not None:
478             video_upload_date = unified_strdate(mobj.group(1))
479
480         try:
481             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
482             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
483             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
484         except RegexNotFoundError:
485             # This info is only available in vimeo.com/{id} urls
486             view_count = None
487             like_count = None
488             comment_count = None
489
490         formats = []
491         download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
492             'X-Requested-With': 'XMLHttpRequest'})
493         download_data = self._download_json(download_request, video_id, fatal=False)
494         if download_data:
495             source_file = download_data.get('source_file')
496             if isinstance(source_file, dict):
497                 download_url = source_file.get('download_url')
498                 if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
499                     source_name = source_file.get('public_name', 'Original')
500                     if self._is_valid_url(download_url, video_id, '%s video' % source_name):
501                         ext = source_file.get('extension', determine_ext(download_url)).lower()
502                         formats.append({
503                             'url': download_url,
504                             'ext': ext,
505                             'width': int_or_none(source_file.get('width')),
506                             'height': int_or_none(source_file.get('height')),
507                             'filesize': parse_filesize(source_file.get('size')),
508                             'format_id': source_name,
509                             'preference': 1,
510                         })
511
512         info_dict = self._parse_config(config, video_id)
513         formats.extend(info_dict['formats'])
514         self._vimeo_sort_formats(formats)
515         info_dict.update({
516             'id': video_id,
517             'formats': formats,
518             'upload_date': video_upload_date,
519             'description': video_description,
520             'webpage_url': url,
521             'view_count': view_count,
522             'like_count': like_count,
523             'comment_count': comment_count,
524         })
525
526         return info_dict
527
528
529 class VimeoOndemandIE(VimeoBaseInfoExtractor):
530     IE_NAME = 'vimeo:ondemand'
531     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
532     _TESTS = [{
533         # ondemand video not available via https://vimeo.com/id
534         'url': 'https://vimeo.com/ondemand/20704',
535         'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
536         'info_dict': {
537             'id': '105442900',
538             'ext': 'mp4',
539             'title': 'המעבדה - במאי יותם פלדמן',
540             'uploader': 'גם סרטים',
541             'uploader_url': 're:https?://(?:www\.)?vimeo\.com/gumfilms',
542             'uploader_id': 'gumfilms',
543         },
544     }, {
545         'url': 'https://vimeo.com/ondemand/nazmaalik',
546         'only_matching': True,
547     }, {
548         'url': 'https://vimeo.com/ondemand/141692381',
549         'only_matching': True,
550     }, {
551         'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
552         'only_matching': True,
553     }]
554
555     def _real_extract(self, url):
556         video_id = self._match_id(url)
557         webpage = self._download_webpage(url, video_id)
558         return self.url_result(self._og_search_video_url(webpage), VimeoIE.ie_key())
559
560
561 class VimeoChannelIE(VimeoBaseInfoExtractor):
562     IE_NAME = 'vimeo:channel'
563     _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
564     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
565     _TITLE = None
566     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
567     _TESTS = [{
568         'url': 'https://vimeo.com/channels/tributes',
569         'info_dict': {
570             'id': 'tributes',
571             'title': 'Vimeo Tributes',
572         },
573         'playlist_mincount': 25,
574     }]
575
576     def _page_url(self, base_url, pagenum):
577         return '%s/videos/page:%d/' % (base_url, pagenum)
578
579     def _extract_list_title(self, webpage):
580         return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
581
582     def _login_list_password(self, page_url, list_id, webpage):
583         login_form = self._search_regex(
584             r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
585             webpage, 'login form', default=None)
586         if not login_form:
587             return webpage
588
589         password = self._downloader.params.get('videopassword')
590         if password is None:
591             raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
592         fields = self._hidden_inputs(login_form)
593         token, vuid = self._extract_xsrft_and_vuid(webpage)
594         fields['token'] = token
595         fields['password'] = password
596         post = urlencode_postdata(fields)
597         password_path = self._search_regex(
598             r'action="([^"]+)"', login_form, 'password URL')
599         password_url = compat_urlparse.urljoin(page_url, password_path)
600         password_request = sanitized_Request(password_url, post)
601         password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
602         self._set_vimeo_cookie('vuid', vuid)
603         self._set_vimeo_cookie('xsrft', token)
604
605         return self._download_webpage(
606             password_request, list_id,
607             'Verifying the password', 'Wrong password')
608
609     def _title_and_entries(self, list_id, base_url):
610         for pagenum in itertools.count(1):
611             page_url = self._page_url(base_url, pagenum)
612             webpage = self._download_webpage(
613                 page_url, list_id,
614                 'Downloading page %s' % pagenum)
615
616             if pagenum == 1:
617                 webpage = self._login_list_password(page_url, list_id, webpage)
618                 yield self._extract_list_title(webpage)
619
620             for video_id in re.findall(r'id="clip_(\d+?)"', webpage):
621                 yield self.url_result('https://vimeo.com/%s' % video_id, 'Vimeo')
622
623             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
624                 break
625
626     def _extract_videos(self, list_id, base_url):
627         title_and_entries = self._title_and_entries(list_id, base_url)
628         list_title = next(title_and_entries)
629         return self.playlist_result(title_and_entries, list_id, list_title)
630
631     def _real_extract(self, url):
632         mobj = re.match(self._VALID_URL, url)
633         channel_id = mobj.group('id')
634         return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
635
636
637 class VimeoUserIE(VimeoChannelIE):
638     IE_NAME = 'vimeo:user'
639     _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
640     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
641     _TESTS = [{
642         'url': 'https://vimeo.com/nkistudio/videos',
643         'info_dict': {
644             'title': 'Nki',
645             'id': 'nkistudio',
646         },
647         'playlist_mincount': 66,
648     }]
649
650     def _real_extract(self, url):
651         mobj = re.match(self._VALID_URL, url)
652         name = mobj.group('name')
653         return self._extract_videos(name, 'https://vimeo.com/%s' % name)
654
655
656 class VimeoAlbumIE(VimeoChannelIE):
657     IE_NAME = 'vimeo:album'
658     _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)'
659     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
660     _TESTS = [{
661         'url': 'https://vimeo.com/album/2632481',
662         'info_dict': {
663             'id': '2632481',
664             'title': 'Staff Favorites: November 2013',
665         },
666         'playlist_mincount': 13,
667     }, {
668         'note': 'Password-protected album',
669         'url': 'https://vimeo.com/album/3253534',
670         'info_dict': {
671             'title': 'test',
672             'id': '3253534',
673         },
674         'playlist_count': 1,
675         'params': {
676             'videopassword': 'youtube-dl',
677         }
678     }]
679
680     def _page_url(self, base_url, pagenum):
681         return '%s/page:%d/' % (base_url, pagenum)
682
683     def _real_extract(self, url):
684         album_id = self._match_id(url)
685         return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
686
687
688 class VimeoGroupsIE(VimeoAlbumIE):
689     IE_NAME = 'vimeo:group'
690     _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
691     _TESTS = [{
692         'url': 'https://vimeo.com/groups/rolexawards',
693         'info_dict': {
694             'id': 'rolexawards',
695             'title': 'Rolex Awards for Enterprise',
696         },
697         'playlist_mincount': 73,
698     }]
699
700     def _extract_list_title(self, webpage):
701         return self._og_search_title(webpage)
702
703     def _real_extract(self, url):
704         mobj = re.match(self._VALID_URL, url)
705         name = mobj.group('name')
706         return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
707
708
709 class VimeoReviewIE(VimeoBaseInfoExtractor):
710     IE_NAME = 'vimeo:review'
711     IE_DESC = 'Review pages on vimeo'
712     _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
713     _TESTS = [{
714         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
715         'md5': 'c507a72f780cacc12b2248bb4006d253',
716         'info_dict': {
717             'id': '75524534',
718             'ext': 'mp4',
719             'title': "DICK HARDWICK 'Comedian'",
720             'uploader': 'Richard Hardwick',
721             'uploader_id': 'user21297594',
722         }
723     }, {
724         'note': 'video player needs Referer',
725         'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
726         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
727         'info_dict': {
728             'id': '91613211',
729             'ext': 'mp4',
730             'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
731             'uploader': 'DevWeek Events',
732             'duration': 2773,
733             'thumbnail': 're:^https?://.*\.jpg$',
734             'uploader_id': 'user22258446',
735         }
736     }]
737
738     def _real_extract(self, url):
739         video_id = self._match_id(url)
740         config = self._download_json(
741             'https://player.vimeo.com/video/%s/config' % video_id, video_id)
742         info_dict = self._parse_config(config, video_id)
743         self._vimeo_sort_formats(info_dict['formats'])
744         info_dict['id'] = video_id
745         return info_dict
746
747
748 class VimeoWatchLaterIE(VimeoChannelIE):
749     IE_NAME = 'vimeo:watchlater'
750     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
751     _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
752     _TITLE = 'Watch Later'
753     _LOGIN_REQUIRED = True
754     _TESTS = [{
755         'url': 'https://vimeo.com/watchlater',
756         'only_matching': True,
757     }]
758
759     def _real_initialize(self):
760         self._login()
761
762     def _page_url(self, base_url, pagenum):
763         url = '%s/page:%d/' % (base_url, pagenum)
764         request = sanitized_Request(url)
765         # Set the header to get a partial html page with the ids,
766         # the normal page doesn't contain them.
767         request.add_header('X-Requested-With', 'XMLHttpRequest')
768         return request
769
770     def _real_extract(self, url):
771         return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
772
773
774 class VimeoLikesIE(InfoExtractor):
775     _VALID_URL = r'https://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
776     IE_NAME = 'vimeo:likes'
777     IE_DESC = 'Vimeo user likes'
778     _TEST = {
779         'url': 'https://vimeo.com/user755559/likes/',
780         'playlist_mincount': 293,
781         'info_dict': {
782             'id': 'user755559_likes',
783             'description': 'See all the videos urza likes',
784             'title': 'Videos urza likes',
785         },
786     }
787
788     def _real_extract(self, url):
789         user_id = self._match_id(url)
790         webpage = self._download_webpage(url, user_id)
791         page_count = self._int(
792             self._search_regex(
793                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
794                     .*?</a></li>\s*<li\s+class="pagination_next">
795                 ''', webpage, 'page count'),
796             'page count', fatal=True)
797         PAGE_SIZE = 12
798         title = self._html_search_regex(
799             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
800         description = self._html_search_meta('description', webpage)
801
802         def _get_page(idx):
803             page_url = 'https://vimeo.com/user%s/likes/page:%d/sort:date' % (
804                 user_id, idx + 1)
805             webpage = self._download_webpage(
806                 page_url, user_id,
807                 note='Downloading page %d/%d' % (idx + 1, page_count))
808             video_list = self._search_regex(
809                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
810                 webpage, 'video content')
811             paths = re.findall(
812                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
813             for path in paths:
814                 yield {
815                     '_type': 'url',
816                     'url': compat_urlparse.urljoin(page_url, path),
817                 }
818
819         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
820
821         return {
822             '_type': 'playlist',
823             'id': 'user%s_likes' % user_id,
824             'title': title,
825             'description': description,
826             'entries': pl,
827         }