]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/udemy.py
debian/changelog: Annotate with another bug being closed.
[youtubedl] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7 compat_HTTPError,
8 compat_kwargs,
9 compat_str,
10 compat_urllib_request,
11 compat_urlparse,
12 )
13 from ..utils import (
14 determine_ext,
15 extract_attributes,
16 ExtractorError,
17 float_or_none,
18 int_or_none,
19 js_to_json,
20 sanitized_Request,
21 unescapeHTML,
22 urlencode_postdata,
23 )
24
25
26 class UdemyIE(InfoExtractor):
27 IE_NAME = 'udemy'
28 _VALID_URL = r'''(?x)
29 https?://
30 www\.udemy\.com/
31 (?:
32 [^#]+\#/lecture/|
33 lecture/view/?\?lectureId=|
34 [^/]+/learn/v4/t/lecture/
35 )
36 (?P<id>\d+)
37 '''
38 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
39 _ORIGIN_URL = 'https://www.udemy.com'
40 _NETRC_MACHINE = 'udemy'
41
42 _TESTS = [{
43 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
44 'md5': '98eda5b657e752cf945d8445e261b5c5',
45 'info_dict': {
46 'id': '160614',
47 'ext': 'mp4',
48 'title': 'Introduction and Installation',
49 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
50 'duration': 579.29,
51 },
52 'skip': 'Requires udemy account credentials',
53 }, {
54 # new URL schema
55 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
56 'only_matching': True,
57 }, {
58 # no url in outputs format entry
59 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
60 'only_matching': True,
61 }]
62
63 def _extract_course_info(self, webpage, video_id):
64 course = self._parse_json(
65 unescapeHTML(self._search_regex(
66 r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
67 webpage, 'course', default='{}')),
68 video_id, fatal=False) or {}
69 course_id = course.get('id') or self._search_regex(
70 r'data-course-id=["\'](\d+)', webpage, 'course id')
71 return course_id, course.get('title')
72
73 def _enroll_course(self, base_url, webpage, course_id):
74 def combine_url(base_url, url):
75 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
76
77 checkout_url = unescapeHTML(self._search_regex(
78 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
79 webpage, 'checkout url', group='url', default=None))
80 if checkout_url:
81 raise ExtractorError(
82 'Course %s is not free. You have to pay for it before you can download. '
83 'Use this URL to confirm purchase: %s'
84 % (course_id, combine_url(base_url, checkout_url)),
85 expected=True)
86
87 enroll_url = unescapeHTML(self._search_regex(
88 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
89 webpage, 'enroll url', group='url', default=None))
90 if enroll_url:
91 webpage = self._download_webpage(
92 combine_url(base_url, enroll_url),
93 course_id, 'Enrolling in the course',
94 headers={'Referer': base_url})
95 if '>You have enrolled in' in webpage:
96 self.to_screen('%s: Successfully enrolled in the course' % course_id)
97
98 def _download_lecture(self, course_id, lecture_id):
99 return self._download_json(
100 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
101 % (course_id, lecture_id),
102 lecture_id, 'Downloading lecture JSON', query={
103 'fields[lecture]': 'title,description,view_html,asset',
104 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
105 })
106
107 def _handle_error(self, response):
108 if not isinstance(response, dict):
109 return
110 error = response.get('error')
111 if error:
112 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
113 error_data = error.get('data')
114 if error_data:
115 error_str += ' - %s' % error_data.get('formErrors')
116 raise ExtractorError(error_str, expected=True)
117
118 def _download_webpage(self, *args, **kwargs):
119 kwargs.setdefault('headers', {})['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4'
120 return super(UdemyIE, self)._download_webpage(
121 *args, **compat_kwargs(kwargs))
122
123 def _download_json(self, url_or_request, *args, **kwargs):
124 headers = {
125 'X-Udemy-Snail-Case': 'true',
126 'X-Requested-With': 'XMLHttpRequest',
127 }
128 for cookie in self._downloader.cookiejar:
129 if cookie.name == 'client_id':
130 headers['X-Udemy-Client-Id'] = cookie.value
131 elif cookie.name == 'access_token':
132 headers['X-Udemy-Bearer-Token'] = cookie.value
133 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
134
135 if isinstance(url_or_request, compat_urllib_request.Request):
136 for header, value in headers.items():
137 url_or_request.add_header(header, value)
138 else:
139 url_or_request = sanitized_Request(url_or_request, headers=headers)
140
141 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
142 self._handle_error(response)
143 return response
144
145 def _real_initialize(self):
146 self._login()
147
148 def _login(self):
149 (username, password) = self._get_login_info()
150 if username is None:
151 return
152
153 login_popup = self._download_webpage(
154 self._LOGIN_URL, None, 'Downloading login popup')
155
156 def is_logged(webpage):
157 return any(re.search(p, webpage) for p in (
158 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
159 r'>Logout<'))
160
161 # already logged in
162 if is_logged(login_popup):
163 return
164
165 login_form = self._form_hidden_inputs('login-form', login_popup)
166
167 login_form.update({
168 'email': username,
169 'password': password,
170 })
171
172 response = self._download_webpage(
173 self._LOGIN_URL, None, 'Logging in',
174 data=urlencode_postdata(login_form),
175 headers={
176 'Referer': self._ORIGIN_URL,
177 'Origin': self._ORIGIN_URL,
178 })
179
180 if not is_logged(response):
181 error = self._html_search_regex(
182 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
183 response, 'error message', default=None)
184 if error:
185 raise ExtractorError('Unable to login: %s' % error, expected=True)
186 raise ExtractorError('Unable to log in')
187
188 def _real_extract(self, url):
189 lecture_id = self._match_id(url)
190
191 webpage = self._download_webpage(url, lecture_id)
192
193 course_id, _ = self._extract_course_info(webpage, lecture_id)
194
195 try:
196 lecture = self._download_lecture(course_id, lecture_id)
197 except ExtractorError as e:
198 # Error could possibly mean we are not enrolled in the course
199 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
200 self._enroll_course(url, webpage, course_id)
201 lecture = self._download_lecture(course_id, lecture_id)
202 else:
203 raise
204
205 title = lecture['title']
206 description = lecture.get('description')
207
208 asset = lecture['asset']
209
210 asset_type = asset.get('asset_type') or asset.get('assetType')
211 if asset_type != 'Video':
212 raise ExtractorError(
213 'Lecture %s is not a video' % lecture_id, expected=True)
214
215 stream_url = asset.get('stream_url') or asset.get('streamUrl')
216 if stream_url:
217 youtube_url = self._search_regex(
218 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
219 if youtube_url:
220 return self.url_result(youtube_url, 'Youtube')
221
222 video_id = compat_str(asset['id'])
223 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
224 duration = float_or_none(asset.get('data', {}).get('duration'))
225
226 subtitles = {}
227 automatic_captions = {}
228
229 formats = []
230
231 def extract_output_format(src, f_id):
232 return {
233 'url': src.get('url'),
234 'format_id': '%sp' % (src.get('height') or f_id),
235 'width': int_or_none(src.get('width')),
236 'height': int_or_none(src.get('height')),
237 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
238 'vcodec': src.get('video_codec'),
239 'fps': int_or_none(src.get('frame_rate')),
240 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
241 'acodec': src.get('audio_codec'),
242 'asr': int_or_none(src.get('audio_sample_rate')),
243 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
244 'filesize': int_or_none(src.get('file_size_in_bytes')),
245 }
246
247 outputs = asset.get('data', {}).get('outputs')
248 if not isinstance(outputs, dict):
249 outputs = {}
250
251 def add_output_format_meta(f, key):
252 output = outputs.get(key)
253 if isinstance(output, dict):
254 output_format = extract_output_format(output, key)
255 output_format.update(f)
256 return output_format
257 return f
258
259 def extract_formats(source_list):
260 if not isinstance(source_list, list):
261 return
262 for source in source_list:
263 video_url = source.get('file') or source.get('src')
264 if not video_url or not isinstance(video_url, compat_str):
265 continue
266 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
267 formats.extend(self._extract_m3u8_formats(
268 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
269 m3u8_id='hls', fatal=False))
270 continue
271 format_id = source.get('label')
272 f = {
273 'url': video_url,
274 'format_id': '%sp' % format_id,
275 'height': int_or_none(format_id),
276 }
277 if format_id:
278 # Some videos contain additional metadata (e.g.
279 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
280 f = add_output_format_meta(f, format_id)
281 formats.append(f)
282
283 def extract_subtitles(track_list):
284 if not isinstance(track_list, list):
285 return
286 for track in track_list:
287 if not isinstance(track, dict):
288 continue
289 if track.get('kind') != 'captions':
290 continue
291 src = track.get('src')
292 if not src or not isinstance(src, compat_str):
293 continue
294 lang = track.get('language') or track.get(
295 'srclang') or track.get('label')
296 sub_dict = automatic_captions if track.get(
297 'autogenerated') is True else subtitles
298 sub_dict.setdefault(lang, []).append({
299 'url': src,
300 })
301
302 download_urls = asset.get('download_urls')
303 if isinstance(download_urls, dict):
304 extract_formats(download_urls.get('Video'))
305
306 view_html = lecture.get('view_html')
307 if view_html:
308 view_html_urls = set()
309 for source in re.findall(r'<source[^>]+>', view_html):
310 attributes = extract_attributes(source)
311 src = attributes.get('src')
312 if not src:
313 continue
314 res = attributes.get('data-res')
315 height = int_or_none(res)
316 if src in view_html_urls:
317 continue
318 view_html_urls.add(src)
319 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
320 m3u8_formats = self._extract_m3u8_formats(
321 src, video_id, 'mp4', entry_protocol='m3u8_native',
322 m3u8_id='hls', fatal=False)
323 for f in m3u8_formats:
324 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
325 if m:
326 if not f.get('height'):
327 f['height'] = int(m.group('height'))
328 if not f.get('tbr'):
329 f['tbr'] = int(m.group('tbr'))
330 formats.extend(m3u8_formats)
331 else:
332 formats.append(add_output_format_meta({
333 'url': src,
334 'format_id': '%dp' % height if height else None,
335 'height': height,
336 }, res))
337
338 # react rendition since 2017.04.15 (see
339 # https://github.com/rg3/youtube-dl/issues/12744)
340 data = self._parse_json(
341 self._search_regex(
342 r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
343 'setup data', default='{}', group='data'), video_id,
344 transform_source=unescapeHTML, fatal=False)
345 if data and isinstance(data, dict):
346 extract_formats(data.get('sources'))
347 if not duration:
348 duration = int_or_none(data.get('duration'))
349 extract_subtitles(data.get('tracks'))
350
351 if not subtitles and not automatic_captions:
352 text_tracks = self._parse_json(
353 self._search_regex(
354 r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
355 'text tracks', default='{}', group='data'), video_id,
356 transform_source=lambda s: js_to_json(unescapeHTML(s)),
357 fatal=False)
358 extract_subtitles(text_tracks)
359
360 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
361
362 return {
363 'id': video_id,
364 'title': title,
365 'description': description,
366 'thumbnail': thumbnail,
367 'duration': duration,
368 'formats': formats,
369 'subtitles': subtitles,
370 'automatic_captions': automatic_captions,
371 }
372
373
374 class UdemyCourseIE(UdemyIE):
375 IE_NAME = 'udemy:course'
376 _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
377 _TESTS = []
378
379 @classmethod
380 def suitable(cls, url):
381 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
382
383 def _real_extract(self, url):
384 course_path = self._match_id(url)
385
386 webpage = self._download_webpage(url, course_path)
387
388 course_id, title = self._extract_course_info(webpage, course_path)
389
390 self._enroll_course(url, webpage, course_id)
391
392 response = self._download_json(
393 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
394 course_id, 'Downloading course curriculum', query={
395 'fields[chapter]': 'title,object_index',
396 'fields[lecture]': 'title,asset',
397 'page_size': '1000',
398 })
399
400 entries = []
401 chapter, chapter_number = [None] * 2
402 for entry in response['results']:
403 clazz = entry.get('_class')
404 if clazz == 'lecture':
405 asset = entry.get('asset')
406 if isinstance(asset, dict):
407 asset_type = asset.get('asset_type') or asset.get('assetType')
408 if asset_type != 'Video':
409 continue
410 lecture_id = entry.get('id')
411 if lecture_id:
412 entry = {
413 '_type': 'url_transparent',
414 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
415 'title': entry.get('title'),
416 'ie_key': UdemyIE.ie_key(),
417 }
418 if chapter_number:
419 entry['chapter_number'] = chapter_number
420 if chapter:
421 entry['chapter'] = chapter
422 entries.append(entry)
423 elif clazz == 'chapter':
424 chapter_number = entry.get('object_index')
425 chapter = entry.get('title')
426
427 return self.playlist_result(entries, course_id, title)