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