udemy.py 19 KB

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