udemy.py 12 KB

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