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