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