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