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.

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