Merge branch 'walla' of https://github.com/lenaten/youtube-dl into lenaten-walla
[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     clean_html,
12     compat_HTTPError,
13     compat_urllib_parse,
14     compat_urllib_request,
15     compat_urlparse,
16     ExtractorError,
17     get_element_by_attribute,
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         (?P<proto>(?: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
162     def _verify_video_password(self, url, video_id, webpage):
163         password = self._downloader.params.get('videopassword', None)
164         if password is None:
165             raise ExtractorError('This video is protected by a password, use the --video-password option')
166         token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
167         data = compat_urllib_parse.urlencode({
168             'password': password,
169             'token': token,
170         })
171         # I didn't manage to use the password with https
172         if url.startswith('https'):
173             pass_url = url.replace('https', 'http')
174         else:
175             pass_url = url
176         password_request = compat_urllib_request.Request(pass_url + '/password', data)
177         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
178         password_request.add_header('Cookie', 'xsrft=%s' % token)
179         self._download_webpage(password_request, video_id,
180                                'Verifying the password',
181                                'Wrong password')
182
183     def _verify_player_video_password(self, url, video_id):
184         password = self._downloader.params.get('videopassword', None)
185         if password is None:
186             raise ExtractorError('This video is protected by a password, use the --video-password option')
187         data = compat_urllib_parse.urlencode({'password': password})
188         pass_url = url + '/check-password'
189         password_request = compat_urllib_request.Request(pass_url, data)
190         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
191         return self._download_json(
192             password_request, video_id,
193             'Verifying the password',
194             'Wrong password')
195
196     def _real_initialize(self):
197         self._login()
198
199     def _real_extract(self, url):
200         url, data = unsmuggle_url(url)
201         headers = std_headers
202         if data is not None:
203             headers = headers.copy()
204             headers.update(data)
205         if 'Referer' not in headers:
206             headers['Referer'] = url
207
208         # Extract ID from URL
209         mobj = re.match(self._VALID_URL, url)
210         video_id = mobj.group('id')
211         orig_url = url
212         if mobj.group('pro') or mobj.group('player'):
213             url = 'http://player.vimeo.com/video/' + video_id
214
215         # Retrieve video webpage to extract further information
216         request = compat_urllib_request.Request(url, None, headers)
217         try:
218             webpage = self._download_webpage(request, video_id)
219         except ExtractorError as ee:
220             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
221                 errmsg = ee.cause.read()
222                 if b'Because of its privacy settings, this video cannot be played here' in errmsg:
223                     raise ExtractorError(
224                         'Cannot download embed-only video without embedding '
225                         'URL. Please call youtube-dl with the URL of the page '
226                         'that embeds this video.',
227                         expected=True)
228             raise
229
230         # Now we begin extracting as much information as we can from what we
231         # retrieved. First we extract the information common to all extractors,
232         # and latter we extract those that are Vimeo specific.
233         self.report_extraction(video_id)
234
235         # Extract the config JSON
236         try:
237             try:
238                 config_url = self._html_search_regex(
239                     r' data-config-url="(.+?)"', webpage, 'config URL')
240                 config_json = self._download_webpage(config_url, video_id)
241                 config = json.loads(config_json)
242             except RegexNotFoundError:
243                 # For pro videos or player.vimeo.com urls
244                 # We try to find out to which variable is assigned the config dic
245                 m_variable_name = re.search('(\w)\.video\.id', webpage)
246                 if m_variable_name is not None:
247                     config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
248                 else:
249                     config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
250                 config = self._search_regex(config_re, webpage, 'info section',
251                     flags=re.DOTALL)
252                 config = json.loads(config)
253         except Exception as e:
254             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
255                 raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
256
257             if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
258                 self._verify_video_password(url, video_id, webpage)
259                 return self._real_extract(url)
260             else:
261                 raise ExtractorError('Unable to extract info section',
262                                      cause=e)
263         else:
264             if config.get('view') == 4:
265                 config = self._verify_player_video_password(url, video_id)
266
267         # Extract title
268         video_title = config["video"]["title"]
269
270         # Extract uploader and uploader_id
271         video_uploader = config["video"]["owner"]["name"]
272         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
273
274         # Extract video thumbnail
275         video_thumbnail = config["video"].get("thumbnail")
276         if video_thumbnail is None:
277             video_thumbs = config["video"].get("thumbs")
278             if video_thumbs and isinstance(video_thumbs, dict):
279                 _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
280
281         # Extract video description
282
283         video_description = self._html_search_regex(
284             r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
285             webpage, 'description', default=None)
286         if not video_description:
287             video_description = self._html_search_meta(
288                 'description', webpage, default=None)
289         if not video_description and mobj.group('pro'):
290             orig_webpage = self._download_webpage(
291                 orig_url, video_id,
292                 note='Downloading webpage for description',
293                 fatal=False)
294             if orig_webpage:
295                 video_description = self._html_search_meta(
296                     'description', orig_webpage, default=None)
297         if not video_description and not mobj.group('player'):
298             self._downloader.report_warning('Cannot find video description')
299
300         # Extract video duration
301         video_duration = int_or_none(config["video"].get("duration"))
302
303         # Extract upload date
304         video_upload_date = None
305         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
306         if mobj is not None:
307             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
308
309         try:
310             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
311             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
312             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
313         except RegexNotFoundError:
314             # This info is only available in vimeo.com/{id} urls
315             view_count = None
316             like_count = None
317             comment_count = None
318
319         # Vimeo specific: extract request signature and timestamp
320         sig = config['request']['signature']
321         timestamp = config['request']['timestamp']
322
323         # Vimeo specific: extract video codec and quality information
324         # First consider quality, then codecs, then take everything
325         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
326         files = {'hd': [], 'sd': [], 'other': []}
327         config_files = config["video"].get("files") or config["request"].get("files")
328         for codec_name, codec_extension in codecs:
329             for quality in config_files.get(codec_name, []):
330                 format_id = '-'.join((codec_name, quality)).lower()
331                 key = quality if quality in files else 'other'
332                 video_url = None
333                 if isinstance(config_files[codec_name], dict):
334                     file_info = config_files[codec_name][quality]
335                     video_url = file_info.get('url')
336                 else:
337                     file_info = {}
338                 if video_url is None:
339                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
340                         % (video_id, sig, timestamp, quality, codec_name.upper())
341
342                 files[key].append({
343                     'ext': codec_extension,
344                     'url': video_url,
345                     'format_id': format_id,
346                     'width': file_info.get('width'),
347                     'height': file_info.get('height'),
348                 })
349         formats = []
350         for key in ('other', 'sd', 'hd'):
351             formats += files[key]
352         if len(formats) == 0:
353             raise ExtractorError('No known codec found')
354
355         subtitles = {}
356         text_tracks = config['request'].get('text_tracks')
357         if text_tracks:
358             for tt in text_tracks:
359                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
360
361         video_subtitles = self.extract_subtitles(video_id, subtitles)
362         if self._downloader.params.get('listsubtitles', False):
363             self._list_available_subtitles(video_id, subtitles)
364             return
365
366         return {
367             'id': video_id,
368             'uploader': video_uploader,
369             'uploader_id': video_uploader_id,
370             'upload_date': video_upload_date,
371             'title': video_title,
372             'thumbnail': video_thumbnail,
373             'description': video_description,
374             'duration': video_duration,
375             'formats': formats,
376             'webpage_url': url,
377             'view_count': view_count,
378             'like_count': like_count,
379             'comment_count': comment_count,
380             'subtitles': video_subtitles,
381         }
382
383
384 class VimeoChannelIE(InfoExtractor):
385     IE_NAME = 'vimeo:channel'
386     _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
387     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
388     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
389     _TESTS = [{
390         'url': 'http://vimeo.com/channels/tributes',
391         'info_dict': {
392             'title': 'Vimeo Tributes',
393         },
394         'playlist_mincount': 25,
395     }]
396
397     def _page_url(self, base_url, pagenum):
398         return '%s/videos/page:%d/' % (base_url, pagenum)
399
400     def _extract_list_title(self, webpage):
401         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
402
403     def _extract_videos(self, list_id, base_url):
404         video_ids = []
405         for pagenum in itertools.count(1):
406             webpage = self._download_webpage(
407                 self._page_url(base_url, pagenum), list_id,
408                 'Downloading page %s' % pagenum)
409             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
410             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
411                 break
412
413         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
414                    for video_id in video_ids]
415         return {'_type': 'playlist',
416                 'id': list_id,
417                 'title': self._extract_list_title(webpage),
418                 'entries': entries,
419                 }
420
421     def _real_extract(self, url):
422         mobj = re.match(self._VALID_URL, url)
423         channel_id = mobj.group('id')
424         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
425
426
427 class VimeoUserIE(VimeoChannelIE):
428     IE_NAME = 'vimeo:user'
429     _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
430     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
431     _TESTS = [{
432         'url': 'http://vimeo.com/nkistudio/videos',
433         'info_dict': {
434             'title': 'Nki',
435         },
436         'playlist_mincount': 66,
437     }]
438
439     def _real_extract(self, url):
440         mobj = re.match(self._VALID_URL, url)
441         name = mobj.group('name')
442         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
443
444
445 class VimeoAlbumIE(VimeoChannelIE):
446     IE_NAME = 'vimeo:album'
447     _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
448     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
449     _TESTS = [{
450         'url': 'http://vimeo.com/album/2632481',
451         'info_dict': {
452             'title': 'Staff Favorites: November 2013',
453         },
454         'playlist_mincount': 13,
455     }]
456
457     def _page_url(self, base_url, pagenum):
458         return '%s/page:%d/' % (base_url, pagenum)
459
460     def _real_extract(self, url):
461         mobj = re.match(self._VALID_URL, url)
462         album_id = mobj.group('id')
463         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
464
465
466 class VimeoGroupsIE(VimeoAlbumIE):
467     IE_NAME = 'vimeo:group'
468     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
469     _TESTS = [{
470         'url': 'http://vimeo.com/groups/rolexawards',
471         'info_dict': {
472             'title': 'Rolex Awards for Enterprise',
473         },
474         'playlist_mincount': 73,
475     }]
476
477     def _extract_list_title(self, webpage):
478         return self._og_search_title(webpage)
479
480     def _real_extract(self, url):
481         mobj = re.match(self._VALID_URL, url)
482         name = mobj.group('name')
483         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
484
485
486 class VimeoReviewIE(InfoExtractor):
487     IE_NAME = 'vimeo:review'
488     IE_DESC = 'Review pages on vimeo'
489     _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
490     _TESTS = [{
491         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
492         'file': '75524534.mp4',
493         'md5': 'c507a72f780cacc12b2248bb4006d253',
494         'info_dict': {
495             'title': "DICK HARDWICK 'Comedian'",
496             'uploader': 'Richard Hardwick',
497         }
498     }, {
499         'note': 'video player needs Referer',
500         'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
501         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
502         'info_dict': {
503             'id': '91613211',
504             'ext': 'mp4',
505             'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
506             'uploader': 'DevWeek Events',
507             'duration': 2773,
508             'thumbnail': 're:^https?://.*\.jpg$',
509         }
510     }]
511
512     def _real_extract(self, url):
513         mobj = re.match(self._VALID_URL, url)
514         video_id = mobj.group('id')
515         player_url = 'https://player.vimeo.com/player/' + video_id
516         return self.url_result(player_url, 'Vimeo', video_id)
517
518
519 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
520     IE_NAME = 'vimeo:watchlater'
521     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
522     _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
523     _LOGIN_REQUIRED = True
524     _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
525     _TESTS = [{
526         'url': 'http://vimeo.com/home/watchlater',
527         'only_matching': True,
528     }]
529
530     def _real_initialize(self):
531         self._login()
532
533     def _page_url(self, base_url, pagenum):
534         url = '%s/page:%d/' % (base_url, pagenum)
535         request = compat_urllib_request.Request(url)
536         # Set the header to get a partial html page with the ids,
537         # the normal page doesn't contain them.
538         request.add_header('X-Requested-With', 'XMLHttpRequest')
539         return request
540
541     def _real_extract(self, url):
542         return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')
543
544
545 class VimeoLikesIE(InfoExtractor):
546     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
547     IE_NAME = 'vimeo:likes'
548     IE_DESC = 'Vimeo user likes'
549     _TEST = {
550         'url': 'https://vimeo.com/user755559/likes/',
551         'playlist_mincount': 293,
552         "info_dict": {
553             "description": "See all the videos urza likes",
554             "title": 'Videos urza likes',
555         },
556     }
557
558     def _real_extract(self, url):
559         user_id = self._match_id(url)
560         webpage = self._download_webpage(url, user_id)
561         page_count = self._int(
562             self._search_regex(
563                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
564                     .*?</a></li>\s*<li\s+class="pagination_next">
565                 ''', webpage, 'page count'),
566             'page count', fatal=True)
567         PAGE_SIZE = 12
568         title = self._html_search_regex(
569             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
570         description = self._html_search_meta('description', webpage)
571
572         def _get_page(idx):
573             page_url = '%s//vimeo.com/user%s/likes/page:%d/sort:date' % (
574                 self.http_scheme(), user_id, idx + 1)
575             webpage = self._download_webpage(
576                 page_url, user_id,
577                 note='Downloading page %d/%d' % (idx + 1, page_count))
578             video_list = self._search_regex(
579                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
580                 webpage, 'video content')
581             paths = re.findall(
582                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
583             for path in paths:
584                 yield {
585                     '_type': 'url',
586                     'url': compat_urlparse.urljoin(page_url, path),
587                 }
588
589         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
590
591         return {
592             '_type': 'playlist',
593             'id': 'user%s_likes' % user_id,
594             'title': title,
595             'description': description,
596             'entries': pl,
597         }