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