]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/udemy.py
[extractor/__init__] Add youtube:live and sort youtube extractors alphabetically
[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(
f20756fb 44 'Course %s is not free. You have to pay for it before you can download. '
17b2d7ca
S
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(
70cab344 147 (r'data-course-id=["\'](\d+)', r'&quot;id&quot;\s*:\s*(\d+)'),
a7ba57dc 148 webpage, 'course id')
e5de3f6c 149
328f82d5
S
150 try:
151 lecture = self._download_lecture(course_id, lecture_id)
152 except ExtractorError as e:
153 # Error could possibly mean we are not enrolled in the course
154 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
155 self._enroll_course(webpage, course_id)
3092fc40 156 lecture = self._download_lecture(course_id, lecture_id)
328f82d5
S
157 else:
158 raise
159
160 title = lecture['title']
161 description = lecture.get('description')
162
163 asset = lecture['asset']
164
165 asset_type = asset.get('assetType') or asset.get('asset_type')
e2937118
S
166 if asset_type != 'Video':
167 raise ExtractorError(
168 'Lecture %s is not a video' % lecture_id, expected=True)
e5de3f6c 169
e2937118 170 stream_url = asset.get('streamUrl') or asset.get('stream_url')
328f82d5
S
171 if stream_url:
172 youtube_url = self._search_regex(
173 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
174 if youtube_url:
175 return self.url_result(youtube_url, 'Youtube')
e5de3f6c
S
176
177 video_id = asset['id']
e2937118 178 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
328f82d5
S
179 duration = float_or_none(asset.get('data', {}).get('duration'))
180 outputs = asset.get('data', {}).get('outputs', {})
181
182 formats = []
183 for format_ in asset.get('download_urls', {}).get('Video', []):
184 video_url = format_.get('file')
185 if not video_url:
186 continue
187 format_id = format_.get('label')
188 f = {
189 'url': format_['file'],
190 'height': int_or_none(format_id),
191 }
192 if format_id:
193 # Some videos contain additional metadata (e.g.
194 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
195 output = outputs.get(format_id)
196 if isinstance(output, dict):
197 f.update({
198 'format_id': '%sp' % (output.get('label') or format_id),
199 'width': int_or_none(output.get('width')),
200 'height': int_or_none(output.get('height')),
201 'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
202 'vcodec': output.get('video_codec'),
203 'fps': int_or_none(output.get('frame_rate')),
204 'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
205 'acodec': output.get('audio_codec'),
206 'asr': int_or_none(output.get('audio_sample_rate')),
207 'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
208 'filesize': int_or_none(output.get('file_size_in_bytes')),
3b35c342 209 })
328f82d5
S
210 else:
211 f['format_id'] = '%sp' % format_id
212 formats.append(f)
3b35c342
S
213
214 self._sort_formats(formats)
e5de3f6c 215
e5de3f6c
S
216 return {
217 'id': video_id,
218 'title': title,
219 'description': description,
220 'thumbnail': thumbnail,
221 'duration': duration,
222 'formats': formats
223 }
224
225
226class UdemyCourseIE(UdemyIE):
227 IE_NAME = 'udemy:course'
328f82d5 228 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
6563837e 229 _TESTS = []
e5de3f6c
S
230
231 @classmethod
232 def suitable(cls, url):
233 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
234
235 def _real_extract(self, url):
328f82d5
S
236 course_path = self._match_id(url)
237
238 webpage = self._download_webpage(url, course_path)
e5de3f6c 239
61c0663c 240 response = self._download_json(
e2937118
S
241 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
242 course_path, 'Downloading course JSON')
e5de3f6c 243
328f82d5
S
244 course_id = response['id']
245 course_title = response.get('title')
e5de3f6c 246
328f82d5 247 self._enroll_course(webpage, course_id)
e5de3f6c 248
61c0663c 249 response = self._download_json(
e2937118
S
250 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
251 course_id, 'Downloading course curriculum')
e5de3f6c 252
4d402db5 253 entries = []
5bafcf65 254 chapter, chapter_number = None, None
4d402db5
S
255 for asset in response:
256 asset_type = asset.get('assetType') or asset.get('asset_type')
257 if asset_type == 'Video':
258 asset_id = asset.get('id')
259 if asset_id:
260 entry = {
261 '_type': 'url_transparent',
262 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
263 'ie_key': UdemyIE.ie_key(),
264 }
5bafcf65
S
265 if chapter_number:
266 entry['chapter_number'] = chapter_number
4d402db5
S
267 if chapter:
268 entry['chapter'] = chapter
269 entries.append(entry)
270 elif asset.get('type') == 'chapter':
5bafcf65 271 chapter_number = asset.get('index') or asset.get('object_index')
4d402db5 272 chapter = asset.get('title')
e5de3f6c 273
5f6a1245 274 return self.playlist_result(entries, course_id, course_title)