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