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