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