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