udemy.py 7.2 KB

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