]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/udemy.py
a7196997ec111cc4e98331d70cfb5df46682fa49
1 from __future__
import unicode_literals
5 from . common
import InfoExtractor
10 compat_urllib_request
,
27 class UdemyIE ( InfoExtractor
):
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 ,
68 def _extract_course_info ( self
, webpage
, video_id
):
69 course
= self
._ parse
_ json
(
70 unescapeHTML ( self
._ search
_ regex
(
71 r
'ng-init=["\' ].* \b course
=({.+ ?
})[; " \' ]',
72 webpage, 'course', default='{}')),
73 video_id, fatal=False) or {}
74 course_id = course.get('id') or self._search_regex(
75 r'data-course-id=[" \' ]( \d
+) ', webpage, ' course
id ')
76 return course_id, course.get(' title
')
78 def _enroll_course(self, base_url, webpage, course_id):
79 def combine_url(base_url, url):
80 return compat_urlparse.urljoin(base_url, url) if not url.startswith(' http
') else url
82 checkout_url = unescapeHTML(self._search_regex(
83 r' href
=([ " \' ])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
84 webpage, 'checkout url', group='url', default=None))
87 'Course %s is not free. You have to pay for it before you can download. '
88 'Use this URL to confirm purchase: %s '
89 % (course_id, combine_url(base_url, checkout_url)),
92 enroll_url = unescapeHTML(self._search_regex(
93 r'href=([" \' ])( ?P
< url
>( ?
: https?
://( ?
: www\
.) ?udemy\
. com
) ?
/ course
/ subscribe
/.+ ?
) \
1 ',
94 webpage, ' enroll url
', group=' url
', default=None))
96 webpage = self._download_webpage(
97 combine_url(base_url, enroll_url),
98 course_id, ' Enrolling
in the course
',
99 headers={' Referer
': base_url})
100 if ' > You have enrolled
in ' in webpage:
101 self.to_screen(' %s: Successfully enrolled
in the course
' % course_id)
103 def _download_lecture(self, course_id, lecture_id):
104 return self._download_json(
105 ' https
:// www
. udemy
. com
/ api
- 2.0 / users
/ me
/ subscribed
- courses
/ %s/ lectures
/ %s ?
'
106 % (course_id, lecture_id),
107 lecture_id, ' Downloading lecture JSON
', query={
108 ' fields
[ lecture
] ': ' title
, description
, view_html
, asset
',
109 ' fields
[ asset
] ': ' asset_type
, stream_url
, thumbnail_url
, download_urls
, stream_urls
, captions
, data
',
112 def _handle_error(self, response):
113 if not isinstance(response, dict):
115 error = response.get(' error
')
117 error_str = ' Udemy returned error
#%s: %s' % (error.get('code'), error.get('message'))
118 error_data
= error
. get ( 'data' )
120 error_str
+= ' - %s ' % error_data
. get ( 'formErrors' )
121 raise ExtractorError ( error_str
, expected
= True )
123 def _download_webpage_handle ( self
, * args
, ** kwargs
):
124 kwargs
. setdefault ( 'headers' , {})[ 'User-Agent' ] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4'
125 return super ( UdemyIE
, self
) ._ download
_ webpage
_ handle
(
126 * args
, ** compat_kwargs ( kwargs
))
128 def _download_json ( self
, url_or_request
, * args
, ** kwargs
):
130 'X-Udemy-Snail-Case' : 'true' ,
131 'X-Requested-With' : 'XMLHttpRequest' ,
133 for cookie
in self
._ downloader
. cookiejar
:
134 if cookie
. name
== 'client_id' :
135 headers
[ 'X-Udemy-Client-Id' ] = cookie
. value
136 elif cookie
. name
== 'access_token' :
137 headers
[ 'X-Udemy-Bearer-Token' ] = cookie
. value
138 headers
[ 'X-Udemy-Authorization' ] = 'Bearer %s ' % cookie
. value
140 if isinstance ( url_or_request
, compat_urllib_request
. Request
):
141 for header
, value
in headers
. items ():
142 url_or_request
. add_header ( header
, value
)
144 url_or_request
= sanitized_Request ( url_or_request
, headers
= headers
)
146 response
= super ( UdemyIE
, self
) ._ download
_ json
( url_or_request
, * args
, ** kwargs
)
147 self
._ handle
_ error
( response
)
150 def _real_initialize ( self
):
154 username
, password
= self
._ get
_l ogin
_ info
()
158 login_popup
= self
._ download
_ webpage
(
159 self
._L OGIN
_U RL
, None , 'Downloading login popup' )
161 def is_logged ( webpage
):
162 return any ( re
. search ( p
, webpage
) for p
in (
163 r
'href=["\' ]( ?
: https
:// www\
. udemy\
. com
) ?
/ user
/ logout
/ ',
167 if is_logged(login_popup):
170 login_form = self._form_hidden_inputs(' login
- form
', login_popup)
174 ' password
': password,
177 response = self._download_webpage(
178 self._LOGIN_URL, None, ' Logging
in ',
179 data=urlencode_postdata(login_form),
181 ' Referer
': self._ORIGIN_URL,
182 ' Origin
': self._ORIGIN_URL,
185 if not is_logged(response):
186 error = self._html_search_regex(
187 r' ( ?s
)< div
[ ^
>]+ class = "form-errors[^" ]* ">(.+?)</div>',
188 response, 'error message', default=None)
190 raise ExtractorError('Unable to login: %s ' % error, expected=True)
191 raise ExtractorError('Unable to log in')
193 def _real_extract(self, url):
194 lecture_id = self._match_id(url)
196 webpage = self._download_webpage(url, lecture_id)
198 course_id, _ = self._extract_course_info(webpage, lecture_id)
201 lecture = self._download_lecture(course_id, lecture_id)
202 except ExtractorError as e:
203 # Error could possibly mean we are not enrolled in the course
204 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
205 self._enroll_course(url, webpage, course_id)
206 lecture = self._download_lecture(course_id, lecture_id)
210 title = lecture['title']
211 description = lecture.get('description')
213 asset = lecture['asset']
215 asset_type = asset.get('asset_type') or asset.get('assetType')
216 if asset_type != 'Video':
217 raise ExtractorError(
218 'Lecture %s is not a video' % lecture_id, expected=True)
220 stream_url = asset.get('stream_url') or asset.get('streamUrl')
222 youtube_url = self._search_regex(
223 r'(https?://www\.youtube\.com/watch \? v=.*)', stream_url, 'youtube URL', default=None)
225 return self.url_result(youtube_url, 'Youtube')
227 video_id = compat_str(asset['id'])
228 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
229 duration = float_or_none(asset.get('data', {}).get('duration'))
232 automatic_captions = {}
236 def extract_output_format(src, f_id):
238 'url': src.get('url'),
239 'format_id': ' %s p' % (src.get('height') or f_id),
240 'width': int_or_none(src.get('width')),
241 'height': int_or_none(src.get('height')),
242 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
243 'vcodec': src.get('video_codec'),
244 'fps': int_or_none(src.get('frame_rate')),
245 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
246 'acodec': src.get('audio_codec'),
247 'asr': int_or_none(src.get('audio_sample_rate')),
248 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
249 'filesize': int_or_none(src.get('file_size_in_bytes')),
252 outputs = asset.get('data', {}).get('outputs')
253 if not isinstance(outputs, dict):
256 def add_output_format_meta(f, key):
257 output = outputs.get(key)
258 if isinstance(output, dict):
259 output_format = extract_output_format(output, key)
260 output_format.update(f)
264 def extract_formats(source_list):
265 if not isinstance(source_list, list):
267 for source in source_list:
268 video_url = source.get('file') or source.get('src')
269 if not video_url or not isinstance(video_url, compat_str):
271 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
272 formats.extend(self._extract_m3u8_formats(
273 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
274 m3u8_id='hls', fatal=False))
276 format_id = source.get('label')
279 'format_id': ' %s p' % format_id,
280 'height': int_or_none(format_id),
283 # Some videos contain additional metadata (e.g.
284 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
285 f = add_output_format_meta(f, format_id)
288 def extract_subtitles(track_list):
289 if not isinstance(track_list, list):
291 for track in track_list:
292 if not isinstance(track, dict):
294 if track.get('kind') != 'captions':
296 src = track.get('src')
297 if not src or not isinstance(src, compat_str):
299 lang = track.get('language') or track.get(
300 'srclang') or track.get('label')
301 sub_dict = automatic_captions if track.get(
302 'autogenerated') is True else subtitles
303 sub_dict.setdefault(lang, []).append({
307 for url_kind in ('download', 'stream'):
308 urls = asset.get(' %s _urls' % url_kind)
309 if isinstance(urls, dict):
310 extract_formats(urls.get('Video'))
312 captions = asset.get('captions')
313 if isinstance(captions, list):
315 if not isinstance(cc, dict):
317 cc_url = cc.get('url')
318 if not cc_url or not isinstance(cc_url, compat_str):
320 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
321 sub_dict = (automatic_captions if cc.get('source') == 'auto'
323 sub_dict.setdefault(lang or 'en', []).append({
327 view_html = lecture.get('view_html')
329 view_html_urls = set()
330 for source in re.findall(r'<source[^>]+>', view_html):
331 attributes = extract_attributes(source)
332 src = attributes.get('src')
335 res = attributes.get('data-res')
336 height = int_or_none(res)
337 if src in view_html_urls:
339 view_html_urls.add(src)
340 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
341 m3u8_formats = self._extract_m3u8_formats(
342 src, video_id, 'mp4', entry_protocol='m3u8_native',
343 m3u8_id='hls', fatal=False)
344 for f in m3u8_formats:
345 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
347 if not f.get('height'):
348 f['height'] = int(m.group('height'))
350 f['tbr'] = int(m.group('tbr'))
351 formats.extend(m3u8_formats)
353 formats.append(add_output_format_meta({
355 'format_id': ' %d p' % height if height else None,
359 # react rendition since 2017.04.15 (see
360 # https://github.com/rg3/youtube-dl/issues/12744)
361 data = self._parse_json(
363 r'videojs-setup-data=([" \' ])( ?P
< data
>{.+ ?
}) \
1 ', view_html,
364 ' setup data
', default=' {} ', group=' data
'), video_id,
365 transform_source=unescapeHTML, fatal=False)
366 if data and isinstance(data, dict):
367 extract_formats(data.get(' sources
'))
369 duration = int_or_none(data.get(' duration
'))
370 extract_subtitles(data.get(' tracks
'))
372 if not subtitles and not automatic_captions:
373 text_tracks = self._parse_json(
375 r' text
- tracks
=([ " \' ])(?P<data>\[.+?\])\1', view_html,
376 'text tracks', default='{}', group='data'), video_id,
377 transform_source=lambda s: js_to_json(unescapeHTML(s)),
379 extract_subtitles(text_tracks)
381 if not formats and outputs:
382 for format_id, output in outputs.items():
383 f = extract_output_format(output, format_id)
387 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
392 'description': description,
393 'thumbnail': thumbnail,
394 'duration': duration,
396 'subtitles': subtitles,
397 'automatic_captions': automatic_captions,
401 class UdemyCourseIE(UdemyIE):
402 IE_NAME = 'udemy:course'
403 _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
407 def suitable(cls, url):
408 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
410 def _real_extract(self, url):
411 course_path = self._match_id(url)
413 webpage = self._download_webpage(url, course_path)
415 course_id, title = self._extract_course_info(webpage, course_path)
417 self._enroll_course(url, webpage, course_id)
419 response = self._download_json(
420 'https://www.udemy.com/api-2.0/courses/ %s /cached-subscriber-curriculum-items' % course_id,
421 course_id, 'Downloading course curriculum', query={
422 'fields[chapter]': 'title,object_index',
423 'fields[lecture]': 'title,asset',
428 chapter, chapter_number = [None] * 2
429 for entry in response['results']:
430 clazz = entry.get('_class')
431 if clazz == 'lecture':
432 asset = entry.get('asset')
433 if isinstance(asset, dict):
434 asset_type = asset.get('asset_type') or asset.get('assetType')
435 if asset_type != 'Video':
437 lecture_id = entry.get('id')
440 '_type': 'url_transparent',
441 'url': 'https://www.udemy.com/ %s /learn/v4/t/lecture/ %s ' % (course_path, entry['id']),
442 'title': entry.get('title'),
443 'ie_key': UdemyIE.ie_key(),
446 entry['chapter_number'] = chapter_number
448 entry['chapter'] = chapter
449 entries.append(entry)
450 elif clazz == 'chapter':
451 chapter_number = entry.get('object_index')
452 chapter = entry.get('title')
454 return self.playlist_result(entries, course_id, title)