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