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.

195 lines
6.8 KiB

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