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