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