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