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.

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