Merge branch 'vgtv' of https://github.com/mrkolby/youtube-dl into mrkolby-vgtv
[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 .subtitles import SubtitlesInfoExtractor
10 from ..utils import (
11     compat_HTTPError,
12     compat_urllib_parse,
13     compat_urllib_request,
14     clean_html,
15     get_element_by_attribute,
16     ExtractorError,
17     RegexNotFoundError,
18     std_headers,
19     unsmuggle_url,
20     urlencode_postdata,
21     int_or_none,
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         (?P<proto>(?: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                 'duration': 1595,
93             },
94         },
95         {
96             'url': 'http://player.vimeo.com/video/54469442',
97             'md5': '619b811a4417aa4abe78dc653becf511',
98             'note': 'Videos that embed the url in the player page',
99             'info_dict': {
100                 'id': '54469442',
101                 'ext': 'mp4',
102                 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
103                 'uploader': 'The BLN & Business of Software',
104                 'uploader_id': 'theblnbusinessofsoftware',
105                 'duration': 3610,
106             },
107         },
108         {
109             'url': 'http://vimeo.com/68375962',
110             'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
111             'note': 'Video protected with password',
112             'info_dict': {
113                 'id': '68375962',
114                 'ext': 'mp4',
115                 'title': 'youtube-dl password protected test video',
116                 'upload_date': '20130614',
117                 'uploader_id': 'user18948128',
118                 'uploader': 'Jaime Marquínez Ferrándiz',
119                 'duration': 10,
120             },
121             'params': {
122                 'videopassword': 'youtube-dl',
123             },
124         },
125         {
126             'url': 'http://vimeo.com/channels/keypeele/75629013',
127             'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
128             'note': 'Video is freely available via original URL '
129                     'and protected with password when accessed via http://vimeo.com/75629013',
130             'info_dict': {
131                 'id': '75629013',
132                 'ext': 'mp4',
133                 'title': 'Key & Peele: Terrorist Interrogation',
134                 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
135                 'uploader_id': 'atencio',
136                 'uploader': 'Peter Atencio',
137                 'duration': 187,
138             },
139         },
140         {
141             'url': 'http://vimeo.com/76979871',
142             'md5': '3363dd6ffebe3784d56f4132317fd446',
143             'note': 'Video with subtitles',
144             'info_dict': {
145                 'id': '76979871',
146                 'ext': 'mp4',
147                 'title': 'The New Vimeo Player (You Know, For Videos)',
148                 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
149                 'upload_date': '20131015',
150                 'uploader_id': 'staff',
151                 'uploader': 'Vimeo Staff',
152                 'duration': 62,
153             }
154         },
155     ]
156
157     def _verify_video_password(self, url, video_id, webpage):
158         password = self._downloader.params.get('videopassword', None)
159         if password is None:
160             raise ExtractorError('This video is protected by a password, use the --video-password option')
161         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
162         data = compat_urllib_parse.urlencode({
163             'password': password,
164             'token': token,
165         })
166         # I didn't manage to use the password with https
167         if url.startswith('https'):
168             pass_url = url.replace('https', 'http')
169         else:
170             pass_url = url
171         password_request = compat_urllib_request.Request(pass_url + '/password', data)
172         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
173         password_request.add_header('Cookie', 'xsrft=%s' % token)
174         self._download_webpage(password_request, video_id,
175                                'Verifying the password',
176                                'Wrong password')
177
178     def _verify_player_video_password(self, url, video_id):
179         password = self._downloader.params.get('videopassword', None)
180         if password is None:
181             raise ExtractorError('This video is protected by a password, use the --video-password option')
182         data = compat_urllib_parse.urlencode({'password': password})
183         pass_url = url + '/check-password'
184         password_request = compat_urllib_request.Request(pass_url, data)
185         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
186         return self._download_json(
187             password_request, video_id,
188             'Verifying the password',
189             'Wrong password')
190
191     def _real_initialize(self):
192         self._login()
193
194     def _real_extract(self, url):
195         url, data = unsmuggle_url(url)
196         headers = std_headers
197         if data is not None:
198             headers = headers.copy()
199             headers.update(data)
200         if 'Referer' not in headers:
201             headers['Referer'] = url
202
203         # Extract ID from URL
204         mobj = re.match(self._VALID_URL, url)
205         video_id = mobj.group('id')
206         if mobj.group('pro') or mobj.group('player'):
207             url = 'http://player.vimeo.com/video/' + video_id
208
209         # Retrieve video webpage to extract further information
210         request = compat_urllib_request.Request(url, None, headers)
211         try:
212             webpage = self._download_webpage(request, video_id)
213         except ExtractorError as ee:
214             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
215                 errmsg = ee.cause.read()
216                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
217                     raise ExtractorError(
218                         'Cannot download embed-only video without embedding '
219                         'URL. Please call youtube-dl with the URL of the page '
220                         'that embeds this video.',
221                         expected=True)
222             raise
223
224         # Now we begin extracting as much information as we can from what we
225         # retrieved. First we extract the information common to all extractors,
226         # and latter we extract those that are Vimeo specific.
227         self.report_extraction(video_id)
228
229         # Extract the config JSON
230         try:
231             try:
232                 config_url = self._html_search_regex(
233                     r' data-config-url="(.+?)"', webpage, 'config URL')
234                 config_json = self._download_webpage(config_url, video_id)
235                 config = json.loads(config_json)
236             except RegexNotFoundError:
237                 # For pro videos or player.vimeo.com urls
238                 # We try to find out to which variable is assigned the config dic
239                 m_variable_name = re.search('(\w)\.video\.id', webpage)
240                 if m_variable_name is not None:
241                     config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
242                 else:
243                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
244                 config = self._search_regex(config_re, webpage, 'info section',
245                     flags=re.DOTALL)
246                 config = json.loads(config)
247         except Exception as e:
248             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
249                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
250
251             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
252                 self._verify_video_password(url, video_id, webpage)
253                 return self._real_extract(url)
254             else:
255                 raise ExtractorError('Unable to extract info section',
256                                      cause=e)
257         else:
258             if config.get('view') == 4:
259                 config = self._verify_player_video_password(url, video_id)
260
261         # Extract title
262         video_title = config["video"]["title"]
263
264         # Extract uploader and uploader_id
265         video_uploader = config["video"]["owner"]["name"]
266         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
267
268         # Extract video thumbnail
269         video_thumbnail = config["video"].get("thumbnail")
270         if video_thumbnail is None:
271             video_thumbs = config["video"].get("thumbs")
272             if video_thumbs and isinstance(video_thumbs, dict):
273                 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
274
275         # Extract video description
276         video_description = None
277         try:
278             video_description = get_element_by_attribute("class", "description_wrapper", webpage)
279             if video_description:
280                 video_description = clean_html(video_description)
281         except AssertionError as err:
282             # On some pages like (http://player.vimeo.com/video/54469442) the
283             # html tags are not closed, python 2.6 cannot handle it
284             if err.args[0] == 'we should not get here!':
285                 pass
286             else:
287                 raise
288
289         # Extract video duration
290         video_duration = int_or_none(config["video"].get("duration"))
291
292         # Extract upload date
293         video_upload_date = None
294         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
295         if mobj is not None:
296             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
297
298         try:
299             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
300             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
301             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
302         except RegexNotFoundError:
303             # This info is only available in vimeo.com/{id} urls
304             view_count = None
305             like_count = None
306             comment_count = None
307
308         # Vimeo specific: extract request signature and timestamp
309         sig = config['request']['signature']
310         timestamp = config['request']['timestamp']
311
312         # Vimeo specific: extract video codec and quality information
313         # First consider quality, then codecs, then take everything
314         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
315         files = {'hd': [], 'sd': [], 'other': []}
316         config_files = config["video"].get("files") or config["request"].get("files")
317         for codec_name, codec_extension in codecs:
318             for quality in config_files.get(codec_name, []):
319                 format_id = '-'.join((codec_name, quality)).lower()
320                 key = quality if quality in files else 'other'
321                 video_url = None
322                 if isinstance(config_files[codec_name], dict):
323                     file_info = config_files[codec_name][quality]
324                     video_url = file_info.get('url')
325                 else:
326                     file_info = {}
327                 if video_url is None:
328                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
329                         % (video_id, sig, timestamp, quality, codec_name.upper())
330
331                 files[key].append({
332                     'ext': codec_extension,
333                     'url': video_url,
334                     'format_id': format_id,
335                     'width': file_info.get('width'),
336                     'height': file_info.get('height'),
337                 })
338         formats = []
339         for key in ('other', 'sd', 'hd'):
340             formats += files[key]
341         if len(formats) == 0:
342             raise ExtractorError('No known codec found')
343
344         subtitles = {}
345         text_tracks = config['request'].get('text_tracks')
346         if text_tracks:
347             for tt in text_tracks:
348                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
349
350         video_subtitles = self.extract_subtitles(video_id, subtitles)
351         if self._downloader.params.get('listsubtitles', False):
352             self._list_available_subtitles(video_id, subtitles)
353             return
354
355         return {
356             'id': video_id,
357             'uploader': video_uploader,
358             'uploader_id': video_uploader_id,
359             'upload_date': video_upload_date,
360             'title': video_title,
361             'thumbnail': video_thumbnail,
362             'description': video_description,
363             'duration': video_duration,
364             'formats': formats,
365             'webpage_url': url,
366             'view_count': view_count,
367             'like_count': like_count,
368             'comment_count': comment_count,
369             'subtitles': video_subtitles,
370         }
371
372
373 class VimeoChannelIE(InfoExtractor):
374     IE_NAME = 'vimeo:channel'
375     _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
376     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
377     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
378     _TESTS = [{
379         'url': 'http://vimeo.com/channels/tributes',
380         'info_dict': {
381             'title': 'Vimeo Tributes',
382         },
383         'playlist_mincount': 25,
384     }]
385
386     def _page_url(self, base_url, pagenum):
387         return '%s/videos/page:%d/' % (base_url, pagenum)
388
389     def _extract_list_title(self, webpage):
390         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
391
392     def _extract_videos(self, list_id, base_url):
393         video_ids = []
394         for pagenum in itertools.count(1):
395             webpage = self._download_webpage(
396                 self._page_url(base_url, pagenum), list_id,
397                 'Downloading page %s' % pagenum)
398             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
399             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
400                 break
401
402         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
403                    for video_id in video_ids]
404         return {'_type': 'playlist',
405                 'id': list_id,
406                 'title': self._extract_list_title(webpage),
407                 'entries': entries,
408                 }
409
410     def _real_extract(self, url):
411         mobj = re.match(self._VALID_URL, url)
412         channel_id = mobj.group('id')
413         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
414
415
416 class VimeoUserIE(VimeoChannelIE):
417     IE_NAME = 'vimeo:user'
418     _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
419     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
420     _TESTS = [{
421         'url': 'http://vimeo.com/nkistudio/videos',
422         'info_dict': {
423             'title': 'Nki',
424         },
425         'playlist_mincount': 66,
426     }]
427
428     def _real_extract(self, url):
429         mobj = re.match(self._VALID_URL, url)
430         name = mobj.group('name')
431         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
432
433
434 class VimeoAlbumIE(VimeoChannelIE):
435     IE_NAME = 'vimeo:album'
436     _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
437     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
438     _TESTS = [{
439         'url': 'http://vimeo.com/album/2632481',
440         'info_dict': {
441             'title': 'Staff Favorites: November 2013',
442         },
443         'playlist_mincount': 13,
444     }]
445
446     def _page_url(self, base_url, pagenum):
447         return '%s/page:%d/' % (base_url, pagenum)
448
449     def _real_extract(self, url):
450         mobj = re.match(self._VALID_URL, url)
451         album_id = mobj.group('id')
452         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
453
454
455 class VimeoGroupsIE(VimeoAlbumIE):
456     IE_NAME = 'vimeo:group'
457     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
458     _TESTS = [{
459         'url': 'http://vimeo.com/groups/rolexawards',
460         'info_dict': {
461             'title': 'Rolex Awards for Enterprise',
462         },
463         'playlist_mincount': 73,
464     }]
465
466     def _extract_list_title(self, webpage):
467         return self._og_search_title(webpage)
468
469     def _real_extract(self, url):
470         mobj = re.match(self._VALID_URL, url)
471         name = mobj.group('name')
472         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
473
474
475 class VimeoReviewIE(InfoExtractor):
476     IE_NAME = 'vimeo:review'
477     IE_DESC = 'Review pages on vimeo'
478     _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
479     _TESTS = [{
480         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
481         'file': '75524534.mp4',
482         'md5': 'c507a72f780cacc12b2248bb4006d253',
483         'info_dict': {
484             'title': "DICK HARDWICK 'Comedian'",
485             'uploader': 'Richard Hardwick',
486         }
487     }, {
488         'note': 'video player needs Referer',
489         'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
490         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
491         'info_dict': {
492             'id': '91613211',
493             'ext': 'mp4',
494             'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
495             'uploader': 'DevWeek Events',
496             'duration': 2773,
497             'thumbnail': 're:^https?://.*\.jpg$',
498         }
499     }]
500
501     def _real_extract(self, url):
502         mobj = re.match(self._VALID_URL, url)
503         video_id = mobj.group('id')
504         player_url = 'https://player.vimeo.com/player/' + video_id
505         return self.url_result(player_url, 'Vimeo', video_id)
506
507
508 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
509     IE_NAME = 'vimeo:watchlater'
510     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
511     _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
512     _LOGIN_REQUIRED = True
513     _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
514     _TESTS = [{
515         'url': 'http://vimeo.com/home/watchlater',
516         'only_matching': True,
517     }]
518
519     def _real_initialize(self):
520         self._login()
521
522     def _page_url(self, base_url, pagenum):
523         url = '%s/page:%d/' % (base_url, pagenum)
524         request = compat_urllib_request.Request(url)
525         # Set the header to get a partial html page with the ids,
526         # the normal page doesn't contain them.
527         request.add_header('X-Requested-With', 'XMLHttpRequest')
528         return request
529
530     def _real_extract(self, url):
531         return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')