[vimeo] Some modernization and style fixes
[youtube-dl] / youtube_dl / extractor / vimeo.py
1 # encoding: 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 .subtitles import SubtitlesInfoExtractor
10 from ..utils import (
11     compat_HTTPError,
12     compat_urllib_parse,
13     compat_urllib_request,
14     clean_html,
15     get_element_by_attribute,
16     ExtractorError,
17     RegexNotFoundError,
18     std_headers,
19     unsmuggle_url,
20     urlencode_postdata,
21 )
22
23
24 class VimeoBaseInfoExtractor(InfoExtractor):
25     _NETRC_MACHINE = 'vimeo'
26     _LOGIN_REQUIRED = False
27
28     def _login(self):
29         (username, password) = self._get_login_info()
30         if username is None:
31             if self._LOGIN_REQUIRED:
32                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
33             return
34         self.report_login()
35         login_url = 'https://vimeo.com/log_in'
36         webpage = self._download_webpage(login_url, None, False)
37         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
38         data = urlencode_postdata({
39             'email': username,
40             'password': password,
41             'action': 'login',
42             'service': 'vimeo',
43             'token': token,
44         })
45         login_request = compat_urllib_request.Request(login_url, data)
46         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
47         login_request.add_header('Cookie', 'xsrft=%s' % token)
48         self._download_webpage(login_request, None, False, 'Wrong login info')
49
50
51 class VimeoIE(VimeoBaseInfoExtractor, SubtitlesInfoExtractor):
52     """Information extractor for vimeo.com."""
53
54     # _VALID_URL matches Vimeo URLs
55     _VALID_URL = r'''(?x)
56         (?P<proto>(?:https?:)?//)?
57         (?:(?:www|(?P<player>player))\.)?
58         vimeo(?P<pro>pro)?\.com/
59         (?:.*?/)?
60         (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
61         (?:videos?/)?
62         (?P<id>[0-9]+)
63         /?(?:[?&].*)?(?:[#].*)?$'''
64     IE_NAME = 'vimeo'
65     _TESTS = [
66         {
67             'url': 'http://vimeo.com/56015672#at=0',
68             'md5': '8879b6cc097e987f02484baf890129e5',
69             'info_dict': {
70                 'id': '56015672',
71                 'ext': 'mp4',
72                 "upload_date": "20121220",
73                 "description": "This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
74                 "uploader_id": "user7108434",
75                 "uploader": "Filippo Valsorda",
76                 "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
77             },
78         },
79         {
80             'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
81             'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
82             'note': 'Vimeo Pro video (#1197)',
83             'info_dict': {
84                 'id': '68093876',
85                 'ext': 'mp4',
86                 'uploader_id': 'openstreetmapus',
87                 'uploader': 'OpenStreetMap US',
88                 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
89             },
90         },
91         {
92             'url': 'http://player.vimeo.com/video/54469442',
93             'md5': '619b811a4417aa4abe78dc653becf511',
94             'note': 'Videos that embed the url in the player page',
95             'info_dict': {
96                 'id': '54469442',
97                 'ext': 'mp4',
98                 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software',
99                 'uploader': 'The BLN & Business of Software',
100                 'uploader_id': 'theblnbusinessofsoftware',
101             },
102         },
103         {
104             'url': 'http://vimeo.com/68375962',
105             'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
106             'note': 'Video protected with password',
107             'info_dict': {
108                 'id': '68375962',
109                 'ext': 'mp4',
110                 'title': 'youtube-dl password protected test video',
111                 'upload_date': '20130614',
112                 'uploader_id': 'user18948128',
113                 'uploader': 'Jaime Marquínez Ferrándiz',
114             },
115             'params': {
116                 'videopassword': 'youtube-dl',
117             },
118         },
119         {
120             'url': 'http://vimeo.com/76979871',
121             'md5': '3363dd6ffebe3784d56f4132317fd446',
122             'note': 'Video with subtitles',
123             'info_dict': {
124                 'id': '76979871',
125                 'ext': 'mp4',
126                 'title': 'The New Vimeo Player (You Know, For Videos)',
127                 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
128                 'upload_date': '20131015',
129                 'uploader_id': 'staff',
130                 'uploader': 'Vimeo Staff',
131             }
132         },
133     ]
134
135     @classmethod
136     def suitable(cls, url):
137         if VimeoChannelIE.suitable(url):
138             # Otherwise channel urls like http://vimeo.com/channels/31259 would
139             # match
140             return False
141         else:
142             return super(VimeoIE, cls).suitable(url)
143
144     def _verify_video_password(self, url, video_id, webpage):
145         password = self._downloader.params.get('videopassword', None)
146         if password is None:
147             raise ExtractorError('This video is protected by a password, use the --video-password option')
148         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
149         data = compat_urllib_parse.urlencode({
150             'password': password,
151             'token': token,
152         })
153         # I didn't manage to use the password with https
154         if url.startswith('https'):
155             pass_url = url.replace('https', 'http')
156         else:
157             pass_url = url
158         password_request = compat_urllib_request.Request(pass_url + '/password', data)
159         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
160         password_request.add_header('Cookie', 'xsrft=%s' % token)
161         self._download_webpage(password_request, video_id,
162                                'Verifying the password',
163                                'Wrong password')
164
165     def _verify_player_video_password(self, url, video_id):
166         password = self._downloader.params.get('videopassword', None)
167         if password is None:
168             raise ExtractorError('This video is protected by a password, use the --video-password option')
169         data = compat_urllib_parse.urlencode({'password': password})
170         pass_url = url + '/check-password'
171         password_request = compat_urllib_request.Request(pass_url, data)
172         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
173         return self._download_json(
174             password_request, video_id,
175             'Verifying the password',
176             'Wrong password')
177
178     def _real_initialize(self):
179         self._login()
180
181     def _real_extract(self, url):
182         url, data = unsmuggle_url(url)
183         headers = std_headers
184         if data is not None:
185             headers = headers.copy()
186             headers.update(data)
187
188         # Extract ID from URL
189         mobj = re.match(self._VALID_URL, url)
190         video_id = mobj.group('id')
191         if mobj.group('pro') or mobj.group('player'):
192             url = 'http://player.vimeo.com/video/' + video_id
193         else:
194             url = 'https://vimeo.com/' + video_id
195
196         # Retrieve video webpage to extract further information
197         request = compat_urllib_request.Request(url, None, headers)
198         try:
199             webpage = self._download_webpage(request, video_id)
200         except ExtractorError as ee:
201             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
202                 errmsg = ee.cause.read()
203                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
204                     raise ExtractorError(
205                         'Cannot download embed-only video without embedding '
206                         'URL. Please call youtube-dl with the URL of the page '
207                         'that embeds this video.',
208                         expected=True)
209             raise
210
211         # Now we begin extracting as much information as we can from what we
212         # retrieved. First we extract the information common to all extractors,
213         # and latter we extract those that are Vimeo specific.
214         self.report_extraction(video_id)
215
216         # Extract the config JSON
217         try:
218             try:
219                 config_url = self._html_search_regex(
220                     r' data-config-url="(.+?)"', webpage, 'config URL')
221                 config_json = self._download_webpage(config_url, video_id)
222                 config = json.loads(config_json)
223             except RegexNotFoundError:
224                 # For pro videos or player.vimeo.com urls
225                 # We try to find out to which variable is assigned the config dic
226                 m_variable_name = re.search('(\w)\.video\.id', webpage)
227                 if m_variable_name is not None:
228                     config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
229                 else:
230                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
231                 config = self._search_regex(config_re, webpage, 'info section',
232                     flags=re.DOTALL)
233                 config = json.loads(config)
234         except Exception as e:
235             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
236                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
237
238             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
239                 self._verify_video_password(url, video_id, webpage)
240                 return self._real_extract(url)
241             else:
242                 raise ExtractorError('Unable to extract info section',
243                                      cause=e)
244         else:
245             if config.get('view') == 4:
246                 config = self._verify_player_video_password(url, video_id)
247
248         # Extract title
249         video_title = config["video"]["title"]
250
251         # Extract uploader and uploader_id
252         video_uploader = config["video"]["owner"]["name"]
253         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
254
255         # Extract video thumbnail
256         video_thumbnail = config["video"].get("thumbnail")
257         if video_thumbnail is None:
258             video_thumbs = config["video"].get("thumbs")
259             if video_thumbs and isinstance(video_thumbs, dict):
260                 _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in video_thumbs.items())[-1]
261
262         # Extract video description
263         video_description = None
264         try:
265             video_description = get_element_by_attribute("class", "description_wrapper", webpage)
266             if video_description:
267                 video_description = clean_html(video_description)
268         except AssertionError as err:
269             # On some pages like (http://player.vimeo.com/video/54469442) the
270             # html tags are not closed, python 2.6 cannot handle it
271             if err.args[0] == 'we should not get here!':
272                 pass
273             else:
274                 raise
275
276         # Extract upload date
277         video_upload_date = None
278         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
279         if mobj is not None:
280             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
281
282         try:
283             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
284             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
285             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
286         except RegexNotFoundError:
287             # This info is only available in vimeo.com/{id} urls
288             view_count = None
289             like_count = None
290             comment_count = None
291
292         # Vimeo specific: extract request signature and timestamp
293         sig = config['request']['signature']
294         timestamp = config['request']['timestamp']
295
296         # Vimeo specific: extract video codec and quality information
297         # First consider quality, then codecs, then take everything
298         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
299         files = {'hd': [], 'sd': [], 'other': []}
300         config_files = config["video"].get("files") or config["request"].get("files")
301         for codec_name, codec_extension in codecs:
302             for quality in config_files.get(codec_name, []):
303                 format_id = '-'.join((codec_name, quality)).lower()
304                 key = quality if quality in files else 'other'
305                 video_url = None
306                 if isinstance(config_files[codec_name], dict):
307                     file_info = config_files[codec_name][quality]
308                     video_url = file_info.get('url')
309                 else:
310                     file_info = {}
311                 if video_url is None:
312                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
313                         % (video_id, sig, timestamp, quality, codec_name.upper())
314
315                 files[key].append({
316                     'ext': codec_extension,
317                     'url': video_url,
318                     'format_id': format_id,
319                     'width': file_info.get('width'),
320                     'height': file_info.get('height'),
321                 })
322         formats = []
323         for key in ('other', 'sd', 'hd'):
324             formats += files[key]
325         if len(formats) == 0:
326             raise ExtractorError('No known codec found')
327
328         subtitles = {}
329         text_tracks = config['request'].get('text_tracks')
330         if text_tracks:
331             for tt in text_tracks:
332                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
333
334         video_subtitles = self.extract_subtitles(video_id, subtitles)
335         if self._downloader.params.get('listsubtitles', False):
336             self._list_available_subtitles(video_id, subtitles)
337             return
338
339         return {
340             'id': video_id,
341             'uploader': video_uploader,
342             'uploader_id': video_uploader_id,
343             'upload_date': video_upload_date,
344             'title': video_title,
345             'thumbnail': video_thumbnail,
346             'description': video_description,
347             'formats': formats,
348             'webpage_url': url,
349             'view_count': view_count,
350             'like_count': like_count,
351             'comment_count': comment_count,
352             'subtitles': video_subtitles,
353         }
354
355
356 class VimeoChannelIE(InfoExtractor):
357     IE_NAME = 'vimeo:channel'
358     _VALID_URL = r'(?:https?://)?vimeo\.com/channels/(?P<id>[^/]+)/?(\?.*)?$'
359     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
360     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
361
362     def _page_url(self, base_url, pagenum):
363         return '%s/videos/page:%d/' % (base_url, pagenum)
364
365     def _extract_list_title(self, webpage):
366         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
367
368     def _extract_videos(self, list_id, base_url):
369         video_ids = []
370         for pagenum in itertools.count(1):
371             webpage = self._download_webpage(
372                 self._page_url(base_url, pagenum), list_id,
373                 'Downloading page %s' % pagenum)
374             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
375             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
376                 break
377
378         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
379                    for video_id in video_ids]
380         return {'_type': 'playlist',
381                 'id': list_id,
382                 'title': self._extract_list_title(webpage),
383                 'entries': entries,
384                 }
385
386     def _real_extract(self, url):
387         mobj = re.match(self._VALID_URL, url)
388         channel_id = mobj.group('id')
389         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
390
391
392 class VimeoUserIE(VimeoChannelIE):
393     IE_NAME = 'vimeo:user'
394     _VALID_URL = r'(?:https?://)?vimeo\.com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
395     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
396
397     @classmethod
398     def suitable(cls, url):
399         if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
400             return False
401         return super(VimeoUserIE, cls).suitable(url)
402
403     def _real_extract(self, url):
404         mobj = re.match(self._VALID_URL, url)
405         name = mobj.group('name')
406         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
407
408
409 class VimeoAlbumIE(VimeoChannelIE):
410     IE_NAME = 'vimeo:album'
411     _VALID_URL = r'(?:https?://)?vimeo\.com/album/(?P<id>\d+)'
412     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
413
414     def _page_url(self, base_url, pagenum):
415         return '%s/page:%d/' % (base_url, pagenum)
416
417     def _real_extract(self, url):
418         mobj = re.match(self._VALID_URL, url)
419         album_id = mobj.group('id')
420         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
421
422
423 class VimeoGroupsIE(VimeoAlbumIE):
424     IE_NAME = 'vimeo:group'
425     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
426
427     def _extract_list_title(self, webpage):
428         return self._og_search_title(webpage)
429
430     def _real_extract(self, url):
431         mobj = re.match(self._VALID_URL, url)
432         name = mobj.group('name')
433         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
434
435
436 class VimeoReviewIE(InfoExtractor):
437     IE_NAME = 'vimeo:review'
438     IE_DESC = 'Review pages on vimeo'
439     _VALID_URL = r'(?:https?://)?vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
440     _TEST = {
441         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
442         'file': '75524534.mp4',
443         'md5': 'c507a72f780cacc12b2248bb4006d253',
444         'info_dict': {
445             'title': "DICK HARDWICK 'Comedian'",
446             'uploader': 'Richard Hardwick',
447         }
448     }
449
450     def _real_extract(self, url):
451         mobj = re.match(self._VALID_URL, url)
452         video_id = mobj.group('id')
453         player_url = 'https://player.vimeo.com/player/' + video_id
454         return self.url_result(player_url, 'Vimeo', video_id)
455
456
457 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
458     IE_NAME = 'vimeo:watchlater'
459     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
460     _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
461     _LOGIN_REQUIRED = True
462     _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
463
464     def _real_initialize(self):
465         self._login()
466
467     def _page_url(self, base_url, pagenum):
468         url = '%s/page:%d/' % (base_url, pagenum)
469         request = compat_urllib_request.Request(url)
470         # Set the header to get a partial html page with the ids,
471         # the normal page doesn't contain them.
472         request.add_header('X-Requested-With', 'XMLHttpRequest')
473         return request
474
475     def _real_extract(self, url):
476         return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')