]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/vimeo.py
Imported Upstream version 2013.12.04
[youtubedl] / youtube_dl / extractor / vimeo.py
1 # encoding: utf-8
2 import json
3 import re
4 import itertools
5
6 from .common import InfoExtractor
7 from ..utils import (
8 compat_urllib_parse,
9 compat_urllib_request,
10
11 clean_html,
12 get_element_by_attribute,
13 ExtractorError,
14 RegexNotFoundError,
15 std_headers,
16 unsmuggle_url,
17 )
18
19 class VimeoIE(InfoExtractor):
20 """Information extractor for vimeo.com."""
21
22 # _VALID_URL matches Vimeo URLs
23 _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|(?P<player>player))\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)/?(?:[?].*)?(?:#.*)?$'
24 _NETRC_MACHINE = 'vimeo'
25 IE_NAME = u'vimeo'
26 _TESTS = [
27 {
28 u'url': u'http://vimeo.com/56015672#at=0',
29 u'file': u'56015672.mp4',
30 u'md5': u'8879b6cc097e987f02484baf890129e5',
31 u'info_dict': {
32 u"upload_date": u"20121220",
33 u"description": u"This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
34 u"uploader_id": u"user7108434",
35 u"uploader": u"Filippo Valsorda",
36 u"title": u"youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
37 },
38 },
39 {
40 u'url': u'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
41 u'file': u'68093876.mp4',
42 u'md5': u'3b5ca6aa22b60dfeeadf50b72e44ed82',
43 u'note': u'Vimeo Pro video (#1197)',
44 u'info_dict': {
45 u'uploader_id': u'openstreetmapus',
46 u'uploader': u'OpenStreetMap US',
47 u'title': u'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
48 },
49 },
50 {
51 u'url': u'http://player.vimeo.com/video/54469442',
52 u'file': u'54469442.mp4',
53 u'md5': u'619b811a4417aa4abe78dc653becf511',
54 u'note': u'Videos that embed the url in the player page',
55 u'info_dict': {
56 u'title': u'Kathy Sierra: Building the minimum Badass User, Business of Software',
57 u'uploader': u'The BLN & Business of Software',
58 },
59 },
60 {
61 u'url': u'http://vimeo.com/68375962',
62 u'file': u'68375962.mp4',
63 u'md5': u'aaf896bdb7ddd6476df50007a0ac0ae7',
64 u'note': u'Video protected with password',
65 u'info_dict': {
66 u'title': u'youtube-dl password protected test video',
67 u'upload_date': u'20130614',
68 u'uploader_id': u'user18948128',
69 u'uploader': u'Jaime Marquínez Ferrándiz',
70 },
71 u'params': {
72 u'videopassword': u'youtube-dl',
73 },
74 },
75 ]
76
77 def _login(self):
78 (username, password) = self._get_login_info()
79 if username is None:
80 return
81 self.report_login()
82 login_url = 'https://vimeo.com/log_in'
83 webpage = self._download_webpage(login_url, None, False)
84 token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
85 data = compat_urllib_parse.urlencode({'email': username,
86 'password': password,
87 'action': 'login',
88 'service': 'vimeo',
89 'token': token,
90 })
91 login_request = compat_urllib_request.Request(login_url, data)
92 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
93 login_request.add_header('Cookie', 'xsrft=%s' % token)
94 self._download_webpage(login_request, None, False, u'Wrong login info')
95
96 def _verify_video_password(self, url, video_id, webpage):
97 password = self._downloader.params.get('videopassword', None)
98 if password is None:
99 raise ExtractorError(u'This video is protected by a password, use the --video-password option')
100 token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
101 data = compat_urllib_parse.urlencode({'password': password,
102 'token': token})
103 # I didn't manage to use the password with https
104 if url.startswith('https'):
105 pass_url = url.replace('https','http')
106 else:
107 pass_url = url
108 password_request = compat_urllib_request.Request(pass_url+'/password', data)
109 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
110 password_request.add_header('Cookie', 'xsrft=%s' % token)
111 self._download_webpage(password_request, video_id,
112 u'Verifying the password',
113 u'Wrong password')
114
115 def _real_initialize(self):
116 self._login()
117
118 def _real_extract(self, url, new_video=True):
119 url, data = unsmuggle_url(url)
120 headers = std_headers
121 if data is not None:
122 headers = headers.copy()
123 headers.update(data)
124
125 # Extract ID from URL
126 mobj = re.match(self._VALID_URL, url)
127 if mobj is None:
128 raise ExtractorError(u'Invalid URL: %s' % url)
129
130 video_id = mobj.group('id')
131 if mobj.group('pro') or mobj.group('player'):
132 url = 'http://player.vimeo.com/video/' + video_id
133 else:
134 url = 'https://vimeo.com/' + video_id
135
136 # Retrieve video webpage to extract further information
137 request = compat_urllib_request.Request(url, None, headers)
138 webpage = self._download_webpage(request, video_id)
139
140 # Now we begin extracting as much information as we can from what we
141 # retrieved. First we extract the information common to all extractors,
142 # and latter we extract those that are Vimeo specific.
143 self.report_extraction(video_id)
144
145 # Extract the config JSON
146 try:
147 try:
148 config_url = self._html_search_regex(
149 r' data-config-url="(.+?)"', webpage, u'config URL')
150 config_json = self._download_webpage(config_url, video_id)
151 config = json.loads(config_json)
152 except RegexNotFoundError:
153 # For pro videos or player.vimeo.com urls
154 config = self._search_regex([r' = {config:({.+?}),assets:', r'(?:c|b)=({.+?});'],
155 webpage, u'info section', flags=re.DOTALL)
156 config = json.loads(config)
157 except Exception as e:
158 if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
159 raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
160
161 if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
162 self._verify_video_password(url, video_id, webpage)
163 return self._real_extract(url)
164 else:
165 raise ExtractorError(u'Unable to extract info section',
166 cause=e)
167
168 # Extract title
169 video_title = config["video"]["title"]
170
171 # Extract uploader and uploader_id
172 video_uploader = config["video"]["owner"]["name"]
173 video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
174
175 # Extract video thumbnail
176 video_thumbnail = config["video"].get("thumbnail")
177 if video_thumbnail is None:
178 _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
179
180 # Extract video description
181 video_description = None
182 try:
183 video_description = get_element_by_attribute("itemprop", "description", webpage)
184 if video_description: video_description = clean_html(video_description)
185 except AssertionError as err:
186 # On some pages like (http://player.vimeo.com/video/54469442) the
187 # html tags are not closed, python 2.6 cannot handle it
188 if err.args[0] == 'we should not get here!':
189 pass
190 else:
191 raise
192
193 # Extract upload date
194 video_upload_date = None
195 mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
196 if mobj is not None:
197 video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
198
199 # Vimeo specific: extract request signature and timestamp
200 sig = config['request']['signature']
201 timestamp = config['request']['timestamp']
202
203 # Vimeo specific: extract video codec and quality information
204 # First consider quality, then codecs, then take everything
205 codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
206 files = {'hd': [], 'sd': [], 'other': []}
207 config_files = config["video"].get("files") or config["request"].get("files")
208 for codec_name, codec_extension in codecs:
209 for quality in config_files.get(codec_name, []):
210 format_id = '-'.join((codec_name, quality)).lower()
211 key = quality if quality in files else 'other'
212 video_url = None
213 if isinstance(config_files[codec_name], dict):
214 file_info = config_files[codec_name][quality]
215 video_url = file_info.get('url')
216 else:
217 file_info = {}
218 if video_url is None:
219 video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
220 %(video_id, sig, timestamp, quality, codec_name.upper())
221
222 files[key].append({
223 'ext': codec_extension,
224 'url': video_url,
225 'format_id': format_id,
226 'width': file_info.get('width'),
227 'height': file_info.get('height'),
228 })
229 formats = []
230 for key in ('other', 'sd', 'hd'):
231 formats += files[key]
232 if len(formats) == 0:
233 raise ExtractorError(u'No known codec found')
234
235 return {
236 'id': video_id,
237 'uploader': video_uploader,
238 'uploader_id': video_uploader_id,
239 'upload_date': video_upload_date,
240 'title': video_title,
241 'thumbnail': video_thumbnail,
242 'description': video_description,
243 'formats': formats,
244 'webpage_url': url,
245 }
246
247
248 class VimeoChannelIE(InfoExtractor):
249 IE_NAME = u'vimeo:channel'
250 _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
251 _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
252 _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
253
254 def _extract_videos(self, list_id, base_url):
255 video_ids = []
256 for pagenum in itertools.count(1):
257 webpage = self._download_webpage(
258 '%s/videos/page:%d/' % (base_url, pagenum),list_id,
259 u'Downloading page %s' % pagenum)
260 video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
261 if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
262 break
263
264 entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
265 for video_id in video_ids]
266 list_title = self._html_search_regex(self._TITLE_RE, webpage,
267 u'list title')
268 return {'_type': 'playlist',
269 'id': list_id,
270 'title': list_title,
271 'entries': entries,
272 }
273
274 def _real_extract(self, url):
275 mobj = re.match(self._VALID_URL, url)
276 channel_id = mobj.group('id')
277 return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
278
279
280 class VimeoUserIE(VimeoChannelIE):
281 IE_NAME = u'vimeo:user'
282 _VALID_URL = r'(?:https?://)?vimeo.\com/(?P<name>[^/]+)'
283 _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
284
285 @classmethod
286 def suitable(cls, url):
287 if VimeoChannelIE.suitable(url) or VimeoIE.suitable(url):
288 return False
289 return super(VimeoUserIE, cls).suitable(url)
290
291 def _real_extract(self, url):
292 mobj = re.match(self._VALID_URL, url)
293 name = mobj.group('name')
294 return self._extract_videos(name, 'http://vimeo.com/%s' % name)