]> git.bitcoin.ninja Git - youtube-dl/blob - vimeo.py
512e06e2a620161704c8b1d02854c1279276179e
[youtube-dl] / vimeo.py
1 import json
2 import re
3 import itertools
4
5 from .common import InfoExtractor
6 from ..utils import (
7     compat_urllib_parse,
8     compat_urllib_request,
9
10     clean_html,
11     get_element_by_attribute,
12     ExtractorError,
13     std_headers,
14 )
15
16 class VimeoIE(InfoExtractor):
17     """Information extractor for vimeo.com."""
18
19     # _VALID_URL matches Vimeo URLs
20     _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)(?:[?].*)?$'
21     _NETRC_MACHINE = 'vimeo'
22     IE_NAME = u'vimeo'
23     _TESTS = [
24         {
25             u'url': u'http://vimeo.com/56015672',
26             u'file': u'56015672.mp4',
27             u'md5': u'8879b6cc097e987f02484baf890129e5',
28             u'info_dict': {
29                 u"upload_date": u"20121220", 
30                 u"description": u"This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550", 
31                 u"uploader_id": u"user7108434", 
32                 u"uploader": u"Filippo Valsorda", 
33                 u"title": u"youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
34             },
35         },
36         {
37             u'url': u'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
38             u'file': u'68093876.mp4',
39             u'md5': u'3b5ca6aa22b60dfeeadf50b72e44ed82',
40             u'note': u'Vimeo Pro video (#1197)',
41             u'info_dict': {
42                 u'uploader_id': u'openstreetmapus', 
43                 u'uploader': u'OpenStreetMap US', 
44                 u'title': u'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
45             },
46         },
47     ]
48
49     def _login(self):
50         (username, password) = self._get_login_info()
51         if username is None:
52             return
53         self.report_login()
54         login_url = 'https://vimeo.com/log_in'
55         webpage = self._download_webpage(login_url, None, False)
56         token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
57         data = compat_urllib_parse.urlencode({'email': username,
58                                               'password': password,
59                                               'action': 'login',
60                                               'service': 'vimeo',
61                                               'token': token,
62                                               })
63         login_request = compat_urllib_request.Request(login_url, data)
64         login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
65         login_request.add_header('Cookie', 'xsrft=%s' % token)
66         self._download_webpage(login_request, None, False, u'Wrong login info')
67
68     def _verify_video_password(self, url, video_id, webpage):
69         password = self._downloader.params.get('videopassword', None)
70         if password is None:
71             raise ExtractorError(u'This video is protected by a password, use the --video-password option')
72         token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
73         data = compat_urllib_parse.urlencode({'password': password,
74                                               'token': token})
75         # I didn't manage to use the password with https
76         if url.startswith('https'):
77             pass_url = url.replace('https','http')
78         else:
79             pass_url = url
80         password_request = compat_urllib_request.Request(pass_url+'/password', data)
81         password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
82         password_request.add_header('Cookie', 'xsrft=%s' % token)
83         self._download_webpage(password_request, video_id,
84                                u'Verifying the password',
85                                u'Wrong password')
86
87     def _real_initialize(self):
88         self._login()
89
90     def _real_extract(self, url, new_video=True):
91         # Extract ID from URL
92         mobj = re.match(self._VALID_URL, url)
93         if mobj is None:
94             raise ExtractorError(u'Invalid URL: %s' % url)
95
96         video_id = mobj.group('id')
97         if not mobj.group('proto'):
98             url = 'https://' + url
99         elif mobj.group('pro'):
100             url = 'http://player.vimeo.com/video/' + video_id
101         elif mobj.group('direct_link'):
102             url = 'https://vimeo.com/' + video_id
103
104         # Retrieve video webpage to extract further information
105         request = compat_urllib_request.Request(url, None, std_headers)
106         webpage = self._download_webpage(request, video_id)
107
108         # Now we begin extracting as much information as we can from what we
109         # retrieved. First we extract the information common to all extractors,
110         # and latter we extract those that are Vimeo specific.
111         self.report_extraction(video_id)
112
113         # Extract the config JSON
114         try:
115             config = webpage.split(' = {config:')[1].split(',assets:')[0]
116             config = json.loads(config)
117         except:
118             if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
119                 raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
120
121             if re.search('If so please provide the correct password.', webpage):
122                 self._verify_video_password(url, video_id, webpage)
123                 return self._real_extract(url)
124             else:
125                 raise ExtractorError(u'Unable to extract info section')
126
127         # Extract title
128         video_title = config["video"]["title"]
129
130         # Extract uploader and uploader_id
131         video_uploader = config["video"]["owner"]["name"]
132         video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
133
134         # Extract video thumbnail
135         video_thumbnail = config["video"]["thumbnail"]
136
137         # Extract video description
138         video_description = get_element_by_attribute("itemprop", "description", webpage)
139         if video_description: video_description = clean_html(video_description)
140         else: video_description = u''
141
142         # Extract upload date
143         video_upload_date = None
144         mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
145         if mobj is not None:
146             video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
147
148         # Vimeo specific: extract request signature and timestamp
149         sig = config['request']['signature']
150         timestamp = config['request']['timestamp']
151
152         # Vimeo specific: extract video codec and quality information
153         # First consider quality, then codecs, then take everything
154         # TODO bind to format param
155         codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
156         files = { 'hd': [], 'sd': [], 'other': []}
157         for codec_name, codec_extension in codecs:
158             if codec_name in config["video"]["files"]:
159                 if 'hd' in config["video"]["files"][codec_name]:
160                     files['hd'].append((codec_name, codec_extension, 'hd'))
161                 elif 'sd' in config["video"]["files"][codec_name]:
162                     files['sd'].append((codec_name, codec_extension, 'sd'))
163                 else:
164                     files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
165
166         for quality in ('hd', 'sd', 'other'):
167             if len(files[quality]) > 0:
168                 video_quality = files[quality][0][2]
169                 video_codec = files[quality][0][0]
170                 video_extension = files[quality][0][1]
171                 self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
172                 break
173         else:
174             raise ExtractorError(u'No known codec found')
175
176         video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
177                     %(video_id, sig, timestamp, video_quality, video_codec.upper())
178
179         return [{
180             'id':       video_id,
181             'url':      video_url,
182             'uploader': video_uploader,
183             'uploader_id': video_uploader_id,
184             'upload_date':  video_upload_date,
185             'title':    video_title,
186             'ext':      video_extension,
187             'thumbnail':    video_thumbnail,
188             'description':  video_description,
189         }]
190
191
192 class VimeoChannelIE(InfoExtractor):
193     IE_NAME = u'vimeo:channel'
194     _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
195     _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
196
197     def _real_extract(self, url):
198         mobj = re.match(self._VALID_URL, url)
199         channel_id =  mobj.group('id')
200         video_ids = []
201
202         for pagenum in itertools.count(1):
203             webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
204                                              channel_id, u'Downloading page %s' % pagenum)
205             video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
206             if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
207                 break
208
209         entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
210                    for video_id in video_ids]
211         channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
212                                                 webpage, u'channel title')
213         return {'_type': 'playlist',
214                 'id': channel_id,
215                 'title': channel_title,
216                 'entries': entries,
217                 }