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