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