udemy.py 17 KB

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