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.

163 lines
5.6 KiB

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