]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/udemy.py
1 from __future__
import unicode_literals
5 from .common
import InfoExtractor
27 class UdemyIE(InfoExtractor
):
31 (?:[^/]+\.)?udemy\.com/
34 lecture/view/?\?lectureId=|
35 [^/]+/learn/v4/t/lecture/
39 _LOGIN_URL
= 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
40 _ORIGIN_URL
= 'https://www.udemy.com'
41 _NETRC_MACHINE
= 'udemy'
44 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
45 'md5': '98eda5b657e752cf945d8445e261b5c5',
49 'title': 'Introduction and Installation',
50 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
53 'skip': 'Requires udemy account credentials',
56 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
57 'only_matching': True,
59 # no url in outputs format entry
60 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
61 'only_matching': True,
63 # only outputs rendition
64 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
65 'only_matching': True,
67 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
68 'only_matching': True,
71 def _extract_course_info(self
, webpage
, video_id
):
72 course
= self
._parse
_json
(
73 unescapeHTML(self
._search
_regex
(
74 r
'ng-init=["\'].*\bcourse
=({.+?}
)[;"\']',
75 webpage, 'course', default='{}')),
76 video_id, fatal=False) or {}
77 course_id = course.get('id') or self._search_regex(
79 r'data-course-id=["\'](\d
+)',
80 r'"
;courseId
"
;\s
*:\s
*(\d
+)'
81 ], webpage, 'course
id')
82 return course_id, course.get('title
')
84 def _enroll_course(self, base_url, webpage, course_id):
85 def combine_url(base_url, url):
86 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http
') else url
88 checkout_url = unescapeHTML(self._search_regex(
89 r'href
=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
90 webpage, 'checkout url', group='url', default=None))
93 'Course %s is not free. You have to pay for it before you can download. '
94 'Use this URL to confirm purchase: %s'
95 % (course_id, combine_url(base_url, checkout_url)),
98 enroll_url = unescapeHTML(self._search_regex(
99 r'href=(["\'])(?P
<url
>(?
:https?
://(?
:www\
.)?udemy\
.com
)?
/course
/subscribe
/.+?
)\
1',
100 webpage, 'enroll url
', group='url
', default=None))
102 webpage = self._download_webpage(
103 combine_url(base_url, enroll_url),
104 course_id, 'Enrolling
in the course
',
105 headers={'Referer': base_url})
106 if '>You have enrolled
in' in webpage:
107 self.to_screen('%s: Successfully enrolled
in the course
' % course_id)
109 def _download_lecture(self, course_id, lecture_id):
110 return self._download_json(
111 'https
://www
.udemy
.com
/api
-2.0/users
/me
/subscribed
-courses
/%s/lectures
/%s?
'
112 % (course_id, lecture_id),
113 lecture_id, 'Downloading lecture JSON
', query={
114 'fields
[lecture
]': 'title
,description
,view_html
,asset
',
115 'fields
[asset
]': 'asset_type
,stream_url
,thumbnail_url
,download_urls
,stream_urls
,captions
,data
',
118 def _handle_error(self, response):
119 if not isinstance(response, dict):
121 error = response.get('error
')
123 error_str = 'Udemy returned error
#%s: %s' % (error.get('code'), error.get('message'))
124 error_data
= error
.get('data')
126 error_str
+= ' - %s' % error_data
.get('formErrors')
127 raise ExtractorError(error_str
, expected
=True)
129 def _download_webpage_handle(self
, *args
, **kwargs
):
130 headers
= kwargs
.get('headers', {}).copy()
131 headers
['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
132 kwargs
['headers'] = headers
133 ret
= super(UdemyIE
, self
)._download
_webpage
_handle
(
138 if any(p
in webpage
for p
in (
139 '>Please verify you are a human',
140 'Access to this page has been denied because we believe you are using automation tools to browse the website',
142 raise ExtractorError(
143 'Udemy asks you to solve a CAPTCHA. Login with browser, '
144 'solve CAPTCHA, then export cookies and pass cookie file to '
145 'yt-dlp with --cookies.', expected
=True)
148 def _download_json(self
, url_or_request
, *args
, **kwargs
):
150 'X-Udemy-Snail-Case': 'true',
151 'X-Requested-With': 'XMLHttpRequest',
153 for cookie
in self
._downloader
.cookiejar
:
154 if cookie
.name
== 'client_id':
155 headers
['X-Udemy-Client-Id'] = cookie
.value
156 elif cookie
.name
== 'access_token':
157 headers
['X-Udemy-Bearer-Token'] = cookie
.value
158 headers
['X-Udemy-Authorization'] = 'Bearer %s' % cookie
.value
160 if isinstance(url_or_request
, compat_urllib_request
.Request
):
161 for header
, value
in headers
.items():
162 url_or_request
.add_header(header
, value
)
164 url_or_request
= sanitized_Request(url_or_request
, headers
=headers
)
166 response
= super(UdemyIE
, self
)._download
_json
(url_or_request
, *args
, **kwargs
)
167 self
._handle
_error
(response
)
170 def _perform_login(self
, username
, password
):
171 login_popup
= self
._download
_webpage
(
172 self
._LOGIN
_URL
, None, 'Downloading login popup')
174 def is_logged(webpage
):
175 return any(re
.search(p
, webpage
) for p
in (
176 r
'href=["\'](?
:https
://www\
.udemy\
.com
)?
/user
/logout
/',
180 if is_logged(login_popup):
183 login_form = self._form_hidden_inputs('login
-form
', login_popup)
187 'password
': password,
190 response = self._download_webpage(
191 self._LOGIN_URL, None, 'Logging
in',
192 data=urlencode_postdata(login_form),
194 'Referer
': self._ORIGIN_URL,
195 'Origin
': self._ORIGIN_URL,
198 if not is_logged(response):
199 error = self._html_search_regex(
200 r'(?s
)<div
[^
>]+class="form-errors[^"]*">(.+?)</div>',
201 response, 'error message', default=None)
203 raise ExtractorError('Unable to login: %s' % error, expected=True)
204 raise ExtractorError('Unable to log in')
206 def _real_extract(self, url):
207 lecture_id = self._match_id(url)
209 webpage = self._download_webpage(url, lecture_id)
211 course_id, _ = self._extract_course_info(webpage, lecture_id)
214 lecture = self._download_lecture(course_id, lecture_id)
215 except ExtractorError as e:
216 # Error could possibly mean we are not enrolled in the course
217 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
218 self._enroll_course(url, webpage, course_id)
219 lecture = self._download_lecture(course_id, lecture_id)
223 title = lecture['title']
224 description = lecture.get('description')
226 asset = lecture['asset']
228 asset_type = asset.get('asset_type') or asset.get('assetType')
229 if asset_type != 'Video':
230 raise ExtractorError(
231 'Lecture %s is not a video' % lecture_id, expected=True)
233 stream_url = asset.get('stream_url') or asset.get('streamUrl')
235 youtube_url = self._search_regex(
236 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
238 return self.url_result(youtube_url, 'Youtube')
240 video_id = compat_str(asset['id'])
241 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
242 duration = float_or_none(asset.get('data', {}).get('duration'))
245 automatic_captions = {}
249 def extract_output_format(src, f_id):
251 'url': src.get('url'),
252 'format_id': '%sp' % (src.get('height') or f_id),
253 'width': int_or_none(src.get('width')),
254 'height': int_or_none(src.get('height')),
255 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
256 'vcodec': src.get('video_codec'),
257 'fps': int_or_none(src.get('frame_rate')),
258 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
259 'acodec': src.get('audio_codec'),
260 'asr': int_or_none(src.get('audio_sample_rate')),
261 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
262 'filesize': int_or_none(src.get('file_size_in_bytes')),
265 outputs = asset.get('data', {}).get('outputs')
266 if not isinstance(outputs, dict):
269 def add_output_format_meta(f, key):
270 output = outputs.get(key)
271 if isinstance(output, dict):
272 output_format = extract_output_format(output, key)
273 output_format.update(f)
277 def extract_formats(source_list):
278 if not isinstance(source_list, list):
280 for source in source_list:
281 video_url = url_or_none(source.get('file') or source.get('src'))
284 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
285 formats.extend(self._extract_m3u8_formats(
286 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
287 m3u8_id='hls', fatal=False))
289 format_id = source.get('label')
292 'format_id': '%sp' % format_id,
293 'height': int_or_none(format_id),
296 # Some videos contain additional metadata (e.g.
297 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
298 f = add_output_format_meta(f, format_id)
301 def extract_subtitles(track_list):
302 if not isinstance(track_list, list):
304 for track in track_list:
305 if not isinstance(track, dict):
307 if track.get('kind') != 'captions':
309 src = url_or_none(track.get('src'))
312 lang = track.get('language') or track.get(
313 'srclang') or track.get('label')
314 sub_dict = automatic_captions if track.get(
315 'autogenerated') is True else subtitles
316 sub_dict.setdefault(lang, []).append({
320 for url_kind in ('download', 'stream'):
321 urls = asset.get('%s_urls' % url_kind)
322 if isinstance(urls, dict):
323 extract_formats(urls.get('Video'))
325 captions = asset.get('captions')
326 if isinstance(captions, list):
328 if not isinstance(cc, dict):
330 cc_url = url_or_none(cc.get('url'))
333 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
334 sub_dict = (automatic_captions if cc.get('source') == 'auto'
336 sub_dict.setdefault(lang or 'en', []).append({
340 view_html = lecture.get('view_html')
342 view_html_urls = set()
343 for source in re.findall(r'<source[^>]+>', view_html):
344 attributes = extract_attributes(source)
345 src = attributes.get('src')
348 res = attributes.get('data-res')
349 height = int_or_none(res)
350 if src in view_html_urls:
352 view_html_urls.add(src)
353 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
354 m3u8_formats = self._extract_m3u8_formats(
355 src, video_id, 'mp4', entry_protocol='m3u8_native',
356 m3u8_id='hls', fatal=False)
357 for f in m3u8_formats:
358 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
360 if not f.get('height'):
361 f['height'] = int(m.group('height'))
363 f['tbr'] = int(m.group('tbr'))
364 formats.extend(m3u8_formats)
366 formats.append(add_output_format_meta({
368 'format_id': '%dp' % height if height else None,
372 # react rendition since 2017.04.15 (see
373 # https://github.com/ytdl-org/youtube-dl/issues/12744)
374 data = self._parse_json(
376 r'videojs-setup-data=(["\'])(?P
<data
>{.+?}
)\
1', view_html,
377 'setup data
', default='{}', group='data
'), video_id,
378 transform_source=unescapeHTML, fatal=False)
379 if data and isinstance(data, dict):
380 extract_formats(data.get('sources
'))
382 duration = int_or_none(data.get('duration
'))
383 extract_subtitles(data.get('tracks
'))
385 if not subtitles and not automatic_captions:
386 text_tracks = self._parse_json(
388 r'text
-tracks
=(["\'])(?P<data>\[.+?\])\1', view_html,
389 'text tracks', default='{}', group='data'), video_id,
390 transform_source=lambda s: js_to_json(unescapeHTML(s)),
392 extract_subtitles(text_tracks)
394 if not formats and outputs:
395 for format_id, output in outputs.items():
396 f = extract_output_format(output, format_id)
400 self._sort_formats(formats)
405 'description': description,
406 'thumbnail': thumbnail,
407 'duration': duration,
409 'subtitles': subtitles,
410 'automatic_captions': automatic_captions,
414 class UdemyCourseIE(UdemyIE):
415 IE_NAME = 'udemy:course'
416 _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
418 'url': 'https://www.udemy.com/java-tutorial/',
419 'only_matching': True,
421 'url': 'https://wipro.udemy.com/java-tutorial/',
422 'only_matching': True,
426 def suitable(cls, url):
427 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
429 def _real_extract(self, url):
430 course_path = self._match_id(url)
432 webpage = self._download_webpage(url, course_path)
434 course_id, title = self._extract_course_info(webpage, course_path)
436 self._enroll_course(url, webpage, course_id)
438 response = self._download_json(
439 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
440 course_id, 'Downloading course curriculum', query={
441 'fields[chapter]': 'title,object_index',
442 'fields[lecture]': 'title,asset',
447 chapter, chapter_number = [None] * 2
448 for entry in response['results']:
449 clazz = entry.get('_class')
450 if clazz == 'lecture':
451 asset = entry.get('asset')
452 if isinstance(asset, dict):
453 asset_type = asset.get('asset_type') or asset.get('assetType')
454 if asset_type != 'Video':
456 lecture_id = entry.get('id')
459 '_type': 'url_transparent',
460 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
461 'title': entry.get('title'),
462 'ie_key': UdemyIE.ie_key(),
465 entry['chapter_number'] = chapter_number
467 entry['chapter'] = chapter
468 entries.append(entry)
469 elif clazz == 'chapter':
470 chapter_number = entry.get('object_index')
471 chapter = entry.get('title')
473 return self.playlist_result(entries, course_id, title)