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