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