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