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.

193 lines
6.7 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. lecture_id = self._match_id(url)
  85. lecture = self._download_json(
  86. 'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
  87. lecture_id, 'Downloading lecture JSON')
  88. asset_type = lecture.get('assetType') or lecture.get('asset_type')
  89. if asset_type != 'Video':
  90. raise ExtractorError(
  91. 'Lecture %s is not a video' % lecture_id, expected=True)
  92. asset = lecture['asset']
  93. stream_url = asset.get('streamUrl') or asset.get('stream_url')
  94. mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
  95. if mobj:
  96. return self.url_result(mobj.group(1), 'Youtube')
  97. video_id = asset['id']
  98. thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
  99. duration = asset['data']['duration']
  100. download_url = asset.get('downloadUrl') or asset.get('download_url')
  101. video = download_url.get('Video') or download_url.get('video')
  102. video_480p = download_url.get('Video480p') or download_url.get('video_480p')
  103. formats = [
  104. {
  105. 'url': video_480p[0],
  106. 'format_id': '360p',
  107. },
  108. {
  109. 'url': video[0],
  110. 'format_id': '720p',
  111. },
  112. ]
  113. title = lecture['title']
  114. description = lecture['description']
  115. return {
  116. 'id': video_id,
  117. 'title': title,
  118. 'description': description,
  119. 'thumbnail': thumbnail,
  120. 'duration': duration,
  121. 'formats': formats
  122. }
  123. class UdemyCourseIE(UdemyIE):
  124. IE_NAME = 'udemy:course'
  125. _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
  126. _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
  127. _ALREADY_ENROLLED = '>You are already taking this course.<'
  128. _TESTS = []
  129. @classmethod
  130. def suitable(cls, url):
  131. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  132. def _real_extract(self, url):
  133. mobj = re.match(self._VALID_URL, url)
  134. course_path = mobj.group('coursepath')
  135. response = self._download_json(
  136. 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
  137. course_path, 'Downloading course JSON')
  138. course_id = int(response['id'])
  139. course_title = response['title']
  140. webpage = self._download_webpage(
  141. 'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
  142. course_id, 'Enrolling in the course')
  143. if self._SUCCESSFULLY_ENROLLED in webpage:
  144. self.to_screen('%s: Successfully enrolled in' % course_id)
  145. elif self._ALREADY_ENROLLED in webpage:
  146. self.to_screen('%s: Already enrolled in' % course_id)
  147. response = self._download_json(
  148. 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
  149. course_id, 'Downloading course curriculum')
  150. entries = [
  151. self.url_result(
  152. 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
  153. for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
  154. ]
  155. return self.playlist_result(entries, course_id, course_title)