[vimeo] Fix normal videos (Fixes #1642)
[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     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'ae7a1d8b183758a0506b0622f37dfa14',
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_url = self._html_search_regex(
133                 r' data-config-url="(.+?)"', webpage, u'config URL')
134             config_json = self._download_webpage(config_url, video_id)
135             config = json.loads(config_json)
136         except Exception as e:
137             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
138                 raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
139
140             if re.search('If so please provide the correct password.', webpage):
141                 self._verify_video_password(url, video_id, webpage)
142                 return self._real_extract(url)
143             else:
144                 raise ExtractorError(u'Unable to extract info section',
145                                      cause=e)
146
147         # Extract title
148         video_title = config["video"]["title"]
149
150         # Extract uploader and uploader_id
151         video_uploader = config["video"]["owner"]["name"]
152         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
153
154         # Extract video thumbnail
155         video_thumbnail = config["video"].get("thumbnail")
156         if video_thumbnail is None:
157             _, video_thumbnail = sorted((int(width), t_url) for (width, t_url) in config["video"]["thumbs"].items())[-1]
158
159         # Extract video description
160         video_description = None
161         try:
162             video_description = get_element_by_attribute("itemprop", "description", webpage)
163             if video_description: video_description = clean_html(video_description)
164         except AssertionError as err:
165             # On some pages like (http://player.vimeo.com/video/54469442) the
166             # html tags are not closed, python 2.6 cannot handle it
167             if err.args[0] == 'we should not get here!':
168                 pass
169             else:
170                 raise
171
172         # Extract upload date
173         video_upload_date = None
174         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
175         if mobj is not None:
176             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
177
178         # Vimeo specific: extract request signature and timestamp
179         sig = config['request']['signature']
180         timestamp = config['request']['timestamp']
181
182         # Vimeo specific: extract video codec and quality information
183         # First consider quality, then codecs, then take everything
184         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
185         files = { 'hd': [], 'sd': [], 'other': []}
186         config_files = config["video"].get("files") or config["request"].get("files")
187         for codec_name, codec_extension in codecs:
188             for quality in config_files.get(codec_name, []):
189                 format_id = '-'.join((codec_name, quality)).lower()
190                 key = quality if quality in files else 'other'
191                 video_url = None
192                 if isinstance(config_files[codec_name], dict):
193                     file_info = config_files[codec_name][quality]
194                     video_url = file_info.get('url')
195                 else:
196                     file_info = {}
197                 if video_url is None:
198                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
199                         %(video_id, sig, timestamp, quality, codec_name.upper())
200
201                 files[key].append({
202                     'ext': codec_extension,
203                     'url': video_url,
204                     'format_id': format_id,
205                     'width': file_info.get('width'),
206                     'height': file_info.get('height'),
207                 })
208         formats = []
209         for key in ('other', 'sd', 'hd'):
210             formats += files[key]
211         if len(formats) == 0:
212             raise ExtractorError(u'No known codec found')
213
214         return [{
215             'id':       video_id,
216             'uploader': video_uploader,
217             'uploader_id': video_uploader_id,
218             'upload_date':  video_upload_date,
219             'title':    video_title,
220             'thumbnail':    video_thumbnail,
221             'description':  video_description,
222             'formats': formats,
223         }]
224
225
226 class VimeoChannelIE(InfoExtractor):
227     IE_NAME = u'vimeo:channel'
228     _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
229     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
230
231     def _real_extract(self, url):
232         mobj = re.match(self._VALID_URL, url)
233         channel_id =  mobj.group('id')
234         video_ids = []
235
236         for pagenum in itertools.count(1):
237             webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
238                                              channel_id, u'Downloading page %s' % pagenum)
239             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
240             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
241                 break
242
243         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
244                    for video_id in video_ids]
245         channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
246                                                 webpage, u'channel title')
247         return {'_type': 'playlist',
248                 'id': channel_id,
249                 'title': channel_title,
250                 'entries': entries,
251                 }