PEP8: applied even more rules
[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 ..compat import (
11     compat_HTTPError,
12     compat_urllib_parse,
13     compat_urllib_request,
14     compat_urlparse,
15 )
16 from ..utils import (
17     ExtractorError,
18     InAdvancePagedList,
19     int_or_none,
20     RegexNotFoundError,
21     std_headers,
22     unsmuggle_url,
23     urlencode_postdata,
24 )
25
26
27 class VimeoBaseInfoExtractor(InfoExtractor):
28     _NETRC_MACHINE = 'vimeo'
29     _LOGIN_REQUIRED = False
30
31     def _login(self):
32         (username, password) = self._get_login_info()
33         if username is None:
34             if self._LOGIN_REQUIRED:
35                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
36             return
37         self.report_login()
38         login_url = 'https://vimeo.com/log_in'
39         webpage = self._download_webpage(login_url, None, False)
40         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
41         data = urlencode_postdata({
42             'email': username,
43             'password': password,
44             'action': 'login',
45             'service': 'vimeo',
46             'token': token,
47         })
48         login_request = compat_urllib_request.Request(login_url, data)
49         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
50         login_request.add_header('Cookie', 'xsrft=%s' % token)
51         self._download_webpage(login_request, None, False, 'Wrong login info')
52
53
54 class VimeoIE(VimeoBaseInfoExtractor, SubtitlesInfoExtractor):
55     """Information extractor for vimeo.com."""
56
57     # _VALID_URL matches Vimeo URLs
58     _VALID_URL = r'''(?x)
59         https?://
60         (?:(?:www|(?P<player>player))\.)?
61         vimeo(?P<pro>pro)?\.com/
62         (?!channels/[^/?#]+/?(?:$|[?#])|album/)
63         (?:.*?/)?
64         (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
65         (?:videos?/)?
66         (?P<id>[0-9]+)
67         /?(?:[?&].*)?(?:[#].*)?$'''
68     IE_NAME = 'vimeo'
69     _TESTS = [
70         {
71             'url': 'http://vimeo.com/56015672#at=0',
72             'md5': '8879b6cc097e987f02484baf890129e5',
73             'info_dict': {
74                 'id': '56015672',
75                 'ext': 'mp4',
76                 "upload_date": "20121220",
77                 "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",
78                 "uploader_id": "user7108434",
79                 "uploader": "Filippo Valsorda",
80                 "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
81                 "duration": 10,
82             },
83         },
84         {
85             'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
86             'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
87             'note': 'Vimeo Pro video (#1197)',
88             'info_dict': {
89                 'id': '68093876',
90                 'ext': 'mp4',
91                 'uploader_id': 'openstreetmapus',
92                 'uploader': 'OpenStreetMap US',
93                 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
94                 'description': 'md5:380943ec71b89736ff4bf27183233d09',
95                 'duration': 1595,
96             },
97         },
98         {
99             'url': 'http://player.vimeo.com/video/54469442',
100             'md5': '619b811a4417aa4abe78dc653becf511',
101             'note': 'Videos that embed the url in the player page',
102             'info_dict': {
103                 'id': '54469442',
104                 'ext': 'mp4',
105                 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
106                 'uploader': 'The BLN & Business of Software',
107                 'uploader_id': 'theblnbusinessofsoftware',
108                 'duration': 3610,
109                 'description': None,
110             },
111         },
112         {
113             'url': 'http://vimeo.com/68375962',
114             'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
115             'note': 'Video protected with password',
116             'info_dict': {
117                 'id': '68375962',
118                 'ext': 'mp4',
119                 'title': 'youtube-dl password protected test video',
120                 'upload_date': '20130614',
121                 'uploader_id': 'user18948128',
122                 'uploader': 'Jaime Marquínez Ferrándiz',
123                 'duration': 10,
124                 'description': 'This is "youtube-dl password protected test video" by Jaime Marquínez Ferrándiz on Vimeo, the home for high quality videos and the people who love them.',
125             },
126             'params': {
127                 'videopassword': 'youtube-dl',
128             },
129         },
130         {
131             'url': 'http://vimeo.com/channels/keypeele/75629013',
132             'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
133             'note': 'Video is freely available via original URL '
134                     'and protected with password when accessed via http://vimeo.com/75629013',
135             'info_dict': {
136                 'id': '75629013',
137                 'ext': 'mp4',
138                 'title': 'Key & Peele: Terrorist Interrogation',
139                 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
140                 'uploader_id': 'atencio',
141                 'uploader': 'Peter Atencio',
142                 'duration': 187,
143             },
144         },
145         {
146             'url': 'http://vimeo.com/76979871',
147             'md5': '3363dd6ffebe3784d56f4132317fd446',
148             'note': 'Video with subtitles',
149             'info_dict': {
150                 'id': '76979871',
151                 'ext': 'mp4',
152                 'title': 'The New Vimeo Player (You Know, For Videos)',
153                 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
154                 'upload_date': '20131015',
155                 'uploader_id': 'staff',
156                 'uploader': 'Vimeo Staff',
157                 'duration': 62,
158             }
159         },
160         {
161             # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
162             'url': 'https://player.vimeo.com/video/98044508',
163             'note': 'The js code contains assignments to the same variable as the config',
164             'info_dict': {
165                 'id': '98044508',
166                 'ext': 'mp4',
167                 'title': 'Pier Solar OUYA Official Trailer',
168                 'uploader': 'Tulio Gonçalves',
169                 'uploader_id': 'user28849593',
170             },
171         },
172     ]
173
174     def _verify_video_password(self, url, video_id, webpage):
175         password = self._downloader.params.get('videopassword', None)
176         if password is None:
177             raise ExtractorError('This video is protected by a password, use the --video-password option')
178         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
179         data = compat_urllib_parse.urlencode({
180             'password': password,
181             'token': token,
182         })
183         # I didn't manage to use the password with https
184         if url.startswith('https'):
185             pass_url = url.replace('https', 'http')
186         else:
187             pass_url = url
188         password_request = compat_urllib_request.Request(pass_url + '/password', data)
189         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
190         password_request.add_header('Cookie', 'xsrft=%s' % token)
191         self._download_webpage(password_request, video_id,
192                                'Verifying the password',
193                                'Wrong password')
194
195     def _verify_player_video_password(self, url, video_id):
196         password = self._downloader.params.get('videopassword', None)
197         if password is None:
198             raise ExtractorError('This video is protected by a password, use the --video-password option')
199         data = compat_urllib_parse.urlencode({'password': password})
200         pass_url = url + '/check-password'
201         password_request = compat_urllib_request.Request(pass_url, data)
202         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
203         return self._download_json(
204             password_request, video_id,
205             'Verifying the password',
206             'Wrong password')
207
208     def _real_initialize(self):
209         self._login()
210
211     def _real_extract(self, url):
212         url, data = unsmuggle_url(url)
213         headers = std_headers
214         if data is not None:
215             headers = headers.copy()
216             headers.update(data)
217         if 'Referer' not in headers:
218             headers['Referer'] = url
219
220         # Extract ID from URL
221         mobj = re.match(self._VALID_URL, url)
222         video_id = mobj.group('id')
223         orig_url = url
224         if mobj.group('pro') or mobj.group('player'):
225             url = 'http://player.vimeo.com/video/' + video_id
226
227         # Retrieve video webpage to extract further information
228         request = compat_urllib_request.Request(url, None, headers)
229         try:
230             webpage = self._download_webpage(request, video_id)
231         except ExtractorError as ee:
232             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
233                 errmsg = ee.cause.read()
234                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
235                     raise ExtractorError(
236                         'Cannot download embed-only video without embedding '
237                         'URL. Please call youtube-dl with the URL of the page '
238                         'that embeds this video.',
239                         expected=True)
240             raise
241
242         # Now we begin extracting as much information as we can from what we
243         # retrieved. First we extract the information common to all extractors,
244         # and latter we extract those that are Vimeo specific.
245         self.report_extraction(video_id)
246
247         # Extract the config JSON
248         try:
249             try:
250                 config_url = self._html_search_regex(
251                     r' data-config-url="(.+?)"', webpage, 'config URL')
252                 config_json = self._download_webpage(config_url, video_id)
253                 config = json.loads(config_json)
254             except RegexNotFoundError:
255                 # For pro videos or player.vimeo.com urls
256                 # We try to find out to which variable is assigned the config dic
257                 m_variable_name = re.search('(\w)\.video\.id', webpage)
258                 if m_variable_name is not None:
259                     config_re = r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))
260                 else:
261                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
262                 config = self._search_regex(config_re, webpage, 'info section',
263                                             flags=re.DOTALL)
264                 config = json.loads(config)
265         except Exception as e:
266             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
267                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
268
269             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
270                 self._verify_video_password(url, video_id, webpage)
271                 return self._real_extract(url)
272             else:
273                 raise ExtractorError('Unable to extract info section',
274                                      cause=e)
275         else:
276             if config.get('view') == 4:
277                 config = self._verify_player_video_password(url, video_id)
278
279         # Extract title
280         video_title = config["video"]["title"]
281
282         # Extract uploader and uploader_id
283         video_uploader = config["video"]["owner"]["name"]
284         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
285
286         # Extract video thumbnail
287         video_thumbnail = config["video"].get("thumbnail")
288         if video_thumbnail is None:
289             video_thumbs = config["video"].get("thumbs")
290             if video_thumbs and isinstance(video_thumbs, dict):
291                 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
292
293         # Extract video description
294
295         video_description = self._html_search_regex(
296             r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
297             webpage, 'description', default=None)
298         if not video_description:
299             video_description = self._html_search_meta(
300                 'description', webpage, default=None)
301         if not video_description and mobj.group('pro'):
302             orig_webpage = self._download_webpage(
303                 orig_url, video_id,
304                 note='Downloading webpage for description',
305                 fatal=False)
306             if orig_webpage:
307                 video_description = self._html_search_meta(
308                     'description', orig_webpage, default=None)
309         if not video_description and not mobj.group('player'):
310             self._downloader.report_warning('Cannot find video description')
311
312         # Extract video duration
313         video_duration = int_or_none(config["video"].get("duration"))
314
315         # Extract upload date
316         video_upload_date = None
317         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
318         if mobj is not None:
319             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
320
321         try:
322             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
323             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
324             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
325         except RegexNotFoundError:
326             # This info is only available in vimeo.com/{id} urls
327             view_count = None
328             like_count = None
329             comment_count = None
330
331         # Vimeo specific: extract request signature and timestamp
332         sig = config['request']['signature']
333         timestamp = config['request']['timestamp']
334
335         # Vimeo specific: extract video codec and quality information
336         # First consider quality, then codecs, then take everything
337         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
338         files = {'hd': [], 'sd': [], 'other': []}
339         config_files = config["video"].get("files") or config["request"].get("files")
340         for codec_name, codec_extension in codecs:
341             for quality in config_files.get(codec_name, []):
342                 format_id = '-'.join((codec_name, quality)).lower()
343                 key = quality if quality in files else 'other'
344                 video_url = None
345                 if isinstance(config_files[codec_name], dict):
346                     file_info = config_files[codec_name][quality]
347                     video_url = file_info.get('url')
348                 else:
349                     file_info = {}
350                 if video_url is None:
351                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
352                         % (video_id, sig, timestamp, quality, codec_name.upper())
353
354                 files[key].append({
355                     'ext': codec_extension,
356                     'url': video_url,
357                     'format_id': format_id,
358                     'width': file_info.get('width'),
359                     'height': file_info.get('height'),
360                 })
361         formats = []
362         for key in ('other', 'sd', 'hd'):
363             formats += files[key]
364         if len(formats) == 0:
365             raise ExtractorError('No known codec found')
366
367         subtitles = {}
368         text_tracks = config['request'].get('text_tracks')
369         if text_tracks:
370             for tt in text_tracks:
371                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
372
373         video_subtitles = self.extract_subtitles(video_id, subtitles)
374         if self._downloader.params.get('listsubtitles', False):
375             self._list_available_subtitles(video_id, subtitles)
376             return
377
378         return {
379             'id': video_id,
380             'uploader': video_uploader,
381             'uploader_id': video_uploader_id,
382             'upload_date': video_upload_date,
383             'title': video_title,
384             'thumbnail': video_thumbnail,
385             'description': video_description,
386             'duration': video_duration,
387             'formats': formats,
388             'webpage_url': url,
389             'view_count': view_count,
390             'like_count': like_count,
391             'comment_count': comment_count,
392             'subtitles': video_subtitles,
393         }
394
395
396 class VimeoChannelIE(InfoExtractor):
397     IE_NAME = 'vimeo:channel'
398     _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
399     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
400     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
401     _TESTS = [{
402         'url': 'http://vimeo.com/channels/tributes',
403         'info_dict': {
404             'title': 'Vimeo Tributes',
405         },
406         'playlist_mincount': 25,
407     }]
408
409     def _page_url(self, base_url, pagenum):
410         return '%s/videos/page:%d/' % (base_url, pagenum)
411
412     def _extract_list_title(self, webpage):
413         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
414
415     def _extract_videos(self, list_id, base_url):
416         video_ids = []
417         for pagenum in itertools.count(1):
418             webpage = self._download_webpage(
419                 self._page_url(base_url, pagenum), list_id,
420                 'Downloading page %s' % pagenum)
421             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
422             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
423                 break
424
425         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
426                    for video_id in video_ids]
427         return {'_type': 'playlist',
428                 'id': list_id,
429                 'title': self._extract_list_title(webpage),
430                 'entries': entries,
431                 }
432
433     def _real_extract(self, url):
434         mobj = re.match(self._VALID_URL, url)
435         channel_id = mobj.group('id')
436         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
437
438
439 class VimeoUserIE(VimeoChannelIE):
440     IE_NAME = 'vimeo:user'
441     _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
442     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
443     _TESTS = [{
444         'url': 'http://vimeo.com/nkistudio/videos',
445         'info_dict': {
446             'title': 'Nki',
447         },
448         'playlist_mincount': 66,
449     }]
450
451     def _real_extract(self, url):
452         mobj = re.match(self._VALID_URL, url)
453         name = mobj.group('name')
454         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
455
456
457 class VimeoAlbumIE(VimeoChannelIE):
458     IE_NAME = 'vimeo:album'
459     _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
460     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
461     _TESTS = [{
462         'url': 'http://vimeo.com/album/2632481',
463         'info_dict': {
464             'title': 'Staff Favorites: November 2013',
465         },
466         'playlist_mincount': 13,
467     }]
468
469     def _page_url(self, base_url, pagenum):
470         return '%s/page:%d/' % (base_url, pagenum)
471
472     def _real_extract(self, url):
473         mobj = re.match(self._VALID_URL, url)
474         album_id = mobj.group('id')
475         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
476
477
478 class VimeoGroupsIE(VimeoAlbumIE):
479     IE_NAME = 'vimeo:group'
480     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
481     _TESTS = [{
482         'url': 'http://vimeo.com/groups/rolexawards',
483         'info_dict': {
484             'title': 'Rolex Awards for Enterprise',
485         },
486         'playlist_mincount': 73,
487     }]
488
489     def _extract_list_title(self, webpage):
490         return self._og_search_title(webpage)
491
492     def _real_extract(self, url):
493         mobj = re.match(self._VALID_URL, url)
494         name = mobj.group('name')
495         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
496
497
498 class VimeoReviewIE(InfoExtractor):
499     IE_NAME = 'vimeo:review'
500     IE_DESC = 'Review pages on vimeo'
501     _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
502     _TESTS = [{
503         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
504         'file': '75524534.mp4',
505         'md5': 'c507a72f780cacc12b2248bb4006d253',
506         'info_dict': {
507             'title': "DICK HARDWICK 'Comedian'",
508             'uploader': 'Richard Hardwick',
509         }
510     }, {
511         'note': 'video player needs Referer',
512         'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
513         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
514         'info_dict': {
515             'id': '91613211',
516             'ext': 'mp4',
517             'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
518             'uploader': 'DevWeek Events',
519             'duration': 2773,
520             'thumbnail': 're:^https?://.*\.jpg$',
521         }
522     }]
523
524     def _real_extract(self, url):
525         mobj = re.match(self._VALID_URL, url)
526         video_id = mobj.group('id')
527         player_url = 'https://player.vimeo.com/player/' + video_id
528         return self.url_result(player_url, 'Vimeo', video_id)
529
530
531 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
532     IE_NAME = 'vimeo:watchlater'
533     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
534     _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
535     _LOGIN_REQUIRED = True
536     _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
537     _TESTS = [{
538         'url': 'http://vimeo.com/home/watchlater',
539         'only_matching': True,
540     }]
541
542     def _real_initialize(self):
543         self._login()
544
545     def _page_url(self, base_url, pagenum):
546         url = '%s/page:%d/' % (base_url, pagenum)
547         request = compat_urllib_request.Request(url)
548         # Set the header to get a partial html page with the ids,
549         # the normal page doesn't contain them.
550         request.add_header('X-Requested-With', 'XMLHttpRequest')
551         return request
552
553     def _real_extract(self, url):
554         return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')
555
556
557 class VimeoLikesIE(InfoExtractor):
558     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
559     IE_NAME = 'vimeo:likes'
560     IE_DESC = 'Vimeo user likes'
561     _TEST = {
562         'url': 'https://vimeo.com/user755559/likes/',
563         'playlist_mincount': 293,
564         "info_dict": {
565             "description": "See all the videos urza likes",
566             "title": 'Videos urza likes',
567         },
568     }
569
570     def _real_extract(self, url):
571         user_id = self._match_id(url)
572         webpage = self._download_webpage(url, user_id)
573         page_count = self._int(
574             self._search_regex(
575                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
576                     .*?</a></li>\s*<li\s+class="pagination_next">
577                 ''', webpage, 'page count'),
578             'page count', fatal=True)
579         PAGE_SIZE = 12
580         title = self._html_search_regex(
581             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
582         description = self._html_search_meta('description', webpage)
583
584         def _get_page(idx):
585             page_url = '%s//vimeo.com/user%s/likes/page:%d/sort:date' % (
586                 self.http_scheme(), user_id, idx + 1)
587             webpage = self._download_webpage(
588                 page_url, user_id,
589                 note='Downloading page %d/%d' % (idx + 1, page_count))
590             video_list = self._search_regex(
591                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
592                 webpage, 'video content')
593             paths = re.findall(
594                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
595             for path in paths:
596                 yield {
597                     '_type': 'url',
598                     'url': compat_urlparse.urljoin(page_url, path),
599                 }
600
601         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
602
603         return {
604             '_type': 'playlist',
605             'id': 'user%s_likes' % user_id,
606             'title': title,
607             'description': description,
608             'entries': pl,
609         }