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