]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/vimeo.py
debian/changelog: Annotate bugs being closed.
[youtubedl] / 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 .subtitles import SubtitlesInfoExtractor
10 from ..utils import (
11 compat_HTTPError,
12 compat_urllib_parse,
13 compat_urllib_request,
14 compat_urlparse,
15 ExtractorError,
16 InAdvancePagedList,
17 int_or_none,
18 RegexNotFoundError,
19 std_headers,
20 unsmuggle_url,
21 urlencode_postdata,
22 )
23
24
25 class VimeoBaseInfoExtractor(InfoExtractor):
26 _NETRC_MACHINE = 'vimeo'
27 _LOGIN_REQUIRED = False
28
29 def _login(self):
30 (username, password) = self._get_login_info()
31 if username is None:
32 if self._LOGIN_REQUIRED:
33 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
34 return
35 self.report_login()
36 login_url = 'https://vimeo.com/log_in'
37 webpage = self._download_webpage(login_url, None, False)
38 token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
39 data = urlencode_postdata({
40 'email': username,
41 'password': password,
42 'action': 'login',
43 'service': 'vimeo',
44 'token': token,
45 })
46 login_request = compat_urllib_request.Request(login_url, data)
47 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
48 login_request.add_header('Cookie', 'xsrft=%s' % token)
49 self._download_webpage(login_request, None, False, 'Wrong login info')
50
51
52 class VimeoIE(VimeoBaseInfoExtractor, SubtitlesInfoExtractor):
53 """Information extractor for vimeo.com."""
54
55 # _VALID_URL matches Vimeo URLs
56 _VALID_URL = r'''(?x)
57 https?://
58 (?:(?:www|(?P<player>player))\.)?
59 vimeo(?P<pro>pro)?\.com/
60 (?!channels/[^/?#]+/?(?:$|[?#])|album/)
61 (?:.*?/)?
62 (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
63 (?:videos?/)?
64 (?P<id>[0-9]+)
65 /?(?:[?&].*)?(?:[#].*)?$'''
66 IE_NAME = 'vimeo'
67 _TESTS = [
68 {
69 'url': 'http://vimeo.com/56015672#at=0',
70 'md5': '8879b6cc097e987f02484baf890129e5',
71 'info_dict': {
72 'id': '56015672',
73 'ext': 'mp4',
74 "upload_date": "20121220",
75 "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",
76 "uploader_id": "user7108434",
77 "uploader": "Filippo Valsorda",
78 "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
79 "duration": 10,
80 },
81 },
82 {
83 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
84 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
85 'note': 'Vimeo Pro video (#1197)',
86 'info_dict': {
87 'id': '68093876',
88 'ext': 'mp4',
89 'uploader_id': 'openstreetmapus',
90 'uploader': 'OpenStreetMap US',
91 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
92 'description': 'md5:380943ec71b89736ff4bf27183233d09',
93 'duration': 1595,
94 },
95 },
96 {
97 'url': 'http://player.vimeo.com/video/54469442',
98 'md5': '619b811a4417aa4abe78dc653becf511',
99 'note': 'Videos that embed the url in the player page',
100 'info_dict': {
101 'id': '54469442',
102 'ext': 'mp4',
103 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
104 'uploader': 'The BLN & Business of Software',
105 'uploader_id': 'theblnbusinessofsoftware',
106 'duration': 3610,
107 'description': None,
108 },
109 },
110 {
111 'url': 'http://vimeo.com/68375962',
112 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
113 'note': 'Video protected with password',
114 'info_dict': {
115 'id': '68375962',
116 'ext': 'mp4',
117 'title': 'youtube-dl password protected test video',
118 'upload_date': '20130614',
119 'uploader_id': 'user18948128',
120 'uploader': 'Jaime Marquínez Ferrándiz',
121 'duration': 10,
122 'description': 'This is "youtube-dl password protected test video" by Jaime Marquínez Ferrándiz on Vimeo, the home for high quality videos and the people who love them.',
123 },
124 'params': {
125 'videopassword': 'youtube-dl',
126 },
127 },
128 {
129 'url': 'http://vimeo.com/channels/keypeele/75629013',
130 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
131 'note': 'Video is freely available via original URL '
132 'and protected with password when accessed via http://vimeo.com/75629013',
133 'info_dict': {
134 'id': '75629013',
135 'ext': 'mp4',
136 'title': 'Key & Peele: Terrorist Interrogation',
137 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
138 'uploader_id': 'atencio',
139 'uploader': 'Peter Atencio',
140 'duration': 187,
141 },
142 },
143 {
144 'url': 'http://vimeo.com/76979871',
145 'md5': '3363dd6ffebe3784d56f4132317fd446',
146 'note': 'Video with subtitles',
147 'info_dict': {
148 'id': '76979871',
149 'ext': 'mp4',
150 'title': 'The New Vimeo Player (You Know, For Videos)',
151 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
152 'upload_date': '20131015',
153 'uploader_id': 'staff',
154 'uploader': 'Vimeo Staff',
155 'duration': 62,
156 }
157 },
158 {
159 # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
160 'url': 'https://player.vimeo.com/video/98044508',
161 'note': 'The js code contains assignments to the same variable as the config',
162 'info_dict': {
163 'id': '98044508',
164 'ext': 'mp4',
165 'title': 'Pier Solar OUYA Official Trailer',
166 'uploader': 'Tulio Gonçalves',
167 'uploader_id': 'user28849593',
168 },
169 },
170 ]
171
172 def _verify_video_password(self, url, video_id, webpage):
173 password = self._downloader.params.get('videopassword', None)
174 if password is None:
175 raise ExtractorError('This video is protected by a password, use the --video-password option')
176 token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
177 data = compat_urllib_parse.urlencode({
178 'password': password,
179 'token': token,
180 })
181 # I didn't manage to use the password with https
182 if url.startswith('https'):
183 pass_url = url.replace('https', 'http')
184 else:
185 pass_url = url
186 password_request = compat_urllib_request.Request(pass_url + '/password', data)
187 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
188 password_request.add_header('Cookie', 'xsrft=%s' % token)
189 self._download_webpage(password_request, video_id,
190 'Verifying the password',
191 'Wrong password')
192
193 def _verify_player_video_password(self, url, video_id):
194 password = self._downloader.params.get('videopassword', None)
195 if password is None:
196 raise ExtractorError('This video is protected by a password, use the --video-password option')
197 data = compat_urllib_parse.urlencode({'password': password})
198 pass_url = url + '/check-password'
199 password_request = compat_urllib_request.Request(pass_url, data)
200 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
201 return self._download_json(
202 password_request, video_id,
203 'Verifying the password',
204 'Wrong password')
205
206 def _real_initialize(self):
207 self._login()
208
209 def _real_extract(self, url):
210 url, data = unsmuggle_url(url)
211 headers = std_headers
212 if data is not None:
213 headers = headers.copy()
214 headers.update(data)
215 if 'Referer' not in headers:
216 headers['Referer'] = url
217
218 # Extract ID from URL
219 mobj = re.match(self._VALID_URL, url)
220 video_id = mobj.group('id')
221 orig_url = url
222 if mobj.group('pro') or mobj.group('player'):
223 url = 'http://player.vimeo.com/video/' + video_id
224
225 # Retrieve video webpage to extract further information
226 request = compat_urllib_request.Request(url, None, headers)
227 try:
228 webpage = self._download_webpage(request, video_id)
229 except ExtractorError as ee:
230 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
231 errmsg = ee.cause.read()
232 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
233 raise ExtractorError(
234 'Cannot download embed-only video without embedding '
235 'URL. Please call youtube-dl with the URL of the page '
236 'that embeds this video.',
237 expected=True)
238 raise
239
240 # Now we begin extracting as much information as we can from what we
241 # retrieved. First we extract the information common to all extractors,
242 # and latter we extract those that are Vimeo specific.
243 self.report_extraction(video_id)
244
245 # Extract the config JSON
246 try:
247 try:
248 config_url = self._html_search_regex(
249 r' data-config-url="(.+?)"', webpage, 'config URL')
250 config_json = self._download_webpage(config_url, video_id)
251 config = json.loads(config_json)
252 except RegexNotFoundError:
253 # For pro videos or player.vimeo.com urls
254 # We try to find out to which variable is assigned the config dic
255 m_variable_name = re.search('(\w)\.video\.id', webpage)
256 if m_variable_name is not None:
257 config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
258 else:
259 config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
260 config = self._search_regex(config_re, webpage, 'info section',
261 flags=re.DOTALL)
262 config = json.loads(config)
263 except Exception as e:
264 if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
265 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
266
267 if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
268 self._verify_video_password(url, video_id, webpage)
269 return self._real_extract(url)
270 else:
271 raise ExtractorError('Unable to extract info section',
272 cause=e)
273 else:
274 if config.get('view') == 4:
275 config = self._verify_player_video_password(url, video_id)
276
277 # Extract title
278 video_title = config["video"]["title"]
279
280 # Extract uploader and uploader_id
281 video_uploader = config["video"]["owner"]["name"]
282 video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
283
284 # Extract video thumbnail
285 video_thumbnail = config["video"].get("thumbnail")
286 if video_thumbnail is None:
287 video_thumbs = config["video"].get("thumbs")
288 if video_thumbs and isinstance(video_thumbs, dict):
289 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
290
291 # Extract video description
292
293 video_description = self._html_search_regex(
294 r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
295 webpage, 'description', default=None)
296 if not video_description:
297 video_description = self._html_search_meta(
298 'description', webpage, default=None)
299 if not video_description and mobj.group('pro'):
300 orig_webpage = self._download_webpage(
301 orig_url, video_id,
302 note='Downloading webpage for description',
303 fatal=False)
304 if orig_webpage:
305 video_description = self._html_search_meta(
306 'description', orig_webpage, default=None)
307 if not video_description and not mobj.group('player'):
308 self._downloader.report_warning('Cannot find video description')
309
310 # Extract video duration
311 video_duration = int_or_none(config["video"].get("duration"))
312
313 # Extract upload date
314 video_upload_date = None
315 mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
316 if mobj is not None:
317 video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
318
319 try:
320 view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
321 like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
322 comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
323 except RegexNotFoundError:
324 # This info is only available in vimeo.com/{id} urls
325 view_count = None
326 like_count = None
327 comment_count = None
328
329 # Vimeo specific: extract request signature and timestamp
330 sig = config['request']['signature']
331 timestamp = config['request']['timestamp']
332
333 # Vimeo specific: extract video codec and quality information
334 # First consider quality, then codecs, then take everything
335 codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
336 files = {'hd': [], 'sd': [], 'other': []}
337 config_files = config["video"].get("files") or config["request"].get("files")
338 for codec_name, codec_extension in codecs:
339 for quality in config_files.get(codec_name, []):
340 format_id = '-'.join((codec_name, quality)).lower()
341 key = quality if quality in files else 'other'
342 video_url = None
343 if isinstance(config_files[codec_name], dict):
344 file_info = config_files[codec_name][quality]
345 video_url = file_info.get('url')
346 else:
347 file_info = {}
348 if video_url is None:
349 video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
350 % (video_id, sig, timestamp, quality, codec_name.upper())
351
352 files[key].append({
353 'ext': codec_extension,
354 'url': video_url,
355 'format_id': format_id,
356 'width': file_info.get('width'),
357 'height': file_info.get('height'),
358 })
359 formats = []
360 for key in ('other', 'sd', 'hd'):
361 formats += files[key]
362 if len(formats) == 0:
363 raise ExtractorError('No known codec found')
364
365 subtitles = {}
366 text_tracks = config['request'].get('text_tracks')
367 if text_tracks:
368 for tt in text_tracks:
369 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
370
371 video_subtitles = self.extract_subtitles(video_id, subtitles)
372 if self._downloader.params.get('listsubtitles', False):
373 self._list_available_subtitles(video_id, subtitles)
374 return
375
376 return {
377 'id': video_id,
378 'uploader': video_uploader,
379 'uploader_id': video_uploader_id,
380 'upload_date': video_upload_date,
381 'title': video_title,
382 'thumbnail': video_thumbnail,
383 'description': video_description,
384 'duration': video_duration,
385 'formats': formats,
386 'webpage_url': url,
387 'view_count': view_count,
388 'like_count': like_count,
389 'comment_count': comment_count,
390 'subtitles': video_subtitles,
391 }
392
393
394 class VimeoChannelIE(InfoExtractor):
395 IE_NAME = 'vimeo:channel'
396 _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
397 _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
398 _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
399 _TESTS = [{
400 'url': 'http://vimeo.com/channels/tributes',
401 'info_dict': {
402 'title': 'Vimeo Tributes',
403 },
404 'playlist_mincount': 25,
405 }]
406
407 def _page_url(self, base_url, pagenum):
408 return '%s/videos/page:%d/' % (base_url, pagenum)
409
410 def _extract_list_title(self, webpage):
411 return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
412
413 def _extract_videos(self, list_id, base_url):
414 video_ids = []
415 for pagenum in itertools.count(1):
416 webpage = self._download_webpage(
417 self._page_url(base_url, pagenum), list_id,
418 'Downloading page %s' % pagenum)
419 video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
420 if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
421 break
422
423 entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
424 for video_id in video_ids]
425 return {'_type': 'playlist',
426 'id': list_id,
427 'title': self._extract_list_title(webpage),
428 'entries': entries,
429 }
430
431 def _real_extract(self, url):
432 mobj = re.match(self._VALID_URL, url)
433 channel_id = mobj.group('id')
434 return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
435
436
437 class VimeoUserIE(VimeoChannelIE):
438 IE_NAME = 'vimeo:user'
439 _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
440 _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
441 _TESTS = [{
442 'url': 'http://vimeo.com/nkistudio/videos',
443 'info_dict': {
444 'title': 'Nki',
445 },
446 'playlist_mincount': 66,
447 }]
448
449 def _real_extract(self, url):
450 mobj = re.match(self._VALID_URL, url)
451 name = mobj.group('name')
452 return self._extract_videos(name, 'http://vimeo.com/%s' % name)
453
454
455 class VimeoAlbumIE(VimeoChannelIE):
456 IE_NAME = 'vimeo:album'
457 _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
458 _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
459 _TESTS = [{
460 'url': 'http://vimeo.com/album/2632481',
461 'info_dict': {
462 'title': 'Staff Favorites: November 2013',
463 },
464 'playlist_mincount': 13,
465 }]
466
467 def _page_url(self, base_url, pagenum):
468 return '%s/page:%d/' % (base_url, pagenum)
469
470 def _real_extract(self, url):
471 mobj = re.match(self._VALID_URL, url)
472 album_id = mobj.group('id')
473 return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
474
475
476 class VimeoGroupsIE(VimeoAlbumIE):
477 IE_NAME = 'vimeo:group'
478 _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
479 _TESTS = [{
480 'url': 'http://vimeo.com/groups/rolexawards',
481 'info_dict': {
482 'title': 'Rolex Awards for Enterprise',
483 },
484 'playlist_mincount': 73,
485 }]
486
487 def _extract_list_title(self, webpage):
488 return self._og_search_title(webpage)
489
490 def _real_extract(self, url):
491 mobj = re.match(self._VALID_URL, url)
492 name = mobj.group('name')
493 return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
494
495
496 class VimeoReviewIE(InfoExtractor):
497 IE_NAME = 'vimeo:review'
498 IE_DESC = 'Review pages on vimeo'
499 _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
500 _TESTS = [{
501 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
502 'file': '75524534.mp4',
503 'md5': 'c507a72f780cacc12b2248bb4006d253',
504 'info_dict': {
505 'title': "DICK HARDWICK 'Comedian'",
506 'uploader': 'Richard Hardwick',
507 }
508 }, {
509 'note': 'video player needs Referer',
510 'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
511 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
512 'info_dict': {
513 'id': '91613211',
514 'ext': 'mp4',
515 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
516 'uploader': 'DevWeek Events',
517 'duration': 2773,
518 'thumbnail': 're:^https?://.*\.jpg$',
519 }
520 }]
521
522 def _real_extract(self, url):
523 mobj = re.match(self._VALID_URL, url)
524 video_id = mobj.group('id')
525 player_url = 'https://player.vimeo.com/player/' + video_id
526 return self.url_result(player_url, 'Vimeo', video_id)
527
528
529 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
530 IE_NAME = 'vimeo:watchlater'
531 IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
532 _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
533 _LOGIN_REQUIRED = True
534 _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
535 _TESTS = [{
536 'url': 'http://vimeo.com/home/watchlater',
537 'only_matching': True,
538 }]
539
540 def _real_initialize(self):
541 self._login()
542
543 def _page_url(self, base_url, pagenum):
544 url = '%s/page:%d/' % (base_url, pagenum)
545 request = compat_urllib_request.Request(url)
546 # Set the header to get a partial html page with the ids,
547 # the normal page doesn't contain them.
548 request.add_header('X-Requested-With', 'XMLHttpRequest')
549 return request
550
551 def _real_extract(self, url):
552 return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')
553
554
555 class VimeoLikesIE(InfoExtractor):
556 _VALID_URL = r'https?://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
557 IE_NAME = 'vimeo:likes'
558 IE_DESC = 'Vimeo user likes'
559 _TEST = {
560 'url': 'https://vimeo.com/user755559/likes/',
561 'playlist_mincount': 293,
562 "info_dict": {
563 "description": "See all the videos urza likes",
564 "title": 'Videos urza likes',
565 },
566 }
567
568 def _real_extract(self, url):
569 user_id = self._match_id(url)
570 webpage = self._download_webpage(url, user_id)
571 page_count = self._int(
572 self._search_regex(
573 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
574 .*?</a></li>\s*<li\s+class="pagination_next">
575 ''', webpage, 'page count'),
576 'page count', fatal=True)
577 PAGE_SIZE = 12
578 title = self._html_search_regex(
579 r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
580 description = self._html_search_meta('description', webpage)
581
582 def _get_page(idx):
583 page_url = '%s//vimeo.com/user%s/likes/page:%d/sort:date' % (
584 self.http_scheme(), user_id, idx + 1)
585 webpage = self._download_webpage(
586 page_url, user_id,
587 note='Downloading page %d/%d' % (idx + 1, page_count))
588 video_list = self._search_regex(
589 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
590 webpage, 'video content')
591 paths = re.findall(
592 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
593 for path in paths:
594 yield {
595 '_type': 'url',
596 'url': compat_urlparse.urljoin(page_url, path),
597 }
598
599 pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
600
601 return {
602 '_type': 'playlist',
603 'id': 'user%s_likes' % user_id,
604 'title': title,
605 'description': description,
606 'entries': pl,
607 }