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