udemy.py 14 KB

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