]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/vimeo.py
Update to ytdl-2021.01.03
[yt-dlp.git] / youtube_dlc / extractor / vimeo.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import functools
6 import json
7 import re
8 import itertools
9
10 from .common import InfoExtractor
11 from ..compat import (
12 compat_kwargs,
13 compat_HTTPError,
14 compat_str,
15 compat_urlparse,
16 )
17 from ..utils import (
18 clean_html,
19 determine_ext,
20 dict_get,
21 ExtractorError,
22 js_to_json,
23 int_or_none,
24 merge_dicts,
25 OnDemandPagedList,
26 parse_filesize,
27 RegexNotFoundError,
28 sanitized_Request,
29 smuggle_url,
30 std_headers,
31 str_or_none,
32 try_get,
33 unified_timestamp,
34 unsmuggle_url,
35 urlencode_postdata,
36 urljoin,
37 unescapeHTML,
38 )
39
40
41 class VimeoBaseInfoExtractor(InfoExtractor):
42 _NETRC_MACHINE = 'vimeo'
43 _LOGIN_REQUIRED = False
44 _LOGIN_URL = 'https://vimeo.com/log_in'
45
46 def _login(self):
47 username, password = self._get_login_info()
48 if username is None:
49 if self._LOGIN_REQUIRED:
50 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
51 return
52 webpage = self._download_webpage(
53 self._LOGIN_URL, None, 'Downloading login page')
54 token, vuid = self._extract_xsrft_and_vuid(webpage)
55 data = {
56 'action': 'login',
57 'email': username,
58 'password': password,
59 'service': 'vimeo',
60 'token': token,
61 }
62 self._set_vimeo_cookie('vuid', vuid)
63 try:
64 self._download_webpage(
65 self._LOGIN_URL, None, 'Logging in',
66 data=urlencode_postdata(data), headers={
67 'Content-Type': 'application/x-www-form-urlencoded',
68 'Referer': self._LOGIN_URL,
69 })
70 except ExtractorError as e:
71 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 418:
72 raise ExtractorError(
73 'Unable to log in: bad username or password',
74 expected=True)
75 raise ExtractorError('Unable to log in')
76
77 def _verify_video_password(self, url, video_id, webpage):
78 password = self._downloader.params.get('videopassword')
79 if password is None:
80 raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
81 token, vuid = self._extract_xsrft_and_vuid(webpage)
82 data = urlencode_postdata({
83 'password': password,
84 'token': token,
85 })
86 if url.startswith('http://'):
87 # vimeo only supports https now, but the user can give an http url
88 url = url.replace('http://', 'https://')
89 password_request = sanitized_Request(url + '/password', data)
90 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
91 password_request.add_header('Referer', url)
92 self._set_vimeo_cookie('vuid', vuid)
93 return self._download_webpage(
94 password_request, video_id,
95 'Verifying the password', 'Wrong password')
96
97 def _extract_xsrft_and_vuid(self, webpage):
98 xsrft = self._search_regex(
99 r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
100 webpage, 'login token', group='xsrft')
101 vuid = self._search_regex(
102 r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
103 webpage, 'vuid', group='vuid')
104 return xsrft, vuid
105
106 def _extract_vimeo_config(self, webpage, video_id, *args, **kwargs):
107 vimeo_config = self._search_regex(
108 r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));',
109 webpage, 'vimeo config', *args, **compat_kwargs(kwargs))
110 if vimeo_config:
111 return self._parse_json(vimeo_config, video_id)
112
113 def _set_vimeo_cookie(self, name, value):
114 self._set_cookie('vimeo.com', name, value)
115
116 def _vimeo_sort_formats(self, formats):
117 # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
118 # at the same time without actual units specified. This lead to wrong sorting.
119 self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
120
121 def _parse_config(self, config, video_id):
122 video_data = config['video']
123 video_title = video_data['title']
124 live_event = video_data.get('live_event') or {}
125 is_live = live_event.get('status') == 'started'
126
127 formats = []
128 config_files = video_data.get('files') or config['request'].get('files', {})
129 for f in config_files.get('progressive', []):
130 video_url = f.get('url')
131 if not video_url:
132 continue
133 formats.append({
134 'url': video_url,
135 'format_id': 'http-%s' % f.get('quality'),
136 'width': int_or_none(f.get('width')),
137 'height': int_or_none(f.get('height')),
138 'fps': int_or_none(f.get('fps')),
139 'tbr': int_or_none(f.get('bitrate')),
140 })
141
142 # TODO: fix handling of 308 status code returned for live archive manifest requests
143 sep_pattern = r'/sep/video/'
144 for files_type in ('hls', 'dash'):
145 for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
146 manifest_url = cdn_data.get('url')
147 if not manifest_url:
148 continue
149 format_id = '%s-%s' % (files_type, cdn_name)
150 sep_manifest_urls = []
151 if re.search(sep_pattern, manifest_url):
152 for suffix, repl in (('', 'video'), ('_sep', 'sep/video')):
153 sep_manifest_urls.append((format_id + suffix, re.sub(
154 sep_pattern, '/%s/' % repl, manifest_url)))
155 else:
156 sep_manifest_urls = [(format_id, manifest_url)]
157 for f_id, m_url in sep_manifest_urls:
158 if files_type == 'hls':
159 formats.extend(self._extract_m3u8_formats(
160 m_url, video_id, 'mp4',
161 'm3u8' if is_live else 'm3u8_native', m3u8_id=f_id,
162 note='Downloading %s m3u8 information' % cdn_name,
163 fatal=False))
164 elif files_type == 'dash':
165 if 'json=1' in m_url:
166 real_m_url = (self._download_json(m_url, video_id, fatal=False) or {}).get('url')
167 if real_m_url:
168 m_url = real_m_url
169 mpd_formats = self._extract_mpd_formats(
170 m_url.replace('/master.json', '/master.mpd'), video_id, f_id,
171 'Downloading %s MPD information' % cdn_name,
172 fatal=False)
173 formats.extend(mpd_formats)
174
175 live_archive = live_event.get('archive') or {}
176 live_archive_source_url = live_archive.get('source_url')
177 if live_archive_source_url and live_archive.get('status') == 'done':
178 formats.append({
179 'format_id': 'live-archive-source',
180 'url': live_archive_source_url,
181 'preference': 1,
182 })
183
184 # Reduntant code! This is already done in common.py
185 # for f in formats:
186 # if f.get('vcodec') == 'none':
187 # f['preference'] = -50
188 # elif f.get('acodec') == 'none':
189 # f['preference'] = -40
190
191 subtitles = {}
192 text_tracks = config['request'].get('text_tracks')
193 if text_tracks:
194 for tt in text_tracks:
195 subtitles[tt['lang']] = [{
196 'ext': 'vtt',
197 'url': urljoin('https://vimeo.com', tt['url']),
198 }]
199
200 thumbnails = []
201 if not is_live:
202 for key, thumb in video_data.get('thumbs', {}).items():
203 thumbnails.append({
204 'id': key,
205 'width': int_or_none(key),
206 'url': thumb,
207 })
208 thumbnail = video_data.get('thumbnail')
209 if thumbnail:
210 thumbnails.append({
211 'url': thumbnail,
212 })
213
214 owner = video_data.get('owner') or {}
215 video_uploader_url = owner.get('url')
216
217 return {
218 'id': str_or_none(video_data.get('id')) or video_id,
219 'title': self._live_title(video_title) if is_live else video_title,
220 'uploader': owner.get('name'),
221 'uploader_id': video_uploader_url.split('/')[-1] if video_uploader_url else None,
222 'uploader_url': video_uploader_url,
223 'thumbnails': thumbnails,
224 'duration': int_or_none(video_data.get('duration')),
225 'formats': formats,
226 'subtitles': subtitles,
227 'is_live': is_live,
228 }
229
230 def _extract_original_format(self, url, video_id):
231 download_data = self._download_json(
232 url, video_id, fatal=False,
233 query={'action': 'load_download_config'},
234 headers={'X-Requested-With': 'XMLHttpRequest'})
235 if download_data:
236 source_file = download_data.get('source_file')
237 if isinstance(source_file, dict):
238 download_url = source_file.get('download_url')
239 if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
240 source_name = source_file.get('public_name', 'Original')
241 if self._is_valid_url(download_url, video_id, '%s video' % source_name):
242 ext = (try_get(
243 source_file, lambda x: x['extension'],
244 compat_str) or determine_ext(
245 download_url, None) or 'mp4').lower()
246 return {
247 'url': download_url,
248 'ext': ext,
249 'width': int_or_none(source_file.get('width')),
250 'height': int_or_none(source_file.get('height')),
251 'filesize': parse_filesize(source_file.get('size')),
252 'format_id': source_name,
253 'preference': 1,
254 }
255
256
257 class VimeoIE(VimeoBaseInfoExtractor):
258 """Information extractor for vimeo.com."""
259
260 # _VALID_URL matches Vimeo URLs
261 _VALID_URL = r'''(?x)
262 https?://
263 (?:
264 (?:
265 www|
266 player
267 )
268 \.
269 )?
270 vimeo(?:pro)?\.com/
271 (?!(?:channels|album|showcase)/[^/?#]+/?(?:$|[?#])|[^/]+/review/|ondemand/)
272 (?:.*?/)?
273 (?:
274 (?:
275 play_redirect_hls|
276 moogaloop\.swf)\?clip_id=
277 )?
278 (?:videos?/)?
279 (?P<id>[0-9]+)
280 (?:/[\da-f]+)?
281 /?(?:[?&].*)?(?:[#].*)?$
282 '''
283 IE_NAME = 'vimeo'
284 _TESTS = [
285 {
286 'url': 'http://vimeo.com/56015672#at=0',
287 'md5': '8879b6cc097e987f02484baf890129e5',
288 'info_dict': {
289 'id': '56015672',
290 'ext': 'mp4',
291 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
292 'description': 'md5:2d3305bad981a06ff79f027f19865021',
293 'timestamp': 1355990239,
294 'upload_date': '20121220',
295 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user7108434',
296 'uploader_id': 'user7108434',
297 'uploader': 'Filippo Valsorda',
298 'duration': 10,
299 'license': 'by-sa',
300 },
301 'params': {
302 'format': 'best[protocol=https]',
303 },
304 },
305 {
306 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
307 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
308 'note': 'Vimeo Pro video (#1197)',
309 'info_dict': {
310 'id': '68093876',
311 'ext': 'mp4',
312 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
313 'uploader_id': 'openstreetmapus',
314 'uploader': 'OpenStreetMap US',
315 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
316 'description': 'md5:2c362968038d4499f4d79f88458590c1',
317 'duration': 1595,
318 'upload_date': '20130610',
319 'timestamp': 1370893156,
320 },
321 'params': {
322 'format': 'best[protocol=https]',
323 },
324 },
325 {
326 'url': 'http://player.vimeo.com/video/54469442',
327 'md5': '619b811a4417aa4abe78dc653becf511',
328 'note': 'Videos that embed the url in the player page',
329 'info_dict': {
330 'id': '54469442',
331 'ext': 'mp4',
332 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
333 'uploader': 'The BLN & Business of Software',
334 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
335 'uploader_id': 'theblnbusinessofsoftware',
336 'duration': 3610,
337 'description': None,
338 },
339 'params': {
340 'format': 'best[protocol=https]',
341 },
342 'expected_warnings': ['Unable to download JSON metadata'],
343 },
344 {
345 'url': 'http://vimeo.com/68375962',
346 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
347 'note': 'Video protected with password',
348 'info_dict': {
349 'id': '68375962',
350 'ext': 'mp4',
351 'title': 'youtube-dl password protected test video',
352 'timestamp': 1371200155,
353 'upload_date': '20130614',
354 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
355 'uploader_id': 'user18948128',
356 'uploader': 'Jaime Marquínez Ferrándiz',
357 'duration': 10,
358 'description': 'md5:dca3ea23adb29ee387127bc4ddfce63f',
359 },
360 'params': {
361 'format': 'best[protocol=https]',
362 'videopassword': 'youtube-dl',
363 },
364 },
365 {
366 'url': 'http://vimeo.com/channels/keypeele/75629013',
367 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
368 'info_dict': {
369 'id': '75629013',
370 'ext': 'mp4',
371 'title': 'Key & Peele: Terrorist Interrogation',
372 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
373 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/atencio',
374 'uploader_id': 'atencio',
375 'uploader': 'Peter Atencio',
376 'channel_id': 'keypeele',
377 'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/keypeele',
378 'timestamp': 1380339469,
379 'upload_date': '20130928',
380 'duration': 187,
381 },
382 'expected_warnings': ['Unable to download JSON metadata'],
383 },
384 {
385 'url': 'http://vimeo.com/76979871',
386 'note': 'Video with subtitles',
387 'info_dict': {
388 'id': '76979871',
389 'ext': 'mp4',
390 'title': 'The New Vimeo Player (You Know, For Videos)',
391 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
392 'timestamp': 1381846109,
393 'upload_date': '20131015',
394 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/staff',
395 'uploader_id': 'staff',
396 'uploader': 'Vimeo Staff',
397 'duration': 62,
398 }
399 },
400 {
401 # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
402 'url': 'https://player.vimeo.com/video/98044508',
403 'note': 'The js code contains assignments to the same variable as the config',
404 'info_dict': {
405 'id': '98044508',
406 'ext': 'mp4',
407 'title': 'Pier Solar OUYA Official Trailer',
408 'uploader': 'Tulio Gonçalves',
409 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user28849593',
410 'uploader_id': 'user28849593',
411 },
412 },
413 {
414 # contains original format
415 'url': 'https://vimeo.com/33951933',
416 'md5': '53c688fa95a55bf4b7293d37a89c5c53',
417 'info_dict': {
418 'id': '33951933',
419 'ext': 'mp4',
420 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
421 'uploader': 'The DMCI',
422 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/dmci',
423 'uploader_id': 'dmci',
424 'timestamp': 1324343742,
425 'upload_date': '20111220',
426 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
427 },
428 },
429 {
430 # only available via https://vimeo.com/channels/tributes/6213729 and
431 # not via https://vimeo.com/6213729
432 'url': 'https://vimeo.com/channels/tributes/6213729',
433 'info_dict': {
434 'id': '6213729',
435 'ext': 'mp4',
436 'title': 'Vimeo Tribute: The Shining',
437 'uploader': 'Casey Donahue',
438 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/caseydonahue',
439 'uploader_id': 'caseydonahue',
440 'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/tributes',
441 'channel_id': 'tributes',
442 'timestamp': 1250886430,
443 'upload_date': '20090821',
444 'description': 'md5:bdbf314014e58713e6e5b66eb252f4a6',
445 },
446 'params': {
447 'skip_download': True,
448 },
449 'expected_warnings': ['Unable to download JSON metadata'],
450 },
451 {
452 # redirects to ondemand extractor and should be passed through it
453 # for successful extraction
454 'url': 'https://vimeo.com/73445910',
455 'info_dict': {
456 'id': '73445910',
457 'ext': 'mp4',
458 'title': 'The Reluctant Revolutionary',
459 'uploader': '10Ft Films',
460 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/tenfootfilms',
461 'uploader_id': 'tenfootfilms',
462 'description': 'md5:0fa704e05b04f91f40b7f3ca2e801384',
463 'upload_date': '20130830',
464 'timestamp': 1377853339,
465 },
466 'params': {
467 'skip_download': True,
468 },
469 'expected_warnings': ['Unable to download JSON metadata'],
470 },
471 {
472 'url': 'http://player.vimeo.com/video/68375962',
473 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
474 'info_dict': {
475 'id': '68375962',
476 'ext': 'mp4',
477 'title': 'youtube-dl password protected test video',
478 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
479 'uploader_id': 'user18948128',
480 'uploader': 'Jaime Marquínez Ferrándiz',
481 'duration': 10,
482 },
483 'params': {
484 'format': 'best[protocol=https]',
485 'videopassword': 'youtube-dl',
486 },
487 },
488 {
489 'url': 'http://vimeo.com/moogaloop.swf?clip_id=2539741',
490 'only_matching': True,
491 },
492 {
493 'url': 'https://vimeo.com/109815029',
494 'note': 'Video not completely processed, "failed" seed status',
495 'only_matching': True,
496 },
497 {
498 'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
499 'only_matching': True,
500 },
501 {
502 'url': 'https://vimeo.com/album/2632481/video/79010983',
503 'only_matching': True,
504 },
505 {
506 # source file returns 403: Forbidden
507 'url': 'https://vimeo.com/7809605',
508 'only_matching': True,
509 },
510 {
511 'url': 'https://vimeo.com/160743502/abd0e13fb4',
512 'only_matching': True,
513 }
514 # https://gettingthingsdone.com/workflowmap/
515 # vimeo embed with check-password page protected by Referer header
516 ]
517
518 @staticmethod
519 def _smuggle_referrer(url, referrer_url):
520 return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
521
522 @staticmethod
523 def _extract_urls(url, webpage):
524 urls = []
525 # Look for embedded (iframe) Vimeo player
526 for mobj in re.finditer(
527 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/\d+.*?)\1',
528 webpage):
529 urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
530 PLAIN_EMBED_RE = (
531 # Look for embedded (swf embed) Vimeo player
532 r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
533 # Look more for non-standard embedded Vimeo player
534 r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
535 )
536 for embed_re in PLAIN_EMBED_RE:
537 for mobj in re.finditer(embed_re, webpage):
538 urls.append(mobj.group('url'))
539 return urls
540
541 @staticmethod
542 def _extract_url(url, webpage):
543 urls = VimeoIE._extract_urls(url, webpage)
544 return urls[0] if urls else None
545
546 def _verify_player_video_password(self, url, video_id, headers):
547 password = self._downloader.params.get('videopassword')
548 if password is None:
549 raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
550 data = urlencode_postdata({
551 'password': base64.b64encode(password.encode()),
552 })
553 headers = merge_dicts(headers, {
554 'Content-Type': 'application/x-www-form-urlencoded',
555 })
556 checked = self._download_json(
557 url + '/check-password', video_id,
558 'Verifying the password', data=data, headers=headers)
559 if checked is False:
560 raise ExtractorError('Wrong video password', expected=True)
561 return checked
562
563 def _real_initialize(self):
564 self._login()
565
566 def _real_extract(self, url):
567 url, data = unsmuggle_url(url, {})
568 headers = std_headers.copy()
569 if 'http_headers' in data:
570 headers.update(data['http_headers'])
571 if 'Referer' not in headers:
572 headers['Referer'] = url
573
574 channel_id = self._search_regex(
575 r'vimeo\.com/channels/([^/]+)', url, 'channel id', default=None)
576
577 # Extract ID from URL
578 video_id = self._match_id(url)
579 orig_url = url
580 is_pro = 'vimeopro.com/' in url
581 is_player = '://player.vimeo.com/video/' in url
582 if is_pro:
583 # some videos require portfolio_id to be present in player url
584 # https://github.com/ytdl-org/youtube-dl/issues/20070
585 url = self._extract_url(url, self._download_webpage(url, video_id))
586 if not url:
587 url = 'https://vimeo.com/' + video_id
588 elif is_player:
589 url = 'https://player.vimeo.com/video/' + video_id
590 elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
591 url = 'https://vimeo.com/' + video_id
592
593 try:
594 # Retrieve video webpage to extract further information
595 webpage, urlh = self._download_webpage_handle(
596 url, video_id, headers=headers)
597 redirect_url = urlh.geturl()
598 except ExtractorError as ee:
599 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
600 errmsg = ee.cause.read()
601 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
602 raise ExtractorError(
603 'Cannot download embed-only video without embedding '
604 'URL. Please call youtube-dlc with the URL of the page '
605 'that embeds this video.',
606 expected=True)
607 raise
608
609 # Now we begin extracting as much information as we can from what we
610 # retrieved. First we extract the information common to all extractors,
611 # and latter we extract those that are Vimeo specific.
612 self.report_extraction(video_id)
613
614 vimeo_config = self._extract_vimeo_config(webpage, video_id, default=None)
615 if vimeo_config:
616 seed_status = vimeo_config.get('seed_status', {})
617 if seed_status.get('state') == 'failed':
618 raise ExtractorError(
619 '%s said: %s' % (self.IE_NAME, seed_status['title']),
620 expected=True)
621
622 cc_license = None
623 timestamp = None
624 video_description = None
625
626 # Extract the config JSON
627 try:
628 try:
629 config_url = self._html_search_regex(
630 r' data-config-url="(.+?)"', webpage,
631 'config URL', default=None)
632 if not config_url:
633 # Sometimes new react-based page is served instead of old one that require
634 # different config URL extraction approach (see
635 # https://github.com/ytdl-org/youtube-dl/pull/7209)
636 page_config = self._parse_json(self._search_regex(
637 r'vimeo\.(?:clip|vod_title)_page_config\s*=\s*({.+?});',
638 webpage, 'page config'), video_id)
639 config_url = page_config['player']['config_url']
640 cc_license = page_config.get('cc_license')
641 timestamp = try_get(
642 page_config, lambda x: x['clip']['uploaded_on'],
643 compat_str)
644 video_description = clean_html(dict_get(
645 page_config, ('description', 'description_html_escaped')))
646 config = self._download_json(config_url, video_id)
647 except RegexNotFoundError:
648 # For pro videos or player.vimeo.com urls
649 # We try to find out to which variable is assigned the config dic
650 m_variable_name = re.search(r'(\w)\.video\.id', webpage)
651 if m_variable_name is not None:
652 config_re = [r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))]
653 else:
654 config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
655 config_re.append(r'\bvar\s+r\s*=\s*({.+?})\s*;')
656 config_re.append(r'\bconfig\s*=\s*({.+?})\s*;')
657 config = self._search_regex(config_re, webpage, 'info section',
658 flags=re.DOTALL)
659 config = json.loads(config)
660 except Exception as e:
661 if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
662 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
663
664 if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
665 if '_video_password_verified' in data:
666 raise ExtractorError('video password verification failed!')
667 self._verify_video_password(redirect_url, video_id, webpage)
668 return self._real_extract(
669 smuggle_url(redirect_url, {'_video_password_verified': 'verified'}))
670 else:
671 raise ExtractorError('Unable to extract info section',
672 cause=e)
673 else:
674 if config.get('view') == 4:
675 config = self._verify_player_video_password(redirect_url, video_id, headers)
676
677 vod = config.get('video', {}).get('vod', {})
678
679 def is_rented():
680 if '>You rented this title.<' in webpage:
681 return True
682 if config.get('user', {}).get('purchased'):
683 return True
684 for purchase_option in vod.get('purchase_options', []):
685 if purchase_option.get('purchased'):
686 return True
687 label = purchase_option.get('label_string')
688 if label and (label.startswith('You rented this') or label.endswith(' remaining')):
689 return True
690 return False
691
692 if is_rented() and vod.get('is_trailer'):
693 feature_id = vod.get('feature_id')
694 if feature_id and not data.get('force_feature_id', False):
695 return self.url_result(smuggle_url(
696 'https://player.vimeo.com/player/%s' % feature_id,
697 {'force_feature_id': True}), 'Vimeo')
698
699 # Extract video description
700 if not video_description:
701 video_description = self._html_search_regex(
702 r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
703 webpage, 'description', default=None)
704 if not video_description:
705 video_description = self._html_search_meta(
706 'description', webpage, default=None)
707 if not video_description and is_pro:
708 orig_webpage = self._download_webpage(
709 orig_url, video_id,
710 note='Downloading webpage for description',
711 fatal=False)
712 if orig_webpage:
713 video_description = self._html_search_meta(
714 'description', orig_webpage, default=None)
715 if not video_description and not is_player:
716 self._downloader.report_warning('Cannot find video description')
717
718 # Extract upload date
719 if not timestamp:
720 timestamp = self._search_regex(
721 r'<time[^>]+datetime="([^"]+)"', webpage,
722 'timestamp', default=None)
723
724 try:
725 view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
726 like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
727 comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
728 except RegexNotFoundError:
729 # This info is only available in vimeo.com/{id} urls
730 view_count = None
731 like_count = None
732 comment_count = None
733
734 formats = []
735
736 source_format = self._extract_original_format(
737 'https://vimeo.com/' + video_id, video_id)
738 if source_format:
739 formats.append(source_format)
740
741 info_dict_config = self._parse_config(config, video_id)
742 formats.extend(info_dict_config['formats'])
743 self._vimeo_sort_formats(formats)
744
745 json_ld = self._search_json_ld(webpage, video_id, default={})
746
747 if not cc_license:
748 cc_license = self._search_regex(
749 r'<link[^>]+rel=["\']license["\'][^>]+href=(["\'])(?P<license>(?:(?!\1).)+)\1',
750 webpage, 'license', default=None, group='license')
751
752 channel_url = 'https://vimeo.com/channels/%s' % channel_id if channel_id else None
753
754 info_dict = {
755 'formats': formats,
756 'timestamp': unified_timestamp(timestamp),
757 'description': video_description,
758 'webpage_url': url,
759 'view_count': view_count,
760 'like_count': like_count,
761 'comment_count': comment_count,
762 'license': cc_license,
763 'channel_id': channel_id,
764 'channel_url': channel_url,
765 }
766
767 info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
768
769 return info_dict
770
771
772 class VimeoOndemandIE(VimeoIE):
773 IE_NAME = 'vimeo:ondemand'
774 _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/([^/]+/)?(?P<id>[^/?#&]+)'
775 _TESTS = [{
776 # ondemand video not available via https://vimeo.com/id
777 'url': 'https://vimeo.com/ondemand/20704',
778 'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
779 'info_dict': {
780 'id': '105442900',
781 'ext': 'mp4',
782 'title': 'המעבדה - במאי יותם פלדמן',
783 'uploader': 'גם סרטים',
784 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
785 'uploader_id': 'gumfilms',
786 'description': 'md5:4c027c965e439de4baab621e48b60791',
787 'upload_date': '20140906',
788 'timestamp': 1410032453,
789 },
790 'params': {
791 'format': 'best[protocol=https]',
792 },
793 'expected_warnings': ['Unable to download JSON metadata'],
794 }, {
795 # requires Referer to be passed along with og:video:url
796 'url': 'https://vimeo.com/ondemand/36938/126682985',
797 'info_dict': {
798 'id': '126584684',
799 'ext': 'mp4',
800 'title': 'Rävlock, rätt läte på rätt plats',
801 'uploader': 'Lindroth & Norin',
802 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/lindrothnorin',
803 'uploader_id': 'lindrothnorin',
804 'description': 'md5:c3c46a90529612c8279fb6af803fc0df',
805 'upload_date': '20150502',
806 'timestamp': 1430586422,
807 },
808 'params': {
809 'skip_download': True,
810 },
811 'expected_warnings': ['Unable to download JSON metadata'],
812 }, {
813 'url': 'https://vimeo.com/ondemand/nazmaalik',
814 'only_matching': True,
815 }, {
816 'url': 'https://vimeo.com/ondemand/141692381',
817 'only_matching': True,
818 }, {
819 'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
820 'only_matching': True,
821 }]
822
823
824 class VimeoChannelIE(VimeoBaseInfoExtractor):
825 IE_NAME = 'vimeo:channel'
826 _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
827 _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
828 _TITLE = None
829 _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
830 _TESTS = [{
831 'url': 'https://vimeo.com/channels/tributes',
832 'info_dict': {
833 'id': 'tributes',
834 'title': 'Vimeo Tributes',
835 },
836 'playlist_mincount': 25,
837 }]
838 _BASE_URL_TEMPL = 'https://vimeo.com/channels/%s'
839
840 def _page_url(self, base_url, pagenum):
841 return '%s/videos/page:%d/' % (base_url, pagenum)
842
843 def _extract_list_title(self, webpage):
844 return self._TITLE or self._html_search_regex(
845 self._TITLE_RE, webpage, 'list title', fatal=False)
846
847 def _title_and_entries(self, list_id, base_url):
848 for pagenum in itertools.count(1):
849 page_url = self._page_url(base_url, pagenum)
850 webpage = self._download_webpage(
851 page_url, list_id,
852 'Downloading page %s' % pagenum)
853
854 if pagenum == 1:
855 yield self._extract_list_title(webpage)
856
857 # Try extracting href first since not all videos are available via
858 # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
859 clips = re.findall(
860 r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
861 if clips:
862 for video_id, video_url, video_title in clips:
863 yield self.url_result(
864 compat_urlparse.urljoin(base_url, video_url),
865 VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
866 # More relaxed fallback
867 else:
868 for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
869 yield self.url_result(
870 'https://vimeo.com/%s' % video_id,
871 VimeoIE.ie_key(), video_id=video_id)
872
873 if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
874 break
875
876 def _extract_videos(self, list_id, base_url):
877 title_and_entries = self._title_and_entries(list_id, base_url)
878 list_title = next(title_and_entries)
879 return self.playlist_result(title_and_entries, list_id, list_title)
880
881 def _real_extract(self, url):
882 channel_id = self._match_id(url)
883 return self._extract_videos(channel_id, self._BASE_URL_TEMPL % channel_id)
884
885
886 class VimeoUserIE(VimeoChannelIE):
887 IE_NAME = 'vimeo:user'
888 _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<id>[^/]+)(?:/videos|[#?]|$)'
889 _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
890 _TESTS = [{
891 'url': 'https://vimeo.com/nkistudio/videos',
892 'info_dict': {
893 'title': 'Nki',
894 'id': 'nkistudio',
895 },
896 'playlist_mincount': 66,
897 }]
898 _BASE_URL_TEMPL = 'https://vimeo.com/%s'
899
900
901 class VimeoAlbumIE(VimeoBaseInfoExtractor):
902 IE_NAME = 'vimeo:album'
903 _VALID_URL = r'https://vimeo\.com/(?:album|showcase)/(?P<id>\d+)(?:$|[?#]|/(?!video))'
904 _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
905 _TESTS = [{
906 'url': 'https://vimeo.com/album/2632481',
907 'info_dict': {
908 'id': '2632481',
909 'title': 'Staff Favorites: November 2013',
910 },
911 'playlist_mincount': 13,
912 }, {
913 'note': 'Password-protected album',
914 'url': 'https://vimeo.com/album/3253534',
915 'info_dict': {
916 'title': 'test',
917 'id': '3253534',
918 },
919 'playlist_count': 1,
920 'params': {
921 'videopassword': 'youtube-dl',
922 }
923 }]
924 _PAGE_SIZE = 100
925
926 def _fetch_page(self, album_id, authorization, hashed_pass, page):
927 api_page = page + 1
928 query = {
929 'fields': 'link,uri',
930 'page': api_page,
931 'per_page': self._PAGE_SIZE,
932 }
933 if hashed_pass:
934 query['_hashed_pass'] = hashed_pass
935 videos = self._download_json(
936 'https://api.vimeo.com/albums/%s/videos' % album_id,
937 album_id, 'Downloading page %d' % api_page, query=query, headers={
938 'Authorization': 'jwt ' + authorization,
939 })['data']
940 for video in videos:
941 link = video.get('link')
942 if not link:
943 continue
944 uri = video.get('uri')
945 video_id = self._search_regex(r'/videos/(\d+)', uri, 'video_id', default=None) if uri else None
946 yield self.url_result(link, VimeoIE.ie_key(), video_id)
947
948 def _real_extract(self, url):
949 album_id = self._match_id(url)
950 viewer = self._download_json(
951 'https://vimeo.com/_rv/viewer', album_id, fatal=False)
952 if not viewer:
953 webpage = self._download_webpage(url, album_id)
954 viewer = self._parse_json(self._search_regex(
955 r'bootstrap_data\s*=\s*({.+?})</script>',
956 webpage, 'bootstrap data'), album_id)['viewer']
957 jwt = viewer['jwt']
958 album = self._download_json(
959 'https://api.vimeo.com/albums/' + album_id,
960 album_id, headers={'Authorization': 'jwt ' + jwt},
961 query={'fields': 'description,name,privacy'})
962 hashed_pass = None
963 if try_get(album, lambda x: x['privacy']['view']) == 'password':
964 password = self._downloader.params.get('videopassword')
965 if not password:
966 raise ExtractorError(
967 'This album is protected by a password, use the --video-password option',
968 expected=True)
969 self._set_vimeo_cookie('vuid', viewer['vuid'])
970 try:
971 hashed_pass = self._download_json(
972 'https://vimeo.com/showcase/%s/auth' % album_id,
973 album_id, 'Verifying the password', data=urlencode_postdata({
974 'password': password,
975 'token': viewer['xsrft'],
976 }), headers={
977 'X-Requested-With': 'XMLHttpRequest',
978 })['hashed_pass']
979 except ExtractorError as e:
980 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
981 raise ExtractorError('Wrong password', expected=True)
982 raise
983 entries = OnDemandPagedList(functools.partial(
984 self._fetch_page, album_id, jwt, hashed_pass), self._PAGE_SIZE)
985 return self.playlist_result(
986 entries, album_id, album.get('name'), album.get('description'))
987
988
989 class VimeoGroupsIE(VimeoChannelIE):
990 IE_NAME = 'vimeo:group'
991 _VALID_URL = r'https://vimeo\.com/groups/(?P<id>[^/]+)(?:/(?!videos?/\d+)|$)'
992 _TESTS = [{
993 'url': 'https://vimeo.com/groups/kattykay',
994 'info_dict': {
995 'id': 'kattykay',
996 'title': 'Katty Kay',
997 },
998 'playlist_mincount': 27,
999 }]
1000 _BASE_URL_TEMPL = 'https://vimeo.com/groups/%s'
1001
1002
1003 class VimeoReviewIE(VimeoBaseInfoExtractor):
1004 IE_NAME = 'vimeo:review'
1005 IE_DESC = 'Review pages on vimeo'
1006 _VALID_URL = r'(?P<url>https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)/[0-9a-f]{10})'
1007 _TESTS = [{
1008 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
1009 'md5': 'c507a72f780cacc12b2248bb4006d253',
1010 'info_dict': {
1011 'id': '75524534',
1012 'ext': 'mp4',
1013 'title': "DICK HARDWICK 'Comedian'",
1014 'uploader': 'Richard Hardwick',
1015 'uploader_id': 'user21297594',
1016 'description': "Comedian Dick Hardwick's five minute demo filmed in front of a live theater audience.\nEdit by Doug Mattocks",
1017 },
1018 'expected_warnings': ['Unable to download JSON metadata'],
1019 }, {
1020 'note': 'video player needs Referer',
1021 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
1022 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
1023 'info_dict': {
1024 'id': '91613211',
1025 'ext': 'mp4',
1026 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
1027 'uploader': 'DevWeek Events',
1028 'duration': 2773,
1029 'thumbnail': r're:^https?://.*\.jpg$',
1030 'uploader_id': 'user22258446',
1031 },
1032 'skip': 'video gone',
1033 }, {
1034 'note': 'Password protected',
1035 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
1036 'info_dict': {
1037 'id': '138823582',
1038 'ext': 'mp4',
1039 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
1040 'uploader': 'TMB',
1041 'uploader_id': 'user37284429',
1042 },
1043 'params': {
1044 'videopassword': 'holygrail',
1045 },
1046 'skip': 'video gone',
1047 }]
1048
1049 def _real_initialize(self):
1050 self._login()
1051
1052 def _real_extract(self, url):
1053 page_url, video_id = re.match(self._VALID_URL, url).groups()
1054 clip_data = self._download_json(
1055 page_url.replace('/review/', '/review/data/'),
1056 video_id)['clipData']
1057 config_url = clip_data['configUrl']
1058 config = self._download_json(config_url, video_id)
1059 info_dict = self._parse_config(config, video_id)
1060 source_format = self._extract_original_format(
1061 page_url + '/action', video_id)
1062 if source_format:
1063 info_dict['formats'].append(source_format)
1064 self._vimeo_sort_formats(info_dict['formats'])
1065 info_dict['description'] = clean_html(clip_data.get('description'))
1066 return info_dict
1067
1068
1069 class VimeoWatchLaterIE(VimeoChannelIE):
1070 IE_NAME = 'vimeo:watchlater'
1071 IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
1072 _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
1073 _TITLE = 'Watch Later'
1074 _LOGIN_REQUIRED = True
1075 _TESTS = [{
1076 'url': 'https://vimeo.com/watchlater',
1077 'only_matching': True,
1078 }]
1079
1080 def _real_initialize(self):
1081 self._login()
1082
1083 def _page_url(self, base_url, pagenum):
1084 url = '%s/page:%d/' % (base_url, pagenum)
1085 request = sanitized_Request(url)
1086 # Set the header to get a partial html page with the ids,
1087 # the normal page doesn't contain them.
1088 request.add_header('X-Requested-With', 'XMLHttpRequest')
1089 return request
1090
1091 def _real_extract(self, url):
1092 return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
1093
1094
1095 class VimeoLikesIE(VimeoChannelIE):
1096 _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
1097 IE_NAME = 'vimeo:likes'
1098 IE_DESC = 'Vimeo user likes'
1099 _TESTS = [{
1100 'url': 'https://vimeo.com/user755559/likes/',
1101 'playlist_mincount': 293,
1102 'info_dict': {
1103 'id': 'user755559',
1104 'title': 'urza’s Likes',
1105 },
1106 }, {
1107 'url': 'https://vimeo.com/stormlapse/likes',
1108 'only_matching': True,
1109 }]
1110
1111 def _page_url(self, base_url, pagenum):
1112 return '%s/page:%d/' % (base_url, pagenum)
1113
1114 def _real_extract(self, url):
1115 user_id = self._match_id(url)
1116 return self._extract_videos(user_id, 'https://vimeo.com/%s/likes' % user_id)
1117
1118
1119 class VHXEmbedIE(VimeoBaseInfoExtractor):
1120 IE_NAME = 'vhx:embed'
1121 _VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
1122
1123 @staticmethod
1124 def _extract_url(webpage):
1125 mobj = re.search(
1126 r'<iframe[^>]+src="(https?://embed\.vhx\.tv/videos/\d+[^"]*)"', webpage)
1127 return unescapeHTML(mobj.group(1)) if mobj else None
1128
1129 def _real_extract(self, url):
1130 video_id = self._match_id(url)
1131 webpage = self._download_webpage(url, video_id)
1132 config_url = self._parse_json(self._search_regex(
1133 r'window\.OTTData\s*=\s*({.+})', webpage,
1134 'ott data'), video_id, js_to_json)['config_url']
1135 config = self._download_json(config_url, video_id)
1136 info = self._parse_config(config, video_id)
1137 info['id'] = video_id
1138 self._vimeo_sort_formats(info['formats'])
1139 return info