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