logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

udemy.py (19413B)


  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_HTTPError,
  6. compat_kwargs,
  7. compat_str,
  8. compat_urllib_request,
  9. compat_urlparse,
  10. )
  11. from ..utils import (
  12. determine_ext,
  13. extract_attributes,
  14. ExtractorError,
  15. float_or_none,
  16. int_or_none,
  17. js_to_json,
  18. sanitized_Request,
  19. try_get,
  20. unescapeHTML,
  21. url_or_none,
  22. urlencode_postdata,
  23. )
  24. class UdemyIE(InfoExtractor):
  25. IE_NAME = 'udemy'
  26. _VALID_URL = r'''(?x)
  27. https?://
  28. (?:[^/]+\.)?udemy\.com/
  29. (?:
  30. [^#]+\#/lecture/|
  31. lecture/view/?\?lectureId=|
  32. [^/]+/learn/v4/t/lecture/
  33. )
  34. (?P<id>\d+)
  35. '''
  36. _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
  37. _ORIGIN_URL = 'https://www.udemy.com'
  38. _NETRC_MACHINE = 'udemy'
  39. _TESTS = [{
  40. 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
  41. 'md5': '98eda5b657e752cf945d8445e261b5c5',
  42. 'info_dict': {
  43. 'id': '160614',
  44. 'ext': 'mp4',
  45. 'title': 'Introduction and Installation',
  46. 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
  47. 'duration': 579.29,
  48. },
  49. 'skip': 'Requires udemy account credentials',
  50. }, {
  51. # new URL schema
  52. 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
  53. 'only_matching': True,
  54. }, {
  55. # no url in outputs format entry
  56. 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
  57. 'only_matching': True,
  58. }, {
  59. # only outputs rendition
  60. 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
  61. 'only_matching': True,
  62. }, {
  63. 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
  64. 'only_matching': True,
  65. }]
  66. def _extract_course_info(self, webpage, video_id):
  67. course = self._parse_json(
  68. unescapeHTML(self._search_regex(
  69. r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
  70. webpage, 'course', default='{}')),
  71. video_id, fatal=False) or {}
  72. course_id = course.get('id') or self._search_regex(
  73. [
  74. r'data-course-id=["\'](\d+)',
  75. r'&quot;courseId&quot;\s*:\s*(\d+)'
  76. ], webpage, 'course id')
  77. return course_id, course.get('title')
  78. def _enroll_course(self, base_url, webpage, course_id):
  79. def combine_url(base_url, url):
  80. return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
  81. checkout_url = unescapeHTML(self._search_regex(
  82. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
  83. webpage, 'checkout url', group='url', default=None))
  84. if checkout_url:
  85. raise ExtractorError(
  86. 'Course %s is not free. You have to pay for it before you can download. '
  87. 'Use this URL to confirm purchase: %s'
  88. % (course_id, combine_url(base_url, checkout_url)),
  89. expected=True)
  90. enroll_url = unescapeHTML(self._search_regex(
  91. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
  92. webpage, 'enroll url', group='url', default=None))
  93. if enroll_url:
  94. webpage = self._download_webpage(
  95. combine_url(base_url, enroll_url),
  96. course_id, 'Enrolling in the course',
  97. headers={'Referer': base_url})
  98. if '>You have enrolled in' in webpage:
  99. self.to_screen('%s: Successfully enrolled in the course' % course_id)
  100. def _download_lecture(self, course_id, lecture_id):
  101. return self._download_json(
  102. 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
  103. % (course_id, lecture_id),
  104. lecture_id, 'Downloading lecture JSON', query={
  105. 'fields[lecture]': 'title,description,view_html,asset',
  106. 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data',
  107. })
  108. def _handle_error(self, response):
  109. if not isinstance(response, dict):
  110. return
  111. error = response.get('error')
  112. if error:
  113. error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
  114. error_data = error.get('data')
  115. if error_data:
  116. error_str += ' - %s' % error_data.get('formErrors')
  117. raise ExtractorError(error_str, expected=True)
  118. def _download_webpage_handle(self, *args, **kwargs):
  119. headers = kwargs.get('headers', {}).copy()
  120. headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
  121. kwargs['headers'] = headers
  122. ret = super(UdemyIE, self)._download_webpage_handle(
  123. *args, **compat_kwargs(kwargs))
  124. if not ret:
  125. return ret
  126. webpage, _ = ret
  127. if any(p in webpage for p in (
  128. '>Please verify you are a human',
  129. 'Access to this page has been denied because we believe you are using automation tools to browse the website',
  130. '"_pxCaptcha"')):
  131. raise ExtractorError(
  132. 'Udemy asks you to solve a CAPTCHA. Login with browser, '
  133. 'solve CAPTCHA, then export cookies and pass cookie file to '
  134. 'youtube-dl with --cookies.', expected=True)
  135. return ret
  136. def _download_json(self, url_or_request, *args, **kwargs):
  137. headers = {
  138. 'X-Udemy-Snail-Case': 'true',
  139. 'X-Requested-With': 'XMLHttpRequest',
  140. }
  141. for cookie in self._downloader.cookiejar:
  142. if cookie.name == 'client_id':
  143. headers['X-Udemy-Client-Id'] = cookie.value
  144. elif cookie.name == 'access_token':
  145. headers['X-Udemy-Bearer-Token'] = cookie.value
  146. headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
  147. if isinstance(url_or_request, compat_urllib_request.Request):
  148. for header, value in headers.items():
  149. url_or_request.add_header(header, value)
  150. else:
  151. url_or_request = sanitized_Request(url_or_request, headers=headers)
  152. response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
  153. self._handle_error(response)
  154. return response
  155. def _real_initialize(self):
  156. self._login()
  157. def _login(self):
  158. username, password = self._get_login_info()
  159. if username is None:
  160. return
  161. login_popup = self._download_webpage(
  162. self._LOGIN_URL, None, 'Downloading login popup')
  163. def is_logged(webpage):
  164. return any(re.search(p, webpage) for p in (
  165. r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
  166. r'>Logout<'))
  167. # already logged in
  168. if is_logged(login_popup):
  169. return
  170. login_form = self._form_hidden_inputs('login-form', login_popup)
  171. login_form.update({
  172. 'email': username,
  173. 'password': password,
  174. })
  175. response = self._download_webpage(
  176. self._LOGIN_URL, None, 'Logging in',
  177. data=urlencode_postdata(login_form),
  178. headers={
  179. 'Referer': self._ORIGIN_URL,
  180. 'Origin': self._ORIGIN_URL,
  181. })
  182. if not is_logged(response):
  183. error = self._html_search_regex(
  184. r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
  185. response, 'error message', default=None)
  186. if error:
  187. raise ExtractorError('Unable to login: %s' % error, expected=True)
  188. raise ExtractorError('Unable to log in')
  189. def _real_extract(self, url):
  190. lecture_id = self._match_id(url)
  191. webpage = self._download_webpage(url, lecture_id)
  192. course_id, _ = self._extract_course_info(webpage, lecture_id)
  193. try:
  194. lecture = self._download_lecture(course_id, lecture_id)
  195. except ExtractorError as e:
  196. # Error could possibly mean we are not enrolled in the course
  197. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  198. self._enroll_course(url, webpage, course_id)
  199. lecture = self._download_lecture(course_id, lecture_id)
  200. else:
  201. raise
  202. title = lecture['title']
  203. description = lecture.get('description')
  204. asset = lecture['asset']
  205. asset_type = asset.get('asset_type') or asset.get('assetType')
  206. if asset_type != 'Video':
  207. raise ExtractorError(
  208. 'Lecture %s is not a video' % lecture_id, expected=True)
  209. stream_url = asset.get('stream_url') or asset.get('streamUrl')
  210. if stream_url:
  211. youtube_url = self._search_regex(
  212. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  213. if youtube_url:
  214. return self.url_result(youtube_url, 'Youtube')
  215. video_id = compat_str(asset['id'])
  216. thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
  217. duration = float_or_none(asset.get('data', {}).get('duration'))
  218. subtitles = {}
  219. automatic_captions = {}
  220. formats = []
  221. def extract_output_format(src, f_id):
  222. return {
  223. 'url': src.get('url'),
  224. 'format_id': '%sp' % (src.get('height') or f_id),
  225. 'width': int_or_none(src.get('width')),
  226. 'height': int_or_none(src.get('height')),
  227. 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
  228. 'vcodec': src.get('video_codec'),
  229. 'fps': int_or_none(src.get('frame_rate')),
  230. 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
  231. 'acodec': src.get('audio_codec'),
  232. 'asr': int_or_none(src.get('audio_sample_rate')),
  233. 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
  234. 'filesize': int_or_none(src.get('file_size_in_bytes')),
  235. }
  236. outputs = asset.get('data', {}).get('outputs')
  237. if not isinstance(outputs, dict):
  238. outputs = {}
  239. def add_output_format_meta(f, key):
  240. output = outputs.get(key)
  241. if isinstance(output, dict):
  242. output_format = extract_output_format(output, key)
  243. output_format.update(f)
  244. return output_format
  245. return f
  246. def extract_formats(source_list):
  247. if not isinstance(source_list, list):
  248. return
  249. for source in source_list:
  250. video_url = url_or_none(source.get('file') or source.get('src'))
  251. if not video_url:
  252. continue
  253. if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
  254. formats.extend(self._extract_m3u8_formats(
  255. video_url, video_id, 'mp4', entry_protocol='m3u8_native',
  256. m3u8_id='hls', fatal=False))
  257. continue
  258. format_id = source.get('label')
  259. f = {
  260. 'url': video_url,
  261. 'format_id': '%sp' % format_id,
  262. 'height': int_or_none(format_id),
  263. }
  264. if format_id:
  265. # Some videos contain additional metadata (e.g.
  266. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  267. f = add_output_format_meta(f, format_id)
  268. formats.append(f)
  269. def extract_subtitles(track_list):
  270. if not isinstance(track_list, list):
  271. return
  272. for track in track_list:
  273. if not isinstance(track, dict):
  274. continue
  275. if track.get('kind') != 'captions':
  276. continue
  277. src = url_or_none(track.get('src'))
  278. if not src:
  279. continue
  280. lang = track.get('language') or track.get(
  281. 'srclang') or track.get('label')
  282. sub_dict = automatic_captions if track.get(
  283. 'autogenerated') is True else subtitles
  284. sub_dict.setdefault(lang, []).append({
  285. 'url': src,
  286. })
  287. for url_kind in ('download', 'stream'):
  288. urls = asset.get('%s_urls' % url_kind)
  289. if isinstance(urls, dict):
  290. extract_formats(urls.get('Video'))
  291. captions = asset.get('captions')
  292. if isinstance(captions, list):
  293. for cc in captions:
  294. if not isinstance(cc, dict):
  295. continue
  296. cc_url = url_or_none(cc.get('url'))
  297. if not cc_url:
  298. continue
  299. lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
  300. sub_dict = (automatic_captions if cc.get('source') == 'auto'
  301. else subtitles)
  302. sub_dict.setdefault(lang or 'en', []).append({
  303. 'url': cc_url,
  304. })
  305. view_html = lecture.get('view_html')
  306. if view_html:
  307. view_html_urls = set()
  308. for source in re.findall(r'<source[^>]+>', view_html):
  309. attributes = extract_attributes(source)
  310. src = attributes.get('src')
  311. if not src:
  312. continue
  313. res = attributes.get('data-res')
  314. height = int_or_none(res)
  315. if src in view_html_urls:
  316. continue
  317. view_html_urls.add(src)
  318. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  319. m3u8_formats = self._extract_m3u8_formats(
  320. src, video_id, 'mp4', entry_protocol='m3u8_native',
  321. m3u8_id='hls', fatal=False)
  322. for f in m3u8_formats:
  323. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  324. if m:
  325. if not f.get('height'):
  326. f['height'] = int(m.group('height'))
  327. if not f.get('tbr'):
  328. f['tbr'] = int(m.group('tbr'))
  329. formats.extend(m3u8_formats)
  330. else:
  331. formats.append(add_output_format_meta({
  332. 'url': src,
  333. 'format_id': '%dp' % height if height else None,
  334. 'height': height,
  335. }, res))
  336. # react rendition since 2017.04.15 (see
  337. # https://github.com/ytdl-org/youtube-dl/issues/12744)
  338. data = self._parse_json(
  339. self._search_regex(
  340. r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
  341. 'setup data', default='{}', group='data'), video_id,
  342. transform_source=unescapeHTML, fatal=False)
  343. if data and isinstance(data, dict):
  344. extract_formats(data.get('sources'))
  345. if not duration:
  346. duration = int_or_none(data.get('duration'))
  347. extract_subtitles(data.get('tracks'))
  348. if not subtitles and not automatic_captions:
  349. text_tracks = self._parse_json(
  350. self._search_regex(
  351. r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
  352. 'text tracks', default='{}', group='data'), video_id,
  353. transform_source=lambda s: js_to_json(unescapeHTML(s)),
  354. fatal=False)
  355. extract_subtitles(text_tracks)
  356. if not formats and outputs:
  357. for format_id, output in outputs.items():
  358. f = extract_output_format(output, format_id)
  359. if f.get('url'):
  360. formats.append(f)
  361. self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
  362. return {
  363. 'id': video_id,
  364. 'title': title,
  365. 'description': description,
  366. 'thumbnail': thumbnail,
  367. 'duration': duration,
  368. 'formats': formats,
  369. 'subtitles': subtitles,
  370. 'automatic_captions': automatic_captions,
  371. }
  372. class UdemyCourseIE(UdemyIE):
  373. IE_NAME = 'udemy:course'
  374. _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
  375. _TESTS = [{
  376. 'url': 'https://www.udemy.com/java-tutorial/',
  377. 'only_matching': True,
  378. }, {
  379. 'url': 'https://wipro.udemy.com/java-tutorial/',
  380. 'only_matching': True,
  381. }]
  382. @classmethod
  383. def suitable(cls, url):
  384. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  385. def _real_extract(self, url):
  386. course_path = self._match_id(url)
  387. webpage = self._download_webpage(url, course_path)
  388. course_id, title = self._extract_course_info(webpage, course_path)
  389. self._enroll_course(url, webpage, course_id)
  390. response = self._download_json(
  391. 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
  392. course_id, 'Downloading course curriculum', query={
  393. 'fields[chapter]': 'title,object_index',
  394. 'fields[lecture]': 'title,asset',
  395. 'page_size': '1000',
  396. })
  397. entries = []
  398. chapter, chapter_number = [None] * 2
  399. for entry in response['results']:
  400. clazz = entry.get('_class')
  401. if clazz == 'lecture':
  402. asset = entry.get('asset')
  403. if isinstance(asset, dict):
  404. asset_type = asset.get('asset_type') or asset.get('assetType')
  405. if asset_type != 'Video':
  406. continue
  407. lecture_id = entry.get('id')
  408. if lecture_id:
  409. entry = {
  410. '_type': 'url_transparent',
  411. 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
  412. 'title': entry.get('title'),
  413. 'ie_key': UdemyIE.ie_key(),
  414. }
  415. if chapter_number:
  416. entry['chapter_number'] = chapter_number
  417. if chapter:
  418. entry['chapter'] = chapter
  419. entries.append(entry)
  420. elif clazz == 'chapter':
  421. chapter_number = entry.get('object_index')
  422. chapter = entry.get('title')
  423. return self.playlist_result(entries, course_id, title)