udemy.py 11 KB

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