udemy.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. compat_urllib_parse,
  6. compat_urllib_request,
  7. ExtractorError,
  8. )
  9. class UdemyIE(InfoExtractor):
  10. IE_NAME = 'udemy'
  11. _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
  12. _LOGIN_URL = 'https://www.udemy.com/join/login-submit/'
  13. _NETRC_MACHINE = 'udemy'
  14. _TESTS = [{
  15. 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
  16. 'md5': '98eda5b657e752cf945d8445e261b5c5',
  17. 'info_dict': {
  18. 'id': '160614',
  19. 'ext': 'mp4',
  20. 'title': 'Introduction and Installation',
  21. 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
  22. 'duration': 579.29,
  23. },
  24. 'skip': 'Requires udemy account credentials',
  25. }]
  26. def _handle_error(self, response):
  27. if not isinstance(response, dict):
  28. return
  29. error = response.get('error')
  30. if error:
  31. error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
  32. error_data = error.get('data')
  33. if error_data:
  34. error_str += ' - %s' % error_data.get('formErrors')
  35. raise ExtractorError(error_str, expected=True)
  36. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  37. response = super(UdemyIE, self)._download_json(url, video_id, note)
  38. self._handle_error(response)
  39. return response
  40. def _download_json_cookies(self, url, video_id, note):
  41. headers = {
  42. 'X-Udemy-Snail-Case': 'true',
  43. 'X-Requested-With': 'XMLHttpRequest',
  44. }
  45. for cookie in self._downloader.cookiejar:
  46. if cookie.name == 'client_id':
  47. headers['X-Udemy-Client-Id'] = cookie.value
  48. elif cookie.name == 'access_token':
  49. headers['X-Udemy-Bearer-Token'] = cookie.value
  50. request = compat_urllib_request.Request(url, headers=headers)
  51. return self._download_json(request, video_id, note)
  52. def _real_initialize(self):
  53. self._login()
  54. def _login(self):
  55. (username, password) = self._get_login_info()
  56. if username is None:
  57. raise ExtractorError(
  58. 'Udemy account is required, use --username and --password options to provide account credentials.',
  59. expected=True)
  60. login_popup = self._download_webpage(
  61. 'https://www.udemy.com/join/login-popup?displayType=ajax&showSkipButton=1', None,
  62. 'Downloading login popup')
  63. if login_popup == '<div class="run-command close-popup redirect" data-url="https://www.udemy.com/"></div>':
  64. return
  65. csrf = self._html_search_regex(
  66. r'<input type="hidden" name="csrf" value="(.+?)"',
  67. login_popup, 'csrf token')
  68. login_form = {
  69. 'email': username,
  70. 'password': password,
  71. 'csrf': csrf,
  72. 'displayType': 'json',
  73. 'isSubmitted': '1',
  74. }
  75. request = compat_urllib_request.Request(
  76. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  77. response = self._download_json(
  78. request, None, 'Logging in as %s' % username)
  79. if 'returnUrl' not in response:
  80. raise ExtractorError('Unable to log in')
  81. def _real_extract(self, url):
  82. mobj = re.match(self._VALID_URL, url)
  83. lecture_id = mobj.group('id')
  84. lecture = self._download_json_cookies(
  85. 'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
  86. lecture_id, 'Downloading lecture JSON')
  87. asset_type = lecture.get('assetType') or lecture.get('asset_type')
  88. if asset_type != 'Video':
  89. raise ExtractorError(
  90. 'Lecture %s is not a video' % lecture_id, expected=True)
  91. asset = lecture['asset']
  92. stream_url = asset.get('streamUrl') or asset.get('stream_url')
  93. mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
  94. if mobj:
  95. return self.url_result(mobj.group(1), 'Youtube')
  96. video_id = asset['id']
  97. thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
  98. duration = asset['data']['duration']
  99. download_url = asset.get('downloadUrl') or asset.get('download_url')
  100. video = download_url.get('Video') or download_url.get('video')
  101. video_480p = download_url.get('Video480p') or download_url.get('video_480p')
  102. formats = [
  103. {
  104. 'url': video_480p[0],
  105. 'format_id': '360p',
  106. },
  107. {
  108. 'url': video[0],
  109. 'format_id': '720p',
  110. },
  111. ]
  112. title = lecture['title']
  113. description = lecture['description']
  114. return {
  115. 'id': video_id,
  116. 'title': title,
  117. 'description': description,
  118. 'thumbnail': thumbnail,
  119. 'duration': duration,
  120. 'formats': formats
  121. }
  122. class UdemyCourseIE(UdemyIE):
  123. IE_NAME = 'udemy:course'
  124. _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
  125. _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
  126. _ALREADY_ENROLLED = '>You are already taking this course.<'
  127. _TESTS = []
  128. @classmethod
  129. def suitable(cls, url):
  130. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  131. def _real_extract(self, url):
  132. mobj = re.match(self._VALID_URL, url)
  133. course_path = mobj.group('coursepath')
  134. response = self._download_json_cookies(
  135. 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
  136. course_path, 'Downloading course JSON')
  137. course_id = int(response['id'])
  138. course_title = response['title']
  139. webpage = self._download_webpage(
  140. 'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
  141. course_id, 'Enrolling in the course')
  142. if self._SUCCESSFULLY_ENROLLED in webpage:
  143. self.to_screen('%s: Successfully enrolled in' % course_id)
  144. elif self._ALREADY_ENROLLED in webpage:
  145. self.to_screen('%s: Already enrolled in' % course_id)
  146. response = self._download_json_cookies(
  147. 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
  148. course_id, 'Downloading course curriculum')
  149. entries = [
  150. self.url_result(
  151. 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
  152. for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
  153. ]
  154. return self.playlist_result(entries, course_id, course_title)