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