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