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