]>
jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/udemy.py
ae8de98974e166940fb16521f3c13c611b5cb657
1 from __future__
import unicode_literals
5 from .common
import InfoExtractor
10 compat_urllib_request
,
28 class UdemyIE(InfoExtractor
):
32 (?:[^/]+\.)?udemy\.com/
35 lecture/view/?\?lectureId=|
36 [^/]+/learn/v4/t/lecture/
40 _LOGIN_URL
= 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
41 _ORIGIN_URL
= 'https://www.udemy.com'
42 _NETRC_MACHINE
= 'udemy'
45 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
46 'md5': '98eda5b657e752cf945d8445e261b5c5',
50 'title': 'Introduction and Installation',
51 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
54 'skip': 'Requires udemy account credentials',
57 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
58 'only_matching': True,
60 # no url in outputs format entry
61 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
62 'only_matching': True,
64 # only outputs rendition
65 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
66 'only_matching': True,
68 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
69 'only_matching': True,
72 def _extract_course_info(self
, webpage
, video_id
):
73 course
= self
._parse
_json
(
74 unescapeHTML(self
._search
_regex
(
75 r
'ng-init=["\'].*\bcourse
=({.+?}
)[;"\']',
76 webpage, 'course', default='{}')),
77 video_id, fatal=False) or {}
78 course_id = course.get('id') or self._search_regex(
79 r'data-course-id=["\'](\d
+)', webpage, 'course
id')
80 return course_id, course.get('title
')
82 def _enroll_course(self, base_url, webpage, course_id):
83 def combine_url(base_url, url):
84 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http
') else url
86 checkout_url = unescapeHTML(self._search_regex(
87 r'href
=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
88 webpage, 'checkout url', group='url', default=None))
91 'Course %s is not free. You have to pay for it before you can download. '
92 'Use this URL to confirm purchase: %s'
93 % (course_id, combine_url(base_url, checkout_url)),
96 enroll_url = unescapeHTML(self._search_regex(
97 r'href=(["\'])(?P
<url
>(?
:https?
://(?
:www\
.)?udemy\
.com
)?
/course
/subscribe
/.+?
)\
1',
98 webpage, 'enroll url
', group='url
', default=None))
100 webpage = self._download_webpage(
101 combine_url(base_url, enroll_url),
102 course_id, 'Enrolling
in the course
',
103 headers={'Referer': base_url})
104 if '>You have enrolled
in' in webpage:
105 self.to_screen('%s: Successfully enrolled
in the course
' % course_id)
107 def _download_lecture(self, course_id, lecture_id):
108 return self._download_json(
109 'https
://www
.udemy
.com
/api
-2.0/users
/me
/subscribed
-courses
/%s/lectures
/%s?
'
110 % (course_id, lecture_id),
111 lecture_id, 'Downloading lecture JSON
', query={
112 'fields
[lecture
]': 'title
,description
,view_html
,asset
',
113 'fields
[asset
]': 'asset_type
,stream_url
,thumbnail_url
,download_urls
,stream_urls
,captions
,data
',
116 def _handle_error(self, response):
117 if not isinstance(response, dict):
119 error = response.get('error
')
121 error_str = 'Udemy returned error
#%s: %s' % (error.get('code'), error.get('message'))
122 error_data
= error
.get('data')
124 error_str
+= ' - %s' % error_data
.get('formErrors')
125 raise ExtractorError(error_str
, expected
=True)
127 def _download_webpage_handle(self
, *args
, **kwargs
):
128 headers
= kwargs
.get('headers', {}).copy()
129 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'
130 kwargs
['headers'] = headers
131 ret
= super(UdemyIE
, self
)._download
_webpage
_handle
(
132 *args
, **compat_kwargs(kwargs
))
136 if any(p
in webpage
for p
in (
137 '>Please verify you are a human',
138 'Access to this page has been denied because we believe you are using automation tools to browse the website',
140 raise ExtractorError(
141 'Udemy asks you to solve a CAPTCHA. Login with browser, '
142 'solve CAPTCHA, then export cookies and pass cookie file to '
143 'youtube-dl with --cookies.', expected
=True)
146 def _download_json(self
, url_or_request
, *args
, **kwargs
):
148 'X-Udemy-Snail-Case': 'true',
149 'X-Requested-With': 'XMLHttpRequest',
151 for cookie
in self
._downloader
.cookiejar
:
152 if cookie
.name
== 'client_id':
153 headers
['X-Udemy-Client-Id'] = cookie
.value
154 elif cookie
.name
== 'access_token':
155 headers
['X-Udemy-Bearer-Token'] = cookie
.value
156 headers
['X-Udemy-Authorization'] = 'Bearer %s' % cookie
.value
158 if isinstance(url_or_request
, compat_urllib_request
.Request
):
159 for header
, value
in headers
.items():
160 url_or_request
.add_header(header
, value
)
162 url_or_request
= sanitized_Request(url_or_request
, headers
=headers
)
164 response
= super(UdemyIE
, self
)._download
_json
(url_or_request
, *args
, **kwargs
)
165 self
._handle
_error
(response
)
168 def _real_initialize(self
):
172 username
, password
= self
._get
_login
_info
()
176 login_popup
= self
._download
_webpage
(
177 self
._LOGIN
_URL
, None, 'Downloading login popup')
179 def is_logged(webpage
):
180 return any(re
.search(p
, webpage
) for p
in (
181 r
'href=["\'](?
:https
://www\
.udemy\
.com
)?
/user
/logout
/',
185 if is_logged(login_popup):
188 login_form = self._form_hidden_inputs('login
-form
', login_popup)
192 'password
': password,
195 response = self._download_webpage(
196 self._LOGIN_URL, None, 'Logging
in',
197 data=urlencode_postdata(login_form),
199 'Referer
': self._ORIGIN_URL,
200 'Origin
': self._ORIGIN_URL,
203 if not is_logged(response):
204 error = self._html_search_regex(
205 r'(?s
)<div
[^
>]+class="form-errors[^"]*">(.+?)</div>',
206 response, 'error message', default=None)
208 raise ExtractorError('Unable to login: %s' % error, expected=True)
209 raise ExtractorError('Unable to log in')
211 def _real_extract(self, url):
212 lecture_id = self._match_id(url)
214 webpage = self._download_webpage(url, lecture_id)
216 course_id, _ = self._extract_course_info(webpage, lecture_id)
219 lecture = self._download_lecture(course_id, lecture_id)
220 except ExtractorError as e:
221 # Error could possibly mean we are not enrolled in the course
222 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
223 self._enroll_course(url, webpage, course_id)
224 lecture = self._download_lecture(course_id, lecture_id)
228 title = lecture['title']
229 description = lecture.get('description')
231 asset = lecture['asset']
233 asset_type = asset.get('asset_type') or asset.get('assetType')
234 if asset_type != 'Video':
235 raise ExtractorError(
236 'Lecture %s is not a video' % lecture_id, expected=True)
238 stream_url = asset.get('stream_url') or asset.get('streamUrl')
240 youtube_url = self._search_regex(
241 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
243 return self.url_result(youtube_url, 'Youtube')
245 video_id = compat_str(asset['id'])
246 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
247 duration = float_or_none(asset.get('data', {}).get('duration'))
250 automatic_captions = {}
254 def extract_output_format(src, f_id):
256 'url': src.get('url'),
257 'format_id': '%sp' % (src.get('height') or f_id),
258 'width': int_or_none(src.get('width')),
259 'height': int_or_none(src.get('height')),
260 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
261 'vcodec': src.get('video_codec'),
262 'fps': int_or_none(src.get('frame_rate')),
263 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
264 'acodec': src.get('audio_codec'),
265 'asr': int_or_none(src.get('audio_sample_rate')),
266 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
267 'filesize': int_or_none(src.get('file_size_in_bytes')),
270 outputs = asset.get('data', {}).get('outputs')
271 if not isinstance(outputs, dict):
274 def add_output_format_meta(f, key):
275 output = outputs.get(key)
276 if isinstance(output, dict):
277 output_format = extract_output_format(output, key)
278 output_format.update(f)
282 def extract_formats(source_list):
283 if not isinstance(source_list, list):
285 for source in source_list:
286 video_url = url_or_none(source.get('file') or source.get('src'))
289 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
290 formats.extend(self._extract_m3u8_formats(
291 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
292 m3u8_id='hls', fatal=False))
294 format_id = source.get('label')
297 'format_id': '%sp' % format_id,
298 'height': int_or_none(format_id),
301 # Some videos contain additional metadata (e.g.
302 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
303 f = add_output_format_meta(f, format_id)
306 def extract_subtitles(track_list):
307 if not isinstance(track_list, list):
309 for track in track_list:
310 if not isinstance(track, dict):
312 if track.get('kind') != 'captions':
314 src = url_or_none(track.get('src'))
317 lang = track.get('language') or track.get(
318 'srclang') or track.get('label')
319 sub_dict = automatic_captions if track.get(
320 'autogenerated') is True else subtitles
321 sub_dict.setdefault(lang, []).append({
325 for url_kind in ('download', 'stream'):
326 urls = asset.get('%s_urls' % url_kind)
327 if isinstance(urls, dict):
328 extract_formats(urls.get('Video'))
330 captions = asset.get('captions')
331 if isinstance(captions, list):
333 if not isinstance(cc, dict):
335 cc_url = url_or_none(cc.get('url'))
338 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
339 sub_dict = (automatic_captions if cc.get('source') == 'auto'
341 sub_dict.setdefault(lang or 'en', []).append({
345 view_html = lecture.get('view_html')
347 view_html_urls = set()
348 for source in re.findall(r'<source[^>]+>', view_html):
349 attributes = extract_attributes(source)
350 src = attributes.get('src')
353 res = attributes.get('data-res')
354 height = int_or_none(res)
355 if src in view_html_urls:
357 view_html_urls.add(src)
358 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
359 m3u8_formats = self._extract_m3u8_formats(
360 src, video_id, 'mp4', entry_protocol='m3u8_native',
361 m3u8_id='hls', fatal=False)
362 for f in m3u8_formats:
363 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
365 if not f.get('height'):
366 f['height'] = int(m.group('height'))
368 f['tbr'] = int(m.group('tbr'))
369 formats.extend(m3u8_formats)
371 formats.append(add_output_format_meta({
373 'format_id': '%dp' % height if height else None,
377 # react rendition since 2017.04.15 (see
378 # https://github.com/rg3/youtube-dl/issues/12744)
379 data = self._parse_json(
381 r'videojs-setup-data=(["\'])(?P
<data
>{.+?}
)\
1', view_html,
382 'setup data
', default='{}', group='data
'), video_id,
383 transform_source=unescapeHTML, fatal=False)
384 if data and isinstance(data, dict):
385 extract_formats(data.get('sources
'))
387 duration = int_or_none(data.get('duration
'))
388 extract_subtitles(data.get('tracks
'))
390 if not subtitles and not automatic_captions:
391 text_tracks = self._parse_json(
393 r'text
-tracks
=(["\'])(?P<data>\[.+?\])\1', view_html,
394 'text tracks', default='{}', group='data'), video_id,
395 transform_source=lambda s: js_to_json(unescapeHTML(s)),
397 extract_subtitles(text_tracks)
399 if not formats and outputs:
400 for format_id, output in outputs.items():
401 f = extract_output_format(output, format_id)
405 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
410 'description': description,
411 'thumbnail': thumbnail,
412 'duration': duration,
414 'subtitles': subtitles,
415 'automatic_captions': automatic_captions,
419 class UdemyCourseIE(UdemyIE):
420 IE_NAME = 'udemy:course'
421 _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
423 'url': 'https://www.udemy.com/java-tutorial/',
424 'only_matching': True,
426 'url': 'https://wipro.udemy.com/java-tutorial/',
427 'only_matching': True,
431 def suitable(cls, url):
432 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
434 def _real_extract(self, url):
435 course_path = self._match_id(url)
437 webpage = self._download_webpage(url, course_path)
439 course_id, title = self._extract_course_info(webpage, course_path)
441 self._enroll_course(url, webpage, course_id)
443 response = self._download_json(
444 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
445 course_id, 'Downloading course curriculum', query={
446 'fields[chapter]': 'title,object_index',
447 'fields[lecture]': 'title,asset',
452 chapter, chapter_number = [None] * 2
453 for entry in response['results']:
454 clazz = entry.get('_class')
455 if clazz == 'lecture':
456 asset = entry.get('asset')
457 if isinstance(asset, dict):
458 asset_type = asset.get('asset_type') or asset.get('assetType')
459 if asset_type != 'Video':
461 lecture_id = entry.get('id')
464 '_type': 'url_transparent',
465 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
466 'title': entry.get('title'),
467 'ie_key': UdemyIE.ie_key(),
470 entry['chapter_number'] = chapter_number
472 entry['chapter'] = chapter
473 entries.append(entry)
474 elif clazz == 'chapter':
475 chapter_number = entry.get('object_index')
476 chapter = entry.get('title')
478 return self.playlist_result(entries, course_id, title)