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