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