udemy.py 13 KB

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