]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/vimeo.py
Implement a different adult sites checking algorithm
[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 = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
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 = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
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 _verify_player_video_password(self, url, video_id):
128         password = self._downloader.params.get('videopassword', None)
129         if password is None:
130             raise ExtractorError('This video is protected by a password, use the --video-password option')
131         data = compat_urllib_parse.urlencode({'password': password})
132         pass_url = url + '/check-password'
133         password_request = compat_urllib_request.Request(pass_url, data)
134         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
135         return self._download_json(
136             password_request, video_id,
137             'Verifying the password',
138             'Wrong password')
139
140     def _real_initialize(self):
141         self._login()
142
143     def _real_extract(self, url):
144         url, data = unsmuggle_url(url)
145         headers = std_headers
146         if data is not None:
147             headers = headers.copy()
148             headers.update(data)
149
150         # Extract ID from URL
151         mobj = re.match(self._VALID_URL, url)
152         video_id = mobj.group('id')
153         if mobj.group('pro') or mobj.group('player'):
154             url = 'http://player.vimeo.com/video/' + video_id
155         else:
156             url = 'https://vimeo.com/' + video_id
157
158         # Retrieve video webpage to extract further information
159         request = compat_urllib_request.Request(url, None, headers)
160         webpage = self._download_webpage(request, video_id)
161
162         # Now we begin extracting as much information as we can from what we
163         # retrieved. First we extract the information common to all extractors,
164         # and latter we extract those that are Vimeo specific.
165         self.report_extraction(video_id)
166
167         # Extract the config JSON
168         try:
169             try:
170                 config_url = self._html_search_regex(
171                     r' data-config-url="(.+?)"', webpage, 'config URL')
172                 config_json = self._download_webpage(config_url, video_id)
173                 config = json.loads(config_json)
174             except RegexNotFoundError:
175                 # For pro videos or player.vimeo.com urls
176                 # We try to find out to which variable is assigned the config dic
177                 m_variable_name = re.search('(\w)\.video\.id', webpage)
178                 if m_variable_name is not None:
179                     config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
180                 else:
181                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
182                 config = self._search_regex(config_re, webpage, 'info section',
183                     flags=re.DOTALL)
184                 config = json.loads(config)
185         except Exception as e:
186             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
187                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
188
189             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
190                 self._verify_video_password(url, video_id, webpage)
191                 return self._real_extract(url)
192             else:
193                 raise ExtractorError('Unable to extract info section',
194                                      cause=e)
195         else:
196             if config.get('view') == 4:
197                 config = self._verify_player_video_password(url, video_id)
198
199         # Extract title
200         video_title = config["video"]["title"]
201
202         # Extract uploader and uploader_id
203         video_uploader = config["video"]["owner"]["name"]
204         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
205
206         # Extract video thumbnail
207         video_thumbnail = config["video"].get("thumbnail")
208         if video_thumbnail is None:
209             _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
210
211         # Extract video description
212         video_description = None
213         try:
214             video_description = get_element_by_attribute("itemprop", "description", webpage)
215             if video_description: video_description = clean_html(video_description)
216         except AssertionError as err:
217             # On some pages like (http://player.vimeo.com/video/54469442) the
218             # html tags are not closed, python 2.6 cannot handle it
219             if err.args[0] == 'we should not get here!':
220                 pass
221             else:
222                 raise
223
224         # Extract upload date
225         video_upload_date = None
226         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
227         if mobj is not None:
228             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
229
230         try:
231             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
232             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
233             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
234         except RegexNotFoundError:
235             # This info is only available in vimeo.com/{id} urls
236             view_count = None
237             like_count = None
238             comment_count = None
239
240         # Vimeo specific: extract request signature and timestamp
241         sig = config['request']['signature']
242         timestamp = config['request']['timestamp']
243
244         # Vimeo specific: extract video codec and quality information
245         # First consider quality, then codecs, then take everything
246         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
247         files = {'hd': [], 'sd': [], 'other': []}
248         config_files = config["video"].get("files") or config["request"].get("files")
249         for codec_name, codec_extension in codecs:
250             for quality in config_files.get(codec_name, []):
251                 format_id = '-'.join((codec_name, quality)).lower()
252                 key = quality if quality in files else 'other'
253                 video_url = None
254                 if isinstance(config_files[codec_name], dict):
255                     file_info = config_files[codec_name][quality]
256                     video_url = file_info.get('url')
257                 else:
258                     file_info = {}
259                 if video_url is None:
260                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
261                         %(video_id, sig, timestamp, quality, codec_name.upper())
262
263                 files[key].append({
264                     'ext': codec_extension,
265                     'url': video_url,
266                     'format_id': format_id,
267                     'width': file_info.get('width'),
268                     'height': file_info.get('height'),
269                 })
270         formats = []
271         for key in ('other', 'sd', 'hd'):
272             formats += files[key]
273         if len(formats) == 0:
274             raise ExtractorError('No known codec found')
275
276         return {
277             'id':       video_id,
278             'uploader': video_uploader,
279             'uploader_id': video_uploader_id,
280             'upload_date':  video_upload_date,
281             'title':    video_title,
282             'thumbnail':    video_thumbnail,
283             'description':  video_description,
284             'formats': formats,
285             'webpage_url': url,
286             'view_count': view_count,
287             'like_count': like_count,
288             'comment_count': comment_count,
289         }
290
291
292 class VimeoChannelIE(InfoExtractor):
293     IE_NAME = 'vimeo:channel'
294     _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
295     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
296     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
297
298     def _page_url(self, base_url, pagenum):
299         return '%s/videos/page:%d/' % (base_url, pagenum)
300
301     def _extract_list_title(self, webpage):
302         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
303
304     def _extract_videos(self, list_id, base_url):
305         video_ids = []
306         for pagenum in itertools.count(1):
307             webpage = self._download_webpage(
308                 self._page_url(base_url, pagenum) ,list_id,
309                 'Downloading page %s' % pagenum)
310             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
311             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
312                 break
313
314         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
315                    for video_id in video_ids]
316         return {'_type': 'playlist',
317                 'id': list_id,
318                 'title': self._extract_list_title(webpage),
319                 'entries': entries,
320                 }
321
322     def _real_extract(self, url):
323         mobj = re.match(self._VALID_URL, url)
324         channel_id =  mobj.group('id')
325         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
326
327
328 class VimeoUserIE(VimeoChannelIE):
329     IE_NAME = 'vimeo:user'
330     _VALID_URL = r'(?:https?://)?vimeo.\com/(?P<name>[^/]+)(?:/videos|[#?]|$)'
331     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
332
333     @classmethod
334     def suitable(cls, url):
335         if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url) or VimeoAlbumIE.suitable(url) or VimeoGroupsIE.suitable(url):
336             return False
337         return super(VimeoUserIE, cls).suitable(url)
338
339     def _real_extract(self, url):
340         mobj = re.match(self._VALID_URL, url)
341         name = mobj.group('name')
342         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
343
344
345 class VimeoAlbumIE(VimeoChannelIE):
346     IE_NAME = 'vimeo:album'
347     _VALID_URL = r'(?:https?://)?vimeo.\com/album/(?P<id>\d+)'
348     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
349
350     def _page_url(self, base_url, pagenum):
351         return '%s/page:%d/' % (base_url, pagenum)
352
353     def _real_extract(self, url):
354         mobj = re.match(self._VALID_URL, url)
355         album_id = mobj.group('id')
356         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
357
358
359 class VimeoGroupsIE(VimeoAlbumIE):
360     IE_NAME = 'vimeo:group'
361     _VALID_URL = r'(?:https?://)?vimeo.\com/groups/(?P<name>[^/]+)'
362
363     def _extract_list_title(self, webpage):
364         return self._og_search_title(webpage)
365
366     def _real_extract(self, url):
367         mobj = re.match(self._VALID_URL, url)
368         name = mobj.group('name')
369         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
370
371
372 class VimeoReviewIE(InfoExtractor):
373     IE_NAME = 'vimeo:review'
374     IE_DESC = 'Review pages on vimeo'
375     _VALID_URL = r'(?:https?://)?vimeo.\com/[^/]+/review/(?P<id>[^/]+)'
376     _TEST = {
377         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
378         'file': '75524534.mp4',
379         'md5': 'c507a72f780cacc12b2248bb4006d253',
380         'info_dict': {
381             'title': "DICK HARDWICK 'Comedian'",
382             'uploader': 'Richard Hardwick',
383         }
384     }
385
386     def _real_extract(self, url):
387         mobj = re.match(self._VALID_URL, url)
388         video_id = mobj.group('id')
389         player_url = 'https://player.vimeo.com/player/' + video_id
390         return self.url_result(player_url, 'Vimeo', video_id)