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