You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

196 lines
6.8 KiB

10 years ago
  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_or_request, video_id, note='Downloading JSON metadata'):
  37. headers = {
  38. 'X-Udemy-Snail-Case': 'true',
  39. 'X-Requested-With': 'XMLHttpRequest',
  40. }
  41. for cookie in self._downloader.cookiejar:
  42. if cookie.name == 'client_id':
  43. headers['X-Udemy-Client-Id'] = cookie.value
  44. elif cookie.name == 'access_token':
  45. headers['X-Udemy-Bearer-Token'] = cookie.value
  46. if isinstance(url_or_request, compat_urllib_request.Request):
  47. for header, value in headers.items():
  48. url_or_request.add_header(header, value)
  49. else:
  50. url_or_request = compat_urllib_request.Request(url_or_request, headers=headers)
  51. response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
  52. self._handle_error(response)
  53. return response
  54. def _real_initialize(self):
  55. self._login()
  56. def _login(self):
  57. (username, password) = self._get_login_info()
  58. if username is None:
  59. raise ExtractorError(
  60. 'Udemy account is required, use --username and --password options to provide account credentials.',
  61. expected=True)
  62. login_popup = self._download_webpage(
  63. 'https://www.udemy.com/join/login-popup?displayType=ajax&showSkipButton=1', None,
  64. 'Downloading login popup')
  65. if login_popup == '<div class="run-command close-popup redirect" data-url="https://www.udemy.com/"></div>':
  66. return
  67. csrf = self._html_search_regex(
  68. r'<input type="hidden" name="csrf" value="(.+?)"',
  69. login_popup, 'csrf token')
  70. login_form = {
  71. 'email': username,
  72. 'password': password,
  73. 'csrf': csrf,
  74. 'displayType': 'json',
  75. 'isSubmitted': '1',
  76. }
  77. request = compat_urllib_request.Request(
  78. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  79. response = self._download_json(
  80. request, None, 'Logging in as %s' % username)
  81. if 'returnUrl' not in response:
  82. raise ExtractorError('Unable to log in')
  83. def _real_extract(self, url):
  84. mobj = re.match(self._VALID_URL, url)
  85. lecture_id = mobj.group('id')
  86. lecture = self._download_json(
  87. 'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
  88. lecture_id, 'Downloading lecture JSON')
  89. asset_type = lecture.get('assetType') or lecture.get('asset_type')
  90. if asset_type != 'Video':
  91. raise ExtractorError(
  92. 'Lecture %s is not a video' % lecture_id, expected=True)
  93. asset = lecture['asset']
  94. stream_url = asset.get('streamUrl') or asset.get('stream_url')
  95. mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
  96. if mobj:
  97. return self.url_result(mobj.group(1), 'Youtube')
  98. video_id = asset['id']
  99. thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
  100. duration = asset['data']['duration']
  101. download_url = asset.get('downloadUrl') or asset.get('download_url')
  102. video = download_url.get('Video') or download_url.get('video')
  103. video_480p = download_url.get('Video480p') or download_url.get('video_480p')
  104. formats = [
  105. {
  106. 'url': video_480p[0],
  107. 'format_id': '360p',
  108. },
  109. {
  110. 'url': video[0],
  111. 'format_id': '720p',
  112. },
  113. ]
  114. title = lecture['title']
  115. description = lecture['description']
  116. return {
  117. 'id': video_id,
  118. 'title': title,
  119. 'description': description,
  120. 'thumbnail': thumbnail,
  121. 'duration': duration,
  122. 'formats': formats
  123. }
  124. class UdemyCourseIE(UdemyIE):
  125. IE_NAME = 'udemy:course'
  126. _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
  127. _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
  128. _ALREADY_ENROLLED = '>You are already taking this course.<'
  129. _TESTS = []
  130. @classmethod
  131. def suitable(cls, url):
  132. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  133. def _real_extract(self, url):
  134. mobj = re.match(self._VALID_URL, url)
  135. course_path = mobj.group('coursepath')
  136. response = self._download_json(
  137. 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
  138. course_path, 'Downloading course JSON')
  139. course_id = int(response['id'])
  140. course_title = response['title']
  141. webpage = self._download_webpage(
  142. 'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
  143. course_id, 'Enrolling in the course')
  144. if self._SUCCESSFULLY_ENROLLED in webpage:
  145. self.to_screen('%s: Successfully enrolled in' % course_id)
  146. elif self._ALREADY_ENROLLED in webpage:
  147. self.to_screen('%s: Already enrolled in' % course_id)
  148. response = self._download_json(
  149. 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
  150. course_id, 'Downloading course curriculum')
  151. entries = [
  152. self.url_result(
  153. 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
  154. for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
  155. ]
  156. return self.playlist_result(entries, course_id, course_title)