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