]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/vimeo.py
Fix "invalid escape sequences" error on Python 3.6
[yt-dlp.git] / youtube_dl / extractor / vimeo.py
CommitLineData
dcdb292f 1# coding: utf-8
9148eb00
PH
2from __future__ import unicode_literals
3
b3d14cbf
PH
4import json
5import re
caeefc29 6import itertools
b3d14cbf
PH
7
8from .common import InfoExtractor
8c25f81b 9from ..compat import (
1060425c 10 compat_HTTPError,
6a55bb66 11 compat_str,
9c44d242 12 compat_urlparse,
8c25f81b
PH
13)
14from ..utils import (
d5f071af 15 determine_ext,
b3d14cbf 16 ExtractorError,
9c44d242
PH
17 InAdvancePagedList,
18 int_or_none,
c1ff6e1a 19 NO_DEFAULT,
55b3e45b 20 RegexNotFoundError,
67dda517 21 sanitized_Request,
30965ac6 22 smuggle_url,
b3d14cbf 23 std_headers,
3c6f2450 24 unified_strdate,
9d4660ca 25 unsmuggle_url,
a980bc43 26 urlencode_postdata,
b407e173 27 unescapeHTML,
eb4f2740 28 parse_filesize,
6a55bb66 29 try_get,
b3d14cbf
PH
30)
31
bbafbe20 32
efb7e119
JMF
33class VimeoBaseInfoExtractor(InfoExtractor):
34 _NETRC_MACHINE = 'vimeo'
35 _LOGIN_REQUIRED = False
f6c3664d 36 _LOGIN_URL = 'https://vimeo.com/log_in'
efb7e119
JMF
37
38 def _login(self):
39 (username, password) = self._get_login_info()
40 if username is None:
41 if self._LOGIN_REQUIRED:
4f3e9430 42 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
efb7e119
JMF
43 return
44 self.report_login()
f6c3664d 45 webpage = self._download_webpage(self._LOGIN_URL, None, False)
7c845629 46 token, vuid = self._extract_xsrft_and_vuid(webpage)
15707c7e 47 data = urlencode_postdata({
f6c3664d 48 'action': 'login',
efb7e119
JMF
49 'email': username,
50 'password': password,
efb7e119
JMF
51 'service': 'vimeo',
52 'token': token,
15707c7e 53 })
67dda517 54 login_request = sanitized_Request(self._LOGIN_URL, data)
efb7e119 55 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
f6c3664d 56 login_request.add_header('Referer', self._LOGIN_URL)
9eab37dc 57 self._set_vimeo_cookie('vuid', vuid)
efb7e119
JMF
58 self._download_webpage(login_request, None, False, 'Wrong login info')
59
c1ff6e1a
YCH
60 def _verify_video_password(self, url, video_id, webpage):
61 password = self._downloader.params.get('videopassword')
62 if password is None:
63 raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
64 token, vuid = self._extract_xsrft_and_vuid(webpage)
65 data = urlencode_postdata({
66 'password': password,
67 'token': token,
68 })
69 if url.startswith('http://'):
70 # vimeo only supports https now, but the user can give an http url
71 url = url.replace('http://', 'https://')
72 password_request = sanitized_Request(url + '/password', data)
73 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
74 password_request.add_header('Referer', url)
75 self._set_vimeo_cookie('vuid', vuid)
76 return self._download_webpage(
77 password_request, video_id,
78 'Verifying the password', 'Wrong password')
79
7c845629
S
80 def _extract_xsrft_and_vuid(self, webpage):
81 xsrft = self._search_regex(
b826035d 82 r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
f6c3664d 83 webpage, 'login token', group='xsrft')
7c845629
S
84 vuid = self._search_regex(
85 r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
86 webpage, 'vuid', group='vuid')
87 return xsrft, vuid
f6c3664d 88
9eab37dc
S
89 def _set_vimeo_cookie(self, name, value):
90 self._set_cookie('vimeo.com', name, value)
91
531a7496
YCH
92 def _vimeo_sort_formats(self, formats):
93 # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
94 # at the same time without actual units specified. This lead to wrong sorting.
d8c507c9 95 self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
531a7496
YCH
96
97 def _parse_config(self, config, video_id):
d8c507c9 98 video_data = config['video']
531a7496 99 # Extract title
d8c507c9 100 video_title = video_data['title']
531a7496
YCH
101
102 # Extract uploader, uploader_url and uploader_id
d8c507c9
RA
103 video_uploader = video_data.get('owner', {}).get('name')
104 video_uploader_url = video_data.get('owner', {}).get('url')
531a7496
YCH
105 video_uploader_id = video_uploader_url.split('/')[-1] if video_uploader_url else None
106
107 # Extract video thumbnail
d8c507c9 108 video_thumbnail = video_data.get('thumbnail')
531a7496 109 if video_thumbnail is None:
d8c507c9 110 video_thumbs = video_data.get('thumbs')
531a7496
YCH
111 if video_thumbs and isinstance(video_thumbs, dict):
112 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
113
114 # Extract video duration
d8c507c9 115 video_duration = int_or_none(video_data.get('duration'))
531a7496
YCH
116
117 formats = []
d8c507c9 118 config_files = video_data.get('files') or config['request'].get('files', {})
531a7496
YCH
119 for f in config_files.get('progressive', []):
120 video_url = f.get('url')
121 if not video_url:
122 continue
123 formats.append({
124 'url': video_url,
125 'format_id': 'http-%s' % f.get('quality'),
126 'width': int_or_none(f.get('width')),
127 'height': int_or_none(f.get('height')),
128 'fps': int_or_none(f.get('fps')),
129 'tbr': int_or_none(f.get('bitrate')),
130 })
d8c507c9
RA
131
132 for files_type in ('hls', 'dash'):
133 for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
134 manifest_url = cdn_data.get('url')
135 if not manifest_url:
136 continue
137 format_id = '%s-%s' % (files_type, cdn_name)
138 if files_type == 'hls':
139 formats.extend(self._extract_m3u8_formats(
140 manifest_url, video_id, 'mp4',
141 'm3u8_native', m3u8_id=format_id,
142 note='Downloading %s m3u8 information' % cdn_name,
143 fatal=False))
144 elif files_type == 'dash':
145 formats.extend(self._extract_mpd_formats(
146 manifest_url.replace('/master.json', '/master.mpd'), video_id, format_id,
147 'Downloading %s MPD information' % cdn_name,
148 fatal=False))
531a7496
YCH
149
150 subtitles = {}
151 text_tracks = config['request'].get('text_tracks')
152 if text_tracks:
153 for tt in text_tracks:
154 subtitles[tt['lang']] = [{
155 'ext': 'vtt',
156 'url': 'https://vimeo.com' + tt['url'],
157 }]
158
159 return {
160 'title': video_title,
161 'uploader': video_uploader,
162 'uploader_id': video_uploader_id,
163 'uploader_url': video_uploader_url,
164 'thumbnail': video_thumbnail,
165 'duration': video_duration,
166 'formats': formats,
167 'subtitles': subtitles,
168 }
169
efb7e119 170
65469a7f 171class VimeoIE(VimeoBaseInfoExtractor):
b3d14cbf
PH
172 """Information extractor for vimeo.com."""
173
174 # _VALID_URL matches Vimeo URLs
bbafbe20 175 _VALID_URL = r'''(?x)
74278def
S
176 https?://
177 (?:
178 (?:
179 www|
180 (?P<player>player)
181 )
182 \.
183 )?
184 vimeo(?P<pro>pro)?\.com/
c8e3e097 185 (?!(?:channels|album)/[^/?#]+/?(?:$|[?#])|[^/]+/review/|ondemand/)
74278def
S
186 (?:.*?/)?
187 (?:
188 (?:
189 play_redirect_hls|
190 moogaloop\.swf)\?clip_id=
191 )?
192 (?:videos?/)?
193 (?P<id>[0-9]+)
241a318f 194 (?:/[\da-f]+)?
74278def
S
195 /?(?:[?&].*)?(?:[#].*)?$
196 '''
9148eb00 197 IE_NAME = 'vimeo'
a91b954b
JMF
198 _TESTS = [
199 {
9148eb00 200 'url': 'http://vimeo.com/56015672#at=0',
9148eb00
PH
201 'md5': '8879b6cc097e987f02484baf890129e5',
202 'info_dict': {
ad5976b4
PH
203 'id': '56015672',
204 'ext': 'mp4',
68f3b61f
S
205 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
206 'description': 'md5:2d3305bad981a06ff79f027f19865021',
207 'upload_date': '20121220',
ec85ded8 208 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user7108434',
68f3b61f
S
209 'uploader_id': 'user7108434',
210 'uploader': 'Filippo Valsorda',
211 'duration': 10,
a91b954b
JMF
212 },
213 },
214 {
9148eb00 215 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
9148eb00
PH
216 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
217 'note': 'Vimeo Pro video (#1197)',
218 'info_dict': {
4f3e9430
JMF
219 'id': '68093876',
220 'ext': 'mp4',
ec85ded8 221 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
9148eb00
PH
222 'uploader_id': 'openstreetmapus',
223 'uploader': 'OpenStreetMap US',
224 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
68f3b61f 225 'description': 'md5:fd69a7b8d8c34a4e1d2ec2e4afd6ec30',
69c8fb9e 226 'duration': 1595,
a91b954b
JMF
227 },
228 },
aa32314d 229 {
9148eb00 230 'url': 'http://player.vimeo.com/video/54469442',
9148eb00
PH
231 'md5': '619b811a4417aa4abe78dc653becf511',
232 'note': 'Videos that embed the url in the player page',
233 'info_dict': {
4f3e9430
JMF
234 'id': '54469442',
235 'ext': 'mp4',
0e6ebc13 236 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
9148eb00 237 'uploader': 'The BLN & Business of Software',
ec85ded8 238 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
9148eb00 239 'uploader_id': 'theblnbusinessofsoftware',
69c8fb9e 240 'duration': 3610,
58ea7ec8 241 'description': None,
aa32314d 242 },
93b22c78
JMF
243 },
244 {
9148eb00 245 'url': 'http://vimeo.com/68375962',
9148eb00
PH
246 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
247 'note': 'Video protected with password',
248 'info_dict': {
4f3e9430
JMF
249 'id': '68375962',
250 'ext': 'mp4',
9148eb00
PH
251 'title': 'youtube-dl password protected test video',
252 'upload_date': '20130614',
ec85ded8 253 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
9148eb00
PH
254 'uploader_id': 'user18948128',
255 'uploader': 'Jaime Marquínez Ferrándiz',
69c8fb9e 256 'duration': 10,
531a7496 257 'description': 'This is "youtube-dl password protected test video" by on Vimeo, the home for high quality videos and the people who love them.',
93b22c78 258 },
9148eb00
PH
259 'params': {
260 'videopassword': 'youtube-dl',
93b22c78
JMF
261 },
262 },
548f31d9
S
263 {
264 'url': 'http://vimeo.com/channels/keypeele/75629013',
265 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
548f31d9
S
266 'info_dict': {
267 'id': '75629013',
268 'ext': 'mp4',
269 'title': 'Key & Peele: Terrorist Interrogation',
270 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
ec85ded8 271 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/atencio',
548f31d9
S
272 'uploader_id': 'atencio',
273 'uploader': 'Peter Atencio',
3c6f2450 274 'upload_date': '20130927',
548f31d9
S
275 'duration': 187,
276 },
277 },
1eac553e
S
278 {
279 'url': 'http://vimeo.com/76979871',
1eac553e
S
280 'note': 'Video with subtitles',
281 'info_dict': {
282 'id': '76979871',
283 'ext': 'mp4',
284 'title': 'The New Vimeo Player (You Know, For Videos)',
285 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
286 'upload_date': '20131015',
ec85ded8 287 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/staff',
1eac553e
S
288 'uploader_id': 'staff',
289 'uploader': 'Vimeo Staff',
69c8fb9e 290 'duration': 62,
1eac553e
S
291 }
292 },
4698f0d8
JMF
293 {
294 # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
295 'url': 'https://player.vimeo.com/video/98044508',
296 'note': 'The js code contains assignments to the same variable as the config',
297 'info_dict': {
298 'id': '98044508',
299 'ext': 'mp4',
300 'title': 'Pier Solar OUYA Official Trailer',
301 'uploader': 'Tulio Gonçalves',
ec85ded8 302 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user28849593',
4698f0d8
JMF
303 'uploader_id': 'user28849593',
304 },
305 },
323f82a7 306 {
307 # contains original format
308 'url': 'https://vimeo.com/33951933',
c143ddce 309 'md5': '2d9f5475e0537f013d0073e812ab89e6',
323f82a7 310 'info_dict': {
311 'id': '33951933',
312 'ext': 'mp4',
313 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
314 'uploader': 'The DMCI',
ec85ded8 315 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/dmci',
323f82a7 316 'uploader_id': 'dmci',
317 'upload_date': '20111220',
318 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
319 },
320 },
c143ddce
S
321 {
322 # only available via https://vimeo.com/channels/tributes/6213729 and
323 # not via https://vimeo.com/6213729
324 'url': 'https://vimeo.com/channels/tributes/6213729',
325 'info_dict': {
326 'id': '6213729',
327 'ext': 'mp4',
328 'title': 'Vimeo Tribute: The Shining',
329 'uploader': 'Casey Donahue',
ec85ded8 330 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/caseydonahue',
c143ddce
S
331 'uploader_id': 'caseydonahue',
332 'upload_date': '20090821',
333 'description': 'md5:bdbf314014e58713e6e5b66eb252f4a6',
334 },
335 'params': {
336 'skip_download': True,
337 },
338 'expected_warnings': ['Unable to download JSON metadata'],
339 },
f16f8505
S
340 {
341 # redirects to ondemand extractor and should be passed throught it
342 # for successful extraction
343 'url': 'https://vimeo.com/73445910',
344 'info_dict': {
345 'id': '73445910',
346 'ext': 'mp4',
347 'title': 'The Reluctant Revolutionary',
348 'uploader': '10Ft Films',
ec85ded8 349 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/tenfootfilms',
f16f8505
S
350 'uploader_id': 'tenfootfilms',
351 },
352 'params': {
353 'skip_download': True,
354 },
355 },
c143ddce
S
356 {
357 'url': 'http://vimeo.com/moogaloop.swf?clip_id=2539741',
358 'only_matching': True,
359 },
8bea039b
LL
360 {
361 'url': 'https://vimeo.com/109815029',
362 'note': 'Video not completely processed, "failed" seed status',
363 'only_matching': True,
364 },
6b7ceee1
S
365 {
366 'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
367 'only_matching': True,
368 },
c8e3e097
S
369 {
370 'url': 'https://vimeo.com/album/2632481/video/79010983',
371 'only_matching': True,
372 },
16f1131a
S
373 {
374 # source file returns 403: Forbidden
375 'url': 'https://vimeo.com/7809605',
376 'only_matching': True,
377 },
241a318f
S
378 {
379 'url': 'https://vimeo.com/160743502/abd0e13fb4',
380 'only_matching': True,
381 }
a91b954b 382 ]
b3d14cbf 383
d002e919
S
384 @staticmethod
385 def _smuggle_referrer(url, referrer_url):
386 return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
387
b407e173 388 @staticmethod
09b9c45e
S
389 def _extract_urls(url, webpage):
390 urls = []
b407e173 391 # Look for embedded (iframe) Vimeo player
09b9c45e 392 for mobj in re.finditer(
f475e881
S
393 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1',
394 webpage):
09b9c45e
S
395 urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
396 PLAIN_EMBED_RE = (
397 # Look for embedded (swf embed) Vimeo player
398 r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
399 # Look more for non-standard embedded Vimeo player
400 r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
401 )
402 for embed_re in PLAIN_EMBED_RE:
403 for mobj in re.finditer(embed_re, webpage):
404 urls.append(mobj.group('url'))
405 return urls
406
407 @staticmethod
408 def _extract_url(url, webpage):
409 urls = VimeoIE._extract_urls(url, webpage)
410 return urls[0] if urls else None
b407e173 411
0eecc6a4 412 def _verify_player_video_password(self, url, video_id):
d800609c 413 password = self._downloader.params.get('videopassword')
0eecc6a4
PH
414 if password is None:
415 raise ExtractorError('This video is protected by a password, use the --video-password option')
15707c7e 416 data = urlencode_postdata({'password': password})
0eecc6a4 417 pass_url = url + '/check-password'
67dda517 418 password_request = sanitized_Request(pass_url, data)
0eecc6a4 419 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
bdbb8530 420 password_request.add_header('Referer', url)
0eecc6a4
PH
421 return self._download_json(
422 password_request, video_id,
bdbb8530 423 'Verifying the password', 'Wrong password')
0eecc6a4 424
fc79158d
JMF
425 def _real_initialize(self):
426 self._login()
427
a0088bdf 428 def _real_extract(self, url):
5dbe81a1 429 url, data = unsmuggle_url(url, {})
0f56a4b4 430 headers = std_headers.copy()
5dbe81a1 431 if 'http_headers' in data:
5dbe81a1 432 headers.update(data['http_headers'])
ba5d51b3
PH
433 if 'Referer' not in headers:
434 headers['Referer'] = url
9d4660ca 435
b3d14cbf
PH
436 # Extract ID from URL
437 mobj = re.match(self._VALID_URL, url)
b3d14cbf 438 video_id = mobj.group('id')
58ea7ec8 439 orig_url = url
9103bbc5 440 if mobj.group('pro') or mobj.group('player'):
61e00a97 441 url = 'https://player.vimeo.com/video/' + video_id
c143ddce 442 elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
10831b5e 443 url = 'https://vimeo.com/' + video_id
b3d14cbf
PH
444
445 # Retrieve video webpage to extract further information
0f56a4b4 446 request = sanitized_Request(url, headers=headers)
1060425c 447 try:
f16f8505
S
448 webpage, urlh = self._download_webpage_handle(request, video_id)
449 # Some URLs redirect to ondemand can't be extracted with
450 # this extractor right away thus should be passed through
451 # ondemand extractor (e.g. https://vimeo.com/73445910)
452 if VimeoOndemandIE.suitable(urlh.geturl()):
453 return self.url_result(urlh.geturl(), VimeoOndemandIE.ie_key())
1060425c
PH
454 except ExtractorError as ee:
455 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
456 errmsg = ee.cause.read()
457 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
458 raise ExtractorError(
459 'Cannot download embed-only video without embedding '
460 'URL. Please call youtube-dl with the URL of the page '
461 'that embeds this video.',
462 expected=True)
463 raise
b3d14cbf
PH
464
465 # Now we begin extracting as much information as we can from what we
466 # retrieved. First we extract the information common to all extractors,
467 # and latter we extract those that are Vimeo specific.
468 self.report_extraction(video_id)
469
998e6cdb 470 vimeo_config = self._search_regex(
b6aa99af 471 r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
998e6cdb
S
472 'vimeo config', default=None)
473 if vimeo_config:
474 seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
475 if seed_status.get('state') == 'failed':
476 raise ExtractorError(
b6aa99af 477 '%s said: %s' % (self.IE_NAME, seed_status['title']),
998e6cdb
S
478 expected=True)
479
b3d14cbf
PH
480 # Extract the config JSON
481 try:
93b22c78
JMF
482 try:
483 config_url = self._html_search_regex(
41a7b00f
LL
484 r' data-config-url="(.+?)"', webpage,
485 'config URL', default=None)
486 if not config_url:
dd841752
S
487 # Sometimes new react-based page is served instead of old one that require
488 # different config URL extraction approach (see
489 # https://github.com/rg3/youtube-dl/pull/7209)
41a7b00f
LL
490 vimeo_clip_page_config = self._search_regex(
491 r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
492 'vimeo clip page config')
dd841752
S
493 config_url = self._parse_json(
494 vimeo_clip_page_config, video_id)['player']['config_url']
93b22c78
JMF
495 config_json = self._download_webpage(config_url, video_id)
496 config = json.loads(config_json)
497 except RegexNotFoundError:
498 # For pro videos or player.vimeo.com urls
48ad51b2 499 # We try to find out to which variable is assigned the config dic
ec85ded8 500 m_variable_name = re.search(r'(\w)\.video\.id', webpage)
48ad51b2 501 if m_variable_name is not None:
4698f0d8 502 config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
48ad51b2
JMF
503 else:
504 config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
9148eb00 505 config = self._search_regex(config_re, webpage, 'info section',
9e1a5b84 506 flags=re.DOTALL)
93b22c78 507 config = json.loads(config)
71907db3 508 except Exception as e:
b3d14cbf 509 if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
9148eb00 510 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
b3d14cbf 511
bf8f082a 512 if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
5dbe81a1 513 if '_video_password_verified' in data:
30965ac6 514 raise ExtractorError('video password verification failed!')
b3d14cbf 515 self._verify_video_password(url, video_id, webpage)
30965ac6
PH
516 return self._real_extract(
517 smuggle_url(url, {'_video_password_verified': 'verified'}))
b3d14cbf 518 else:
9148eb00 519 raise ExtractorError('Unable to extract info section',
71907db3 520 cause=e)
559e370f
PH
521 else:
522 if config.get('view') == 4:
0eecc6a4 523 config = self._verify_player_video_password(url, video_id)
b3d14cbf 524
6a55bb66
S
525 def is_rented():
526 if '>You rented this title.<' in webpage:
527 return True
528 if config.get('user', {}).get('purchased'):
529 return True
530 label = try_get(
531 config, lambda x: x['video']['vod']['purchase_options'][0]['label_string'], compat_str)
532 if label and label.startswith('You rented this'):
533 return True
534 return False
535
536 if is_rented():
5dbe81a1
S
537 feature_id = config.get('video', {}).get('vod', {}).get('feature_id')
538 if feature_id and not data.get('force_feature_id', False):
539 return self.url_result(smuggle_url(
540 'https://player.vimeo.com/player/%s' % feature_id,
541 {'force_feature_id': True}), 'Vimeo')
542
b3d14cbf 543 # Extract video description
58ea7ec8 544
25930395 545 video_description = self._html_search_regex(
58ea7ec8
PH
546 r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
547 webpage, 'description', default=None)
548 if not video_description:
549 video_description = self._html_search_meta(
550 'description', webpage, default=None)
551 if not video_description and mobj.group('pro'):
552 orig_webpage = self._download_webpage(
553 orig_url, video_id,
554 note='Downloading webpage for description',
555 fatal=False)
556 if orig_webpage:
557 video_description = self._html_search_meta(
558 'description', orig_webpage, default=None)
559 if not video_description and not mobj.group('player'):
560 self._downloader.report_warning('Cannot find video description')
b3d14cbf
PH
561
562 # Extract upload date
563 video_upload_date = None
3c6f2450 564 mobj = re.search(r'<time[^>]+datetime="([^"]+)"', webpage)
b3d14cbf 565 if mobj is not None:
3c6f2450 566 video_upload_date = unified_strdate(mobj.group(1))
b3d14cbf 567
4e761794 568 try:
9148eb00
PH
569 view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
570 like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
571 comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
4e761794
JMF
572 except RegexNotFoundError:
573 # This info is only available in vimeo.com/{id} urls
574 view_count = None
575 like_count = None
576 comment_count = None
577
a6387bfd 578 formats = []
eb4f2740 579 download_request = sanitized_Request('https://vimeo.com/%s?action=load_download_config' % video_id, headers={
580 'X-Requested-With': 'XMLHttpRequest'})
581 download_data = self._download_json(download_request, video_id, fatal=False)
582 if download_data:
583 source_file = download_data.get('source_file')
d5f071af
S
584 if isinstance(source_file, dict):
585 download_url = source_file.get('download_url')
586 if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
587 source_name = source_file.get('public_name', 'Original')
588 if self._is_valid_url(download_url, video_id, '%s video' % source_name):
4519c1f4 589 ext = source_file.get('extension', determine_ext(download_url)).lower()
d5f071af
S
590 formats.append({
591 'url': download_url,
592 'ext': ext,
593 'width': int_or_none(source_file.get('width')),
594 'height': int_or_none(source_file.get('height')),
595 'filesize': parse_filesize(source_file.get('size')),
596 'format_id': source_name,
597 'preference': 1,
598 })
1eac553e 599
531a7496
YCH
600 info_dict = self._parse_config(config, video_id)
601 formats.extend(info_dict['formats'])
602 self._vimeo_sort_formats(formats)
603 info_dict.update({
b0268cb6 604 'id': video_id,
531a7496 605 'formats': formats,
b0268cb6 606 'upload_date': video_upload_date,
b0268cb6 607 'description': video_description,
9103bbc5 608 'webpage_url': url,
4e761794
JMF
609 'view_count': view_count,
610 'like_count': like_count,
611 'comment_count': comment_count,
531a7496
YCH
612 })
613
614 return info_dict
caeefc29
JMF
615
616
74278def 617class VimeoOndemandIE(VimeoBaseInfoExtractor):
1e501364 618 IE_NAME = 'vimeo:ondemand'
74278def
S
619 _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
620 _TESTS = [{
621 # ondemand video not available via https://vimeo.com/id
622 'url': 'https://vimeo.com/ondemand/20704',
623 'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
624 'info_dict': {
625 'id': '105442900',
626 'ext': 'mp4',
627 'title': 'המעבדה - במאי יותם פלדמן',
628 'uploader': 'גם סרטים',
ec85ded8 629 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
74278def
S
630 'uploader_id': 'gumfilms',
631 },
d002e919
S
632 }, {
633 # requires Referer to be passed along with og:video:url
634 'url': 'https://vimeo.com/ondemand/36938/126682985',
635 'info_dict': {
636 'id': '126682985',
637 'ext': 'mp4',
638 'title': 'Rävlock, rätt läte på rätt plats',
639 'uploader': 'Lindroth & Norin',
ec85ded8 640 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
d002e919
S
641 'uploader_id': 'user14430847',
642 },
643 'params': {
644 'skip_download': True,
645 },
74278def
S
646 }, {
647 'url': 'https://vimeo.com/ondemand/nazmaalik',
648 'only_matching': True,
649 }, {
650 'url': 'https://vimeo.com/ondemand/141692381',
651 'only_matching': True,
652 }, {
653 'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
654 'only_matching': True,
655 }]
656
657 def _real_extract(self, url):
658 video_id = self._match_id(url)
659 webpage = self._download_webpage(url, video_id)
d002e919
S
660 return self.url_result(
661 # Some videos require Referer to be passed along with og:video:url
662 # similarly to generic vimeo embeds (e.g.
663 # https://vimeo.com/ondemand/36938/126682985).
664 VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
665 VimeoIE.ie_key())
74278def
S
666
667
f6c3664d 668class VimeoChannelIE(VimeoBaseInfoExtractor):
9148eb00 669 IE_NAME = 'vimeo:channel'
3946864c 670 _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
caeefc29 671 _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
84458766 672 _TITLE = None
55a10eab 673 _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
2929b3e7 674 _TESTS = [{
3946864c 675 'url': 'https://vimeo.com/channels/tributes',
2929b3e7 676 'info_dict': {
a3fa5da4 677 'id': 'tributes',
2929b3e7
PH
678 'title': 'Vimeo Tributes',
679 },
680 'playlist_mincount': 25,
681 }]
caeefc29 682
5cc14c2f
JMF
683 def _page_url(self, base_url, pagenum):
684 return '%s/videos/page:%d/' % (base_url, pagenum)
685
fb30ec22 686 def _extract_list_title(self, webpage):
84458766 687 return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
fb30ec22 688
bf8f082a
PH
689 def _login_list_password(self, page_url, list_id, webpage):
690 login_form = self._search_regex(
691 r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
692 webpage, 'login form', default=None)
693 if not login_form:
694 return webpage
695
d800609c 696 password = self._downloader.params.get('videopassword')
bf8f082a
PH
697 if password is None:
698 raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
f8da79f8 699 fields = self._hidden_inputs(login_form)
7c845629 700 token, vuid = self._extract_xsrft_and_vuid(webpage)
bf8f082a
PH
701 fields['token'] = token
702 fields['password'] = password
15707c7e 703 post = urlencode_postdata(fields)
bf8f082a
PH
704 password_path = self._search_regex(
705 r'action="([^"]+)"', login_form, 'password URL')
706 password_url = compat_urlparse.urljoin(page_url, password_path)
67dda517 707 password_request = sanitized_Request(password_url, post)
bf8f082a 708 password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
9eab37dc
S
709 self._set_vimeo_cookie('vuid', vuid)
710 self._set_vimeo_cookie('xsrft', token)
bf8f082a
PH
711
712 return self._download_webpage(
713 password_request, list_id,
714 'Verifying the password', 'Wrong password')
715
2c94198e 716 def _title_and_entries(self, list_id, base_url):
caeefc29 717 for pagenum in itertools.count(1):
bf8f082a 718 page_url = self._page_url(base_url, pagenum)
55a10eab 719 webpage = self._download_webpage(
bf8f082a 720 page_url, list_id,
9148eb00 721 'Downloading page %s' % pagenum)
bf8f082a
PH
722
723 if pagenum == 1:
724 webpage = self._login_list_password(page_url, list_id, webpage)
2c94198e
S
725 yield self._extract_list_title(webpage)
726
c8e3e097
S
727 # Try extracting href first since not all videos are available via
728 # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
729 clips = re.findall(
730 r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)', webpage)
731 if clips:
732 for video_id, video_url in clips:
733 yield self.url_result(
734 compat_urlparse.urljoin(base_url, video_url),
735 VimeoIE.ie_key(), video_id=video_id)
736 # More relaxed fallback
737 else:
738 for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
739 yield self.url_result(
740 'https://vimeo.com/%s' % video_id,
741 VimeoIE.ie_key(), video_id=video_id)
bf8f082a 742
caeefc29
JMF
743 if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
744 break
745
2c94198e
S
746 def _extract_videos(self, list_id, base_url):
747 title_and_entries = self._title_and_entries(list_id, base_url)
748 list_title = next(title_and_entries)
749 return self.playlist_result(title_and_entries, list_id, list_title)
55a10eab
JMF
750
751 def _real_extract(self, url):
752 mobj = re.match(self._VALID_URL, url)
4f3e9430 753 channel_id = mobj.group('id')
3946864c 754 return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
55a10eab
JMF
755
756
757class VimeoUserIE(VimeoChannelIE):
9148eb00 758 IE_NAME = 'vimeo:user'
b29440ae 759 _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
55a10eab 760 _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
2929b3e7 761 _TESTS = [{
3946864c 762 'url': 'https://vimeo.com/nkistudio/videos',
2929b3e7
PH
763 'info_dict': {
764 'title': 'Nki',
a3fa5da4 765 'id': 'nkistudio',
2929b3e7
PH
766 },
767 'playlist_mincount': 66,
768 }]
55a10eab
JMF
769
770 def _real_extract(self, url):
771 mobj = re.match(self._VALID_URL, url)
772 name = mobj.group('name')
3946864c 773 return self._extract_videos(name, 'https://vimeo.com/%s' % name)
5cc14c2f
JMF
774
775
776class VimeoAlbumIE(VimeoChannelIE):
9148eb00 777 IE_NAME = 'vimeo:album'
b5eab86c 778 _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
5cc14c2f 779 _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
2929b3e7 780 _TESTS = [{
d1508cd6 781 'url': 'https://vimeo.com/album/2632481',
2929b3e7 782 'info_dict': {
a3fa5da4 783 'id': '2632481',
2929b3e7
PH
784 'title': 'Staff Favorites: November 2013',
785 },
786 'playlist_mincount': 13,
bf8f082a
PH
787 }, {
788 'note': 'Password-protected album',
789 'url': 'https://vimeo.com/album/3253534',
790 'info_dict': {
791 'title': 'test',
792 'id': '3253534',
793 },
794 'playlist_count': 1,
795 'params': {
796 'videopassword': 'youtube-dl',
797 }
b5eab86c
S
798 }, {
799 'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
800 'only_matching': True,
089657ed
S
801 }, {
802 # TODO: respect page number
803 'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
804 'only_matching': True,
2929b3e7 805 }]
5cc14c2f
JMF
806
807 def _page_url(self, base_url, pagenum):
808 return '%s/page:%d/' % (base_url, pagenum)
809
810 def _real_extract(self, url):
bf8f082a 811 album_id = self._match_id(url)
d1508cd6 812 return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
fb30ec22
JMF
813
814
815class VimeoGroupsIE(VimeoAlbumIE):
9148eb00 816 IE_NAME = 'vimeo:group'
fdb20a27 817 _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
2929b3e7 818 _TESTS = [{
3946864c 819 'url': 'https://vimeo.com/groups/rolexawards',
2929b3e7 820 'info_dict': {
a3fa5da4 821 'id': 'rolexawards',
2929b3e7
PH
822 'title': 'Rolex Awards for Enterprise',
823 },
824 'playlist_mincount': 73,
825 }]
fb30ec22
JMF
826
827 def _extract_list_title(self, webpage):
828 return self._og_search_title(webpage)
829
830 def _real_extract(self, url):
831 mobj = re.match(self._VALID_URL, url)
832 name = mobj.group('name')
3946864c 833 return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
fcea44c6
PH
834
835
531a7496 836class VimeoReviewIE(VimeoBaseInfoExtractor):
9148eb00
PH
837 IE_NAME = 'vimeo:review'
838 IE_DESC = 'Review pages on vimeo'
3946864c 839 _VALID_URL = r'https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
d36d3f42 840 _TESTS = [{
fcea44c6 841 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
fcea44c6
PH
842 'md5': 'c507a72f780cacc12b2248bb4006d253',
843 'info_dict': {
fc09240e
PH
844 'id': '75524534',
845 'ext': 'mp4',
fcea44c6
PH
846 'title': "DICK HARDWICK 'Comedian'",
847 'uploader': 'Richard Hardwick',
531a7496 848 'uploader_id': 'user21297594',
fcea44c6 849 }
d36d3f42
PH
850 }, {
851 'note': 'video player needs Referer',
3946864c 852 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
d36d3f42
PH
853 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
854 'info_dict': {
855 'id': '91613211',
856 'ext': 'mp4',
9dec9930 857 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
d36d3f42
PH
858 'uploader': 'DevWeek Events',
859 'duration': 2773,
ec85ded8 860 'thumbnail': r're:^https?://.*\.jpg$',
531a7496 861 'uploader_id': 'user22258446',
d36d3f42 862 }
c1ff6e1a
YCH
863 }, {
864 'note': 'Password protected',
865 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
866 'info_dict': {
867 'id': '138823582',
868 'ext': 'mp4',
869 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
870 'uploader': 'TMB',
871 'uploader_id': 'user37284429',
872 },
873 'params': {
874 'videopassword': 'holygrail',
875 },
a093cfc7 876 'skip': 'video gone',
d36d3f42 877 }]
fcea44c6 878
c1ff6e1a
YCH
879 def _real_initialize(self):
880 self._login()
881
882 def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
883 webpage = self._download_webpage(webpage_url, video_id)
a093cfc7
YCH
884 data = self._parse_json(self._search_regex(
885 r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
886 default=NO_DEFAULT if video_password_verified else '{}'), video_id)
887 config_url = data.get('vimeo_esi', {}).get('config', {}).get('configUrl')
c1ff6e1a
YCH
888 if config_url is None:
889 self._verify_video_password(webpage_url, video_id, webpage)
890 config_url = self._get_config_url(
891 webpage_url, video_id, video_password_verified=True)
892 return config_url
893
fcea44c6 894 def _real_extract(self, url):
531a7496 895 video_id = self._match_id(url)
c1ff6e1a
YCH
896 config_url = self._get_config_url(url, video_id)
897 config = self._download_json(config_url, video_id)
531a7496
YCH
898 info_dict = self._parse_config(config, video_id)
899 self._vimeo_sort_formats(info_dict['formats'])
900 info_dict['id'] = video_id
901 return info_dict
efb7e119
JMF
902
903
f6c3664d 904class VimeoWatchLaterIE(VimeoChannelIE):
efb7e119
JMF
905 IE_NAME = 'vimeo:watchlater'
906 IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
84458766
S
907 _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
908 _TITLE = 'Watch Later'
efb7e119 909 _LOGIN_REQUIRED = True
2929b3e7 910 _TESTS = [{
84458766 911 'url': 'https://vimeo.com/watchlater',
2929b3e7
PH
912 'only_matching': True,
913 }]
efb7e119
JMF
914
915 def _real_initialize(self):
916 self._login()
917
918 def _page_url(self, base_url, pagenum):
919 url = '%s/page:%d/' % (base_url, pagenum)
67dda517 920 request = sanitized_Request(url)
efb7e119
JMF
921 # Set the header to get a partial html page with the ids,
922 # the normal page doesn't contain them.
923 request.add_header('X-Requested-With', 'XMLHttpRequest')
924 return request
925
926 def _real_extract(self, url):
84458766 927 return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
d6e6a422
PH
928
929
930class VimeoLikesIE(InfoExtractor):
3946864c 931 _VALID_URL = r'https://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
d6e6a422
PH
932 IE_NAME = 'vimeo:likes'
933 IE_DESC = 'Vimeo user likes'
934 _TEST = {
9c44d242
PH
935 'url': 'https://vimeo.com/user755559/likes/',
936 'playlist_mincount': 293,
611c1dd9 937 'info_dict': {
a3fa5da4 938 'id': 'user755559_likes',
611c1dd9
S
939 'description': 'See all the videos urza likes',
940 'title': 'Videos urza likes',
d6e6a422
PH
941 },
942 }
943
944 def _real_extract(self, url):
945 user_id = self._match_id(url)
9c44d242
PH
946 webpage = self._download_webpage(url, user_id)
947 page_count = self._int(
948 self._search_regex(
949 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
950 .*?</a></li>\s*<li\s+class="pagination_next">
951 ''', webpage, 'page count'),
952 'page count', fatal=True)
953 PAGE_SIZE = 12
954 title = self._html_search_regex(
955 r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
956 description = self._html_search_meta('description', webpage)
957
958 def _get_page(idx):
3946864c
JMF
959 page_url = 'https://vimeo.com/user%s/likes/page:%d/sort:date' % (
960 user_id, idx + 1)
9c44d242
PH
961 webpage = self._download_webpage(
962 page_url, user_id,
963 note='Downloading page %d/%d' % (idx + 1, page_count))
964 video_list = self._search_regex(
965 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
966 webpage, 'video content')
967 paths = re.findall(
968 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
969 for path in paths:
970 yield {
971 '_type': 'url',
972 'url': compat_urlparse.urljoin(page_url, path),
973 }
974
975 pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
d6e6a422
PH
976
977 return {
9c44d242
PH
978 '_type': 'playlist',
979 'id': 'user%s_likes' % user_id,
980 'title': title,
981 'description': description,
982 'entries': pl,
d6e6a422 983 }