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