udemy.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. from __future__ import unicode_literals
  2. from .common import InfoExtractor
  3. from ..compat import (
  4. compat_HTTPError,
  5. compat_urllib_parse,
  6. compat_urllib_request,
  7. compat_urlparse,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. float_or_none,
  12. int_or_none,
  13. sanitized_Request,
  14. )
  15. class UdemyIE(InfoExtractor):
  16. IE_NAME = 'udemy'
  17. _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
  18. _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
  19. _ORIGIN_URL = 'https://www.udemy.com'
  20. _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
  21. _ALREADY_ENROLLED = '>You are already taking this course.<'
  22. _NETRC_MACHINE = 'udemy'
  23. _TESTS = [{
  24. 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
  25. 'md5': '98eda5b657e752cf945d8445e261b5c5',
  26. 'info_dict': {
  27. 'id': '160614',
  28. 'ext': 'mp4',
  29. 'title': 'Introduction and Installation',
  30. 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
  31. 'duration': 579.29,
  32. },
  33. 'skip': 'Requires udemy account credentials',
  34. }]
  35. def _enroll_course(self, webpage, course_id):
  36. enroll_url = self._search_regex(
  37. r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/course/subscribe/.+?)\1',
  38. webpage, 'enroll url', group='url',
  39. default='https://www.udemy.com/course/subscribe/?courseId=%s' % course_id)
  40. webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
  41. if self._SUCCESSFULLY_ENROLLED in webpage:
  42. self.to_screen('%s: Successfully enrolled in' % course_id)
  43. elif self._ALREADY_ENROLLED in webpage:
  44. self.to_screen('%s: Already enrolled in' % course_id)
  45. def _download_lecture(self, course_id, lecture_id):
  46. return self._download_json(
  47. 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
  48. course_id, lecture_id, compat_urllib_parse.urlencode({
  49. 'video_only': '',
  50. 'auto_play': '',
  51. 'fields[lecture]': 'title,description,asset',
  52. 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
  53. 'instructorPreviewMode': 'False',
  54. })),
  55. lecture_id, 'Downloading lecture JSON', fatal=False)
  56. def _handle_error(self, response):
  57. if not isinstance(response, dict):
  58. return
  59. error = response.get('error')
  60. if error:
  61. error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
  62. error_data = error.get('data')
  63. if error_data:
  64. error_str += ' - %s' % error_data.get('formErrors')
  65. raise ExtractorError(error_str, expected=True)
  66. def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata', *args, **kwargs):
  67. headers = {
  68. 'X-Udemy-Snail-Case': 'true',
  69. 'X-Requested-With': 'XMLHttpRequest',
  70. }
  71. for cookie in self._downloader.cookiejar:
  72. if cookie.name == 'client_id':
  73. headers['X-Udemy-Client-Id'] = cookie.value
  74. elif cookie.name == 'access_token':
  75. headers['X-Udemy-Bearer-Token'] = cookie.value
  76. headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
  77. if isinstance(url_or_request, compat_urllib_request.Request):
  78. for header, value in headers.items():
  79. url_or_request.add_header(header, value)
  80. else:
  81. url_or_request = sanitized_Request(url_or_request, headers=headers)
  82. response = super(UdemyIE, self)._download_json(url_or_request, video_id, note, *args, **kwargs)
  83. self._handle_error(response)
  84. return response
  85. def _real_initialize(self):
  86. self._login()
  87. def _login(self):
  88. (username, password) = self._get_login_info()
  89. if username is None:
  90. return
  91. login_popup = self._download_webpage(
  92. self._LOGIN_URL, None, 'Downloading login popup')
  93. def is_logged(webpage):
  94. return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
  95. # already logged in
  96. if is_logged(login_popup):
  97. return
  98. login_form = self._form_hidden_inputs('login-form', login_popup)
  99. login_form.update({
  100. 'email': username.encode('utf-8'),
  101. 'password': password.encode('utf-8'),
  102. })
  103. request = sanitized_Request(
  104. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  105. request.add_header('Referer', self._ORIGIN_URL)
  106. request.add_header('Origin', self._ORIGIN_URL)
  107. response = self._download_webpage(
  108. request, None, 'Logging in as %s' % username)
  109. if not is_logged(response):
  110. error = self._html_search_regex(
  111. r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
  112. response, 'error message', default=None)
  113. if error:
  114. raise ExtractorError('Unable to login: %s' % error, expected=True)
  115. raise ExtractorError('Unable to log in')
  116. def _real_extract(self, url):
  117. lecture_id = self._match_id(url)
  118. webpage = self._download_webpage(url, lecture_id)
  119. course_id = self._search_regex(
  120. r'data-course-id=["\'](\d+)', webpage, 'course id')
  121. try:
  122. lecture = self._download_lecture(course_id, lecture_id)
  123. except ExtractorError as e:
  124. # Error could possibly mean we are not enrolled in the course
  125. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  126. self._enroll_course(webpage, course_id)
  127. lecture_id = self._download_lecture(course_id, lecture_id)
  128. else:
  129. raise
  130. title = lecture['title']
  131. description = lecture.get('description')
  132. asset = lecture['asset']
  133. asset_type = asset.get('assetType') or asset.get('asset_type')
  134. if asset_type != 'Video':
  135. raise ExtractorError(
  136. 'Lecture %s is not a video' % lecture_id, expected=True)
  137. stream_url = asset.get('streamUrl') or asset.get('stream_url')
  138. if stream_url:
  139. youtube_url = self._search_regex(
  140. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  141. if youtube_url:
  142. return self.url_result(youtube_url, 'Youtube')
  143. video_id = asset['id']
  144. thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
  145. duration = float_or_none(asset.get('data', {}).get('duration'))
  146. outputs = asset.get('data', {}).get('outputs', {})
  147. formats = []
  148. for format_ in asset.get('download_urls', {}).get('Video', []):
  149. video_url = format_.get('file')
  150. if not video_url:
  151. continue
  152. format_id = format_.get('label')
  153. f = {
  154. 'url': format_['file'],
  155. 'height': int_or_none(format_id),
  156. }
  157. if format_id:
  158. # Some videos contain additional metadata (e.g.
  159. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  160. output = outputs.get(format_id)
  161. if isinstance(output, dict):
  162. f.update({
  163. 'format_id': '%sp' % (output.get('label') or format_id),
  164. 'width': int_or_none(output.get('width')),
  165. 'height': int_or_none(output.get('height')),
  166. 'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
  167. 'vcodec': output.get('video_codec'),
  168. 'fps': int_or_none(output.get('frame_rate')),
  169. 'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
  170. 'acodec': output.get('audio_codec'),
  171. 'asr': int_or_none(output.get('audio_sample_rate')),
  172. 'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
  173. 'filesize': int_or_none(output.get('file_size_in_bytes')),
  174. })
  175. else:
  176. f['format_id'] = '%sp' % format_id
  177. formats.append(f)
  178. self._sort_formats(formats)
  179. return {
  180. 'id': video_id,
  181. 'title': title,
  182. 'description': description,
  183. 'thumbnail': thumbnail,
  184. 'duration': duration,
  185. 'formats': formats
  186. }
  187. class UdemyCourseIE(UdemyIE):
  188. IE_NAME = 'udemy:course'
  189. _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
  190. _TESTS = []
  191. @classmethod
  192. def suitable(cls, url):
  193. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  194. def _real_extract(self, url):
  195. course_path = self._match_id(url)
  196. webpage = self._download_webpage(url, course_path)
  197. response = self._download_json(
  198. 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
  199. course_path, 'Downloading course JSON')
  200. course_id = response['id']
  201. course_title = response.get('title')
  202. self._enroll_course(webpage, course_id)
  203. response = self._download_json(
  204. 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
  205. course_id, 'Downloading course curriculum')
  206. entries = [
  207. self.url_result(
  208. 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
  209. for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
  210. ]
  211. return self.playlist_result(entries, course_id, course_title)