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