udemy.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import re
  2. import urllib.parse
  3. from .common import InfoExtractor
  4. from ..networking import Request
  5. from ..networking.exceptions import HTTPError
  6. from ..utils import (
  7. ExtractorError,
  8. determine_ext,
  9. extract_attributes,
  10. float_or_none,
  11. int_or_none,
  12. js_to_json,
  13. smuggle_url,
  14. try_get,
  15. unescapeHTML,
  16. unsmuggle_url,
  17. url_or_none,
  18. urlencode_postdata,
  19. )
  20. class UdemyIE(InfoExtractor):
  21. IE_NAME = 'udemy'
  22. _VALID_URL = r'''(?x)
  23. https?://
  24. (?:[^/]+\.)?udemy\.com/
  25. (?:
  26. [^#]+\#/lecture/|
  27. lecture/view/?\?lectureId=|
  28. [^/]+/learn/v4/t/lecture/
  29. )
  30. (?P<id>\d+)
  31. '''
  32. _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
  33. _ORIGIN_URL = 'https://www.udemy.com'
  34. _NETRC_MACHINE = 'udemy'
  35. _TESTS = [{
  36. 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
  37. 'md5': '98eda5b657e752cf945d8445e261b5c5',
  38. 'info_dict': {
  39. 'id': '160614',
  40. 'ext': 'mp4',
  41. 'title': 'Introduction and Installation',
  42. 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
  43. 'duration': 579.29,
  44. },
  45. 'skip': 'Requires udemy account credentials',
  46. }, {
  47. # new URL schema
  48. 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
  49. 'only_matching': True,
  50. }, {
  51. # no url in outputs format entry
  52. 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
  53. 'only_matching': True,
  54. }, {
  55. # only outputs rendition
  56. 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
  57. 'only_matching': True,
  58. }, {
  59. 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
  60. 'only_matching': True,
  61. }]
  62. def _extract_course_info(self, webpage, video_id):
  63. course = self._parse_json(
  64. unescapeHTML(self._search_regex(
  65. r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
  66. webpage, 'course', default='{}')),
  67. video_id, fatal=False) or {}
  68. course_id = course.get('id') or self._search_regex(
  69. [
  70. r'data-course-id=["\'](\d+)',
  71. r'&quot;courseId&quot;\s*:\s*(\d+)',
  72. ], webpage, 'course id')
  73. return course_id, course.get('title')
  74. def _enroll_course(self, base_url, webpage, course_id):
  75. def combine_url(base_url, url):
  76. return urllib.parse.urljoin(base_url, url) if not url.startswith('http') else url
  77. checkout_url = unescapeHTML(self._search_regex(
  78. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
  79. webpage, 'checkout url', group='url', default=None))
  80. if checkout_url:
  81. raise ExtractorError(
  82. f'Course {course_id} is not free. You have to pay for it before you can download. '
  83. f'Use this URL to confirm purchase: {combine_url(base_url, checkout_url)}',
  84. expected=True)
  85. enroll_url = unescapeHTML(self._search_regex(
  86. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
  87. webpage, 'enroll url', group='url', default=None))
  88. if enroll_url:
  89. webpage = self._download_webpage(
  90. combine_url(base_url, enroll_url),
  91. course_id, 'Enrolling in the course',
  92. headers={'Referer': base_url})
  93. if '>You have enrolled in' in webpage:
  94. self.to_screen(f'{course_id}: Successfully enrolled in the course')
  95. def _download_lecture(self, course_id, lecture_id):
  96. return self._download_json(
  97. f'https://www.udemy.com/api-2.0/users/me/subscribed-courses/{course_id}/lectures/{lecture_id}?',
  98. lecture_id, 'Downloading lecture JSON', query={
  99. 'fields[lecture]': 'title,description,view_html,asset',
  100. 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data,course_is_drmed',
  101. })
  102. def _handle_error(self, response):
  103. if not isinstance(response, dict):
  104. return
  105. error = response.get('error')
  106. if error:
  107. error_str = 'Udemy returned error #{}: {}'.format(error.get('code'), error.get('message'))
  108. error_data = error.get('data')
  109. if error_data:
  110. error_str += ' - {}'.format(error_data.get('formErrors'))
  111. raise ExtractorError(error_str, expected=True)
  112. def _download_webpage_handle(self, *args, **kwargs):
  113. headers = kwargs.get('headers', {}).copy()
  114. 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'
  115. kwargs['headers'] = headers
  116. ret = super()._download_webpage_handle(
  117. *args, **kwargs)
  118. if not ret:
  119. return ret
  120. webpage, _ = ret
  121. if any(p in webpage for p in (
  122. '>Please verify you are a human',
  123. 'Access to this page has been denied because we believe you are using automation tools to browse the website',
  124. '"_pxCaptcha"')):
  125. raise ExtractorError(
  126. 'Udemy asks you to solve a CAPTCHA. Login with browser, '
  127. 'solve CAPTCHA, then export cookies and pass cookie file to '
  128. 'yt-dlp with --cookies.', expected=True)
  129. return ret
  130. def _download_json(self, url_or_request, *args, **kwargs):
  131. headers = {
  132. 'X-Udemy-Snail-Case': 'true',
  133. 'X-Requested-With': 'XMLHttpRequest',
  134. }
  135. for cookie in self.cookiejar:
  136. if cookie.name == 'client_id':
  137. headers['X-Udemy-Client-Id'] = cookie.value
  138. elif cookie.name == 'access_token':
  139. headers['X-Udemy-Bearer-Token'] = cookie.value
  140. headers['X-Udemy-Authorization'] = f'Bearer {cookie.value}'
  141. if isinstance(url_or_request, Request):
  142. url_or_request.headers.update(headers)
  143. else:
  144. url_or_request = Request(url_or_request, headers=headers)
  145. response = super()._download_json(url_or_request, *args, **kwargs)
  146. self._handle_error(response)
  147. return response
  148. def _perform_login(self, username, password):
  149. login_popup = self._download_webpage(
  150. self._LOGIN_URL, None, 'Downloading login popup')
  151. def is_logged(webpage):
  152. return any(re.search(p, webpage) for p in (
  153. r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
  154. r'>Logout<'))
  155. # already logged in
  156. if is_logged(login_popup):
  157. return
  158. login_form = self._form_hidden_inputs('login-form', login_popup)
  159. login_form.update({
  160. 'email': username,
  161. 'password': password,
  162. })
  163. response = self._download_webpage(
  164. self._LOGIN_URL, None, 'Logging in',
  165. data=urlencode_postdata(login_form),
  166. headers={
  167. 'Referer': self._ORIGIN_URL,
  168. 'Origin': self._ORIGIN_URL,
  169. })
  170. if not is_logged(response):
  171. error = self._html_search_regex(
  172. r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
  173. response, 'error message', default=None)
  174. if error:
  175. raise ExtractorError(f'Unable to login: {error}', expected=True)
  176. raise ExtractorError('Unable to log in')
  177. def _real_extract(self, url):
  178. lecture_id = self._match_id(url)
  179. course_id = unsmuggle_url(url, {})[1].get('course_id')
  180. webpage = None
  181. if not course_id:
  182. webpage = self._download_webpage(url, lecture_id)
  183. course_id, _ = self._extract_course_info(webpage, lecture_id)
  184. try:
  185. lecture = self._download_lecture(course_id, lecture_id)
  186. except ExtractorError as e:
  187. # Error could possibly mean we are not enrolled in the course
  188. if isinstance(e.cause, HTTPError) and e.cause.status == 403:
  189. webpage = webpage or self._download_webpage(url, lecture_id)
  190. self._enroll_course(url, webpage, course_id)
  191. lecture = self._download_lecture(course_id, lecture_id)
  192. else:
  193. raise
  194. title = lecture['title']
  195. description = lecture.get('description')
  196. asset = lecture['asset']
  197. asset_type = asset.get('asset_type') or asset.get('assetType')
  198. if asset_type != 'Video':
  199. raise ExtractorError(
  200. f'Lecture {lecture_id} is not a video', expected=True)
  201. stream_url = asset.get('stream_url') or asset.get('streamUrl')
  202. if stream_url:
  203. youtube_url = self._search_regex(
  204. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  205. if youtube_url:
  206. return self.url_result(youtube_url, 'Youtube')
  207. video_id = str(asset['id'])
  208. thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
  209. duration = float_or_none(asset.get('data', {}).get('duration'))
  210. subtitles = {}
  211. automatic_captions = {}
  212. formats = []
  213. def extract_output_format(src, f_id):
  214. return {
  215. 'url': src.get('url'),
  216. 'format_id': '%sp' % (src.get('height') or f_id),
  217. 'width': int_or_none(src.get('width')),
  218. 'height': int_or_none(src.get('height')),
  219. 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
  220. 'vcodec': src.get('video_codec'),
  221. 'fps': int_or_none(src.get('frame_rate')),
  222. 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
  223. 'acodec': src.get('audio_codec'),
  224. 'asr': int_or_none(src.get('audio_sample_rate')),
  225. 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
  226. 'filesize': int_or_none(src.get('file_size_in_bytes')),
  227. }
  228. outputs = asset.get('data', {}).get('outputs')
  229. if not isinstance(outputs, dict):
  230. outputs = {}
  231. def add_output_format_meta(f, key):
  232. output = outputs.get(key)
  233. if isinstance(output, dict):
  234. output_format = extract_output_format(output, key)
  235. output_format.update(f)
  236. return output_format
  237. return f
  238. def extract_formats(source_list):
  239. if not isinstance(source_list, list):
  240. return
  241. for source in source_list:
  242. video_url = url_or_none(source.get('file') or source.get('src'))
  243. if not video_url:
  244. continue
  245. if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
  246. formats.extend(self._extract_m3u8_formats(
  247. video_url, video_id, 'mp4', entry_protocol='m3u8_native',
  248. m3u8_id='hls', fatal=False))
  249. continue
  250. format_id = source.get('label')
  251. f = {
  252. 'url': video_url,
  253. 'format_id': f'{format_id}p',
  254. 'height': int_or_none(format_id),
  255. }
  256. if format_id:
  257. # Some videos contain additional metadata (e.g.
  258. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  259. f = add_output_format_meta(f, format_id)
  260. formats.append(f)
  261. def extract_subtitles(track_list):
  262. if not isinstance(track_list, list):
  263. return
  264. for track in track_list:
  265. if not isinstance(track, dict):
  266. continue
  267. if track.get('kind') != 'captions':
  268. continue
  269. src = url_or_none(track.get('src'))
  270. if not src:
  271. continue
  272. lang = track.get('language') or track.get(
  273. 'srclang') or track.get('label')
  274. sub_dict = automatic_captions if track.get(
  275. 'autogenerated') is True else subtitles
  276. sub_dict.setdefault(lang, []).append({
  277. 'url': src,
  278. })
  279. for url_kind in ('download', 'stream'):
  280. urls = asset.get(f'{url_kind}_urls')
  281. if isinstance(urls, dict):
  282. extract_formats(urls.get('Video'))
  283. captions = asset.get('captions')
  284. if isinstance(captions, list):
  285. for cc in captions:
  286. if not isinstance(cc, dict):
  287. continue
  288. cc_url = url_or_none(cc.get('url'))
  289. if not cc_url:
  290. continue
  291. lang = try_get(cc, lambda x: x['locale']['locale'], str)
  292. sub_dict = (automatic_captions if cc.get('source') == 'auto'
  293. else subtitles)
  294. sub_dict.setdefault(lang or 'en', []).append({
  295. 'url': cc_url,
  296. })
  297. view_html = lecture.get('view_html')
  298. if view_html:
  299. view_html_urls = set()
  300. for source in re.findall(r'<source[^>]+>', view_html):
  301. attributes = extract_attributes(source)
  302. src = attributes.get('src')
  303. if not src:
  304. continue
  305. res = attributes.get('data-res')
  306. height = int_or_none(res)
  307. if src in view_html_urls:
  308. continue
  309. view_html_urls.add(src)
  310. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  311. m3u8_formats = self._extract_m3u8_formats(
  312. src, video_id, 'mp4', entry_protocol='m3u8_native',
  313. m3u8_id='hls', fatal=False)
  314. for f in m3u8_formats:
  315. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  316. if m:
  317. if not f.get('height'):
  318. f['height'] = int(m.group('height'))
  319. if not f.get('tbr'):
  320. f['tbr'] = int(m.group('tbr'))
  321. formats.extend(m3u8_formats)
  322. else:
  323. formats.append(add_output_format_meta({
  324. 'url': src,
  325. 'format_id': f'{height}p' if height else None,
  326. 'height': height,
  327. }, res))
  328. # react rendition since 2017.04.15 (see
  329. # https://github.com/ytdl-org/youtube-dl/issues/12744)
  330. data = self._parse_json(
  331. self._search_regex(
  332. r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
  333. 'setup data', default='{}', group='data'), video_id,
  334. transform_source=unescapeHTML, fatal=False)
  335. if data and isinstance(data, dict):
  336. extract_formats(data.get('sources'))
  337. if not duration:
  338. duration = int_or_none(data.get('duration'))
  339. extract_subtitles(data.get('tracks'))
  340. if not subtitles and not automatic_captions:
  341. text_tracks = self._parse_json(
  342. self._search_regex(
  343. r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
  344. 'text tracks', default='{}', group='data'), video_id,
  345. transform_source=lambda s: js_to_json(unescapeHTML(s)),
  346. fatal=False)
  347. extract_subtitles(text_tracks)
  348. if not formats and outputs:
  349. for format_id, output in outputs.items():
  350. f = extract_output_format(output, format_id)
  351. if f.get('url'):
  352. formats.append(f)
  353. if not formats and asset.get('course_is_drmed'):
  354. self.report_drm(video_id)
  355. return {
  356. 'id': video_id,
  357. 'title': title,
  358. 'description': description,
  359. 'thumbnail': thumbnail,
  360. 'duration': duration,
  361. 'formats': formats,
  362. 'subtitles': subtitles,
  363. 'automatic_captions': automatic_captions,
  364. }
  365. class UdemyCourseIE(UdemyIE): # XXX: Do not subclass from concrete IE
  366. IE_NAME = 'udemy:course'
  367. _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
  368. _TESTS = [{
  369. 'url': 'https://www.udemy.com/java-tutorial/',
  370. 'only_matching': True,
  371. }, {
  372. 'url': 'https://wipro.udemy.com/java-tutorial/',
  373. 'only_matching': True,
  374. }]
  375. @classmethod
  376. def suitable(cls, url):
  377. return False if UdemyIE.suitable(url) else super().suitable(url)
  378. def _real_extract(self, url):
  379. course_path = self._match_id(url)
  380. webpage = self._download_webpage(url, course_path)
  381. course_id, title = self._extract_course_info(webpage, course_path)
  382. self._enroll_course(url, webpage, course_id)
  383. response = self._download_json(
  384. f'https://www.udemy.com/api-2.0/courses/{course_id}/cached-subscriber-curriculum-items',
  385. course_id, 'Downloading course curriculum', query={
  386. 'fields[chapter]': 'title,object_index',
  387. 'fields[lecture]': 'title,asset',
  388. 'page_size': '1000',
  389. })
  390. entries = []
  391. chapter, chapter_number = [None] * 2
  392. for entry in response['results']:
  393. clazz = entry.get('_class')
  394. if clazz == 'lecture':
  395. asset = entry.get('asset')
  396. if isinstance(asset, dict):
  397. asset_type = asset.get('asset_type') or asset.get('assetType')
  398. if asset_type != 'Video':
  399. continue
  400. lecture_id = entry.get('id')
  401. if lecture_id:
  402. entry = {
  403. '_type': 'url_transparent',
  404. 'url': smuggle_url(
  405. f'https://www.udemy.com/{course_path}/learn/v4/t/lecture/{entry["id"]}',
  406. {'course_id': course_id}),
  407. 'title': entry.get('title'),
  408. 'ie_key': UdemyIE.ie_key(),
  409. }
  410. if chapter_number:
  411. entry['chapter_number'] = chapter_number
  412. if chapter:
  413. entry['chapter'] = chapter
  414. entries.append(entry)
  415. elif clazz == 'chapter':
  416. chapter_number = entry.get('object_index')
  417. chapter = entry.get('title')
  418. return self.playlist_result(entries, course_id, title)