Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

479 lines
19KB

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