[vimeo] Use regexps to find description
[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 = self._html_search_regex(
279             r'(?s)<div class="[^"]*description"[^>]*>(.*?)</div>',
280             webpage, 'description', fatal=False)
281
282         # Extract video duration
283         video_duration = int_or_none(config["video"].get("duration"))
284
285         # Extract upload date
286         video_upload_date = None
287         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
288         if mobj is not None:
289             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
290
291         try:
292             view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
293             like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
294             comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
295         except RegexNotFoundError:
296             # This info is only available in vimeo.com/{id} urls
297             view_count = None
298             like_count = None
299             comment_count = None
300
301         # Vimeo specific: extract request signature and timestamp
302         sig = config['request']['signature']
303         timestamp = config['request']['timestamp']
304
305         # Vimeo specific: extract video codec and quality information
306         # First consider quality, then codecs, then take everything
307         codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
308         files = {'hd': [], 'sd': [], 'other': []}
309         config_files = config["video"].get("files") or config["request"].get("files")
310         for codec_name, codec_extension in codecs:
311             for quality in config_files.get(codec_name, []):
312                 format_id = '-'.join((codec_name, quality)).lower()
313                 key = quality if quality in files else 'other'
314                 video_url = None
315                 if isinstance(config_files[codec_name], dict):
316                     file_info = config_files[codec_name][quality]
317                     video_url = file_info.get('url')
318                 else:
319                     file_info = {}
320                 if video_url is None:
321                     video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
322                         % (video_id, sig, timestamp, quality, codec_name.upper())
323
324                 files[key].append({
325                     'ext': codec_extension,
326                     'url': video_url,
327                     'format_id': format_id,
328                     'width': file_info.get('width'),
329                     'height': file_info.get('height'),
330                 })
331         formats = []
332         for key in ('other', 'sd', 'hd'):
333             formats += files[key]
334         if len(formats) == 0:
335             raise ExtractorError('No known codec found')
336
337         subtitles = {}
338         text_tracks = config['request'].get('text_tracks')
339         if text_tracks:
340             for tt in text_tracks:
341                 subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
342
343         video_subtitles = self.extract_subtitles(video_id, subtitles)
344         if self._downloader.params.get('listsubtitles', False):
345             self._list_available_subtitles(video_id, subtitles)
346             return
347
348         return {
349             'id': video_id,
350             'uploader': video_uploader,
351             'uploader_id': video_uploader_id,
352             'upload_date': video_upload_date,
353             'title': video_title,
354             'thumbnail': video_thumbnail,
355             'description': video_description,
356             'duration': video_duration,
357             'formats': formats,
358             'webpage_url': url,
359             'view_count': view_count,
360             'like_count': like_count,
361             'comment_count': comment_count,
362             'subtitles': video_subtitles,
363         }
364
365
366 class VimeoChannelIE(InfoExtractor):
367     IE_NAME = 'vimeo:channel'
368     _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
369     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
370     _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
371     _TESTS = [{
372         'url': 'http://vimeo.com/channels/tributes',
373         'info_dict': {
374             'title': 'Vimeo Tributes',
375         },
376         'playlist_mincount': 25,
377     }]
378
379     def _page_url(self, base_url, pagenum):
380         return '%s/videos/page:%d/' % (base_url, pagenum)
381
382     def _extract_list_title(self, webpage):
383         return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
384
385     def _extract_videos(self, list_id, base_url):
386         video_ids = []
387         for pagenum in itertools.count(1):
388             webpage = self._download_webpage(
389                 self._page_url(base_url, pagenum), list_id,
390                 'Downloading page %s' % pagenum)
391             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
392             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
393                 break
394
395         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
396                    for video_id in video_ids]
397         return {'_type': 'playlist',
398                 'id': list_id,
399                 'title': self._extract_list_title(webpage),
400                 'entries': entries,
401                 }
402
403     def _real_extract(self, url):
404         mobj = re.match(self._VALID_URL, url)
405         channel_id = mobj.group('id')
406         return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
407
408
409 class VimeoUserIE(VimeoChannelIE):
410     IE_NAME = 'vimeo:user'
411     _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
412     _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
413     _TESTS = [{
414         'url': 'http://vimeo.com/nkistudio/videos',
415         'info_dict': {
416             'title': 'Nki',
417         },
418         'playlist_mincount': 66,
419     }]
420
421     def _real_extract(self, url):
422         mobj = re.match(self._VALID_URL, url)
423         name = mobj.group('name')
424         return self._extract_videos(name, 'http://vimeo.com/%s' % name)
425
426
427 class VimeoAlbumIE(VimeoChannelIE):
428     IE_NAME = 'vimeo:album'
429     _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
430     _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
431     _TESTS = [{
432         'url': 'http://vimeo.com/album/2632481',
433         'info_dict': {
434             'title': 'Staff Favorites: November 2013',
435         },
436         'playlist_mincount': 13,
437     }]
438
439     def _page_url(self, base_url, pagenum):
440         return '%s/page:%d/' % (base_url, pagenum)
441
442     def _real_extract(self, url):
443         mobj = re.match(self._VALID_URL, url)
444         album_id = mobj.group('id')
445         return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
446
447
448 class VimeoGroupsIE(VimeoAlbumIE):
449     IE_NAME = 'vimeo:group'
450     _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
451     _TESTS = [{
452         'url': 'http://vimeo.com/groups/rolexawards',
453         'info_dict': {
454             'title': 'Rolex Awards for Enterprise',
455         },
456         'playlist_mincount': 73,
457     }]
458
459     def _extract_list_title(self, webpage):
460         return self._og_search_title(webpage)
461
462     def _real_extract(self, url):
463         mobj = re.match(self._VALID_URL, url)
464         name = mobj.group('name')
465         return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
466
467
468 class VimeoReviewIE(InfoExtractor):
469     IE_NAME = 'vimeo:review'
470     IE_DESC = 'Review pages on vimeo'
471     _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
472     _TESTS = [{
473         'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
474         'file': '75524534.mp4',
475         'md5': 'c507a72f780cacc12b2248bb4006d253',
476         'info_dict': {
477             'title': "DICK HARDWICK 'Comedian'",
478             'uploader': 'Richard Hardwick',
479         }
480     }, {
481         'note': 'video player needs Referer',
482         'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
483         'md5': '6295fdab8f4bf6a002d058b2c6dce276',
484         'info_dict': {
485             'id': '91613211',
486             'ext': 'mp4',
487             'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
488             'uploader': 'DevWeek Events',
489             'duration': 2773,
490             'thumbnail': 're:^https?://.*\.jpg$',
491         }
492     }]
493
494     def _real_extract(self, url):
495         mobj = re.match(self._VALID_URL, url)
496         video_id = mobj.group('id')
497         player_url = 'https://player.vimeo.com/player/' + video_id
498         return self.url_result(player_url, 'Vimeo', video_id)
499
500
501 class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
502     IE_NAME = 'vimeo:watchlater'
503     IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
504     _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
505     _LOGIN_REQUIRED = True
506     _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
507     _TESTS = [{
508         'url': 'http://vimeo.com/home/watchlater',
509         'only_matching': True,
510     }]
511
512     def _real_initialize(self):
513         self._login()
514
515     def _page_url(self, base_url, pagenum):
516         url = '%s/page:%d/' % (base_url, pagenum)
517         request = compat_urllib_request.Request(url)
518         # Set the header to get a partial html page with the ids,
519         # the normal page doesn't contain them.
520         request.add_header('X-Requested-With', 'XMLHttpRequest')
521         return request
522
523     def _real_extract(self, url):
524         return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')
525
526
527 class VimeoLikesIE(InfoExtractor):
528     _VALID_URL = r'https?://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes/?(?:$|[?#]|sort:)'
529     IE_NAME = 'vimeo:likes'
530     IE_DESC = 'Vimeo user likes'
531     _TEST = {
532         'url': 'https://vimeo.com/user755559/likes/',
533         'playlist_mincount': 293,
534         "info_dict": {
535             "description": "See all the videos urza likes",
536             "title": 'Videos urza likes',
537         },
538     }
539
540     def _real_extract(self, url):
541         user_id = self._match_id(url)
542         webpage = self._download_webpage(url, user_id)
543         page_count = self._int(
544             self._search_regex(
545                 r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
546                     .*?</a></li>\s*<li\s+class="pagination_next">
547                 ''', webpage, 'page count'),
548             'page count', fatal=True)
549         PAGE_SIZE = 12
550         title = self._html_search_regex(
551             r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
552         description = self._html_search_meta('description', webpage)
553
554         def _get_page(idx):
555             page_url = '%s//vimeo.com/user%s/likes/page:%d/sort:date' % (
556                 self.http_scheme(), user_id, idx + 1)
557             webpage = self._download_webpage(
558                 page_url, user_id,
559                 note='Downloading page %d/%d' % (idx + 1, page_count))
560             video_list = self._search_regex(
561                 r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
562                 webpage, 'video content')
563             paths = re.findall(
564                 r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
565             for path in paths:
566                 yield {
567                     '_type': 'url',
568                     'url': compat_urlparse.urljoin(page_url, path),
569                 }
570
571         pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
572
573         return {
574             '_type': 'playlist',
575             'id': 'user%s_likes' % user_id,
576             'title': title,
577             'description': description,
578             'entries': pl,
579         }