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