You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

421 lines
16 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_HTTPError,
  6. compat_str,
  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. js_to_json,
  17. sanitized_Request,
  18. unescapeHTML,
  19. urlencode_postdata,
  20. )
  21. class UdemyIE(InfoExtractor):
  22. IE_NAME = 'udemy'
  23. _VALID_URL = r'''(?x)
  24. https?://
  25. www\.udemy\.com/
  26. (?:
  27. [^#]+\#/lecture/|
  28. lecture/view/?\?lectureId=|
  29. [^/]+/learn/v4/t/lecture/
  30. )
  31. (?P<id>\d+)
  32. '''
  33. _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
  34. _ORIGIN_URL = 'https://www.udemy.com'
  35. _NETRC_MACHINE = 'udemy'
  36. _TESTS = [{
  37. 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
  38. 'md5': '98eda5b657e752cf945d8445e261b5c5',
  39. 'info_dict': {
  40. 'id': '160614',
  41. 'ext': 'mp4',
  42. 'title': 'Introduction and Installation',
  43. 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
  44. 'duration': 579.29,
  45. },
  46. 'skip': 'Requires udemy account credentials',
  47. }, {
  48. # new URL schema
  49. 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
  50. 'only_matching': True,
  51. }, {
  52. # no url in outputs format entry
  53. 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
  54. 'only_matching': True,
  55. }]
  56. def _extract_course_info(self, webpage, video_id):
  57. course = self._parse_json(
  58. unescapeHTML(self._search_regex(
  59. r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
  60. webpage, 'course', default='{}')),
  61. video_id, fatal=False) or {}
  62. course_id = course.get('id') or self._search_regex(
  63. r'data-course-id=["\'](\d+)', webpage, 'course id')
  64. return course_id, course.get('title')
  65. def _enroll_course(self, base_url, webpage, course_id):
  66. def combine_url(base_url, url):
  67. return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
  68. checkout_url = unescapeHTML(self._search_regex(
  69. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
  70. webpage, 'checkout url', group='url', default=None))
  71. if checkout_url:
  72. raise ExtractorError(
  73. 'Course %s is not free. You have to pay for it before you can download. '
  74. 'Use this URL to confirm purchase: %s'
  75. % (course_id, combine_url(base_url, checkout_url)),
  76. expected=True)
  77. enroll_url = unescapeHTML(self._search_regex(
  78. r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
  79. webpage, 'enroll url', group='url', default=None))
  80. if enroll_url:
  81. webpage = self._download_webpage(
  82. combine_url(base_url, enroll_url),
  83. course_id, 'Enrolling in the course',
  84. headers={'Referer': base_url})
  85. if '>You have enrolled in' in webpage:
  86. self.to_screen('%s: Successfully enrolled in the course' % course_id)
  87. def _download_lecture(self, course_id, lecture_id):
  88. return self._download_json(
  89. 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
  90. % (course_id, lecture_id),
  91. lecture_id, 'Downloading lecture JSON', query={
  92. 'fields[lecture]': 'title,description,view_html,asset',
  93. 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
  94. })
  95. def _handle_error(self, response):
  96. if not isinstance(response, dict):
  97. return
  98. error = response.get('error')
  99. if error:
  100. error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
  101. error_data = error.get('data')
  102. if error_data:
  103. error_str += ' - %s' % error_data.get('formErrors')
  104. raise ExtractorError(error_str, expected=True)
  105. def _download_json(self, url_or_request, *args, **kwargs):
  106. headers = {
  107. 'X-Udemy-Snail-Case': 'true',
  108. 'X-Requested-With': 'XMLHttpRequest',
  109. }
  110. for cookie in self._downloader.cookiejar:
  111. if cookie.name == 'client_id':
  112. headers['X-Udemy-Client-Id'] = cookie.value
  113. elif cookie.name == 'access_token':
  114. headers['X-Udemy-Bearer-Token'] = cookie.value
  115. headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
  116. if isinstance(url_or_request, compat_urllib_request.Request):
  117. for header, value in headers.items():
  118. url_or_request.add_header(header, value)
  119. else:
  120. url_or_request = sanitized_Request(url_or_request, headers=headers)
  121. response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
  122. self._handle_error(response)
  123. return response
  124. def _real_initialize(self):
  125. self._login()
  126. def _login(self):
  127. (username, password) = self._get_login_info()
  128. if username is None:
  129. return
  130. login_popup = self._download_webpage(
  131. self._LOGIN_URL, None, 'Downloading login popup')
  132. def is_logged(webpage):
  133. return any(re.search(p, webpage) for p in (
  134. r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
  135. r'>Logout<'))
  136. # already logged in
  137. if is_logged(login_popup):
  138. return
  139. login_form = self._form_hidden_inputs('login-form', login_popup)
  140. login_form.update({
  141. 'email': username,
  142. 'password': password,
  143. })
  144. response = self._download_webpage(
  145. self._LOGIN_URL, None, 'Logging in',
  146. data=urlencode_postdata(login_form),
  147. headers={
  148. 'Referer': self._ORIGIN_URL,
  149. 'Origin': self._ORIGIN_URL,
  150. })
  151. if not is_logged(response):
  152. error = self._html_search_regex(
  153. r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
  154. response, 'error message', default=None)
  155. if error:
  156. raise ExtractorError('Unable to login: %s' % error, expected=True)
  157. raise ExtractorError('Unable to log in')
  158. def _real_extract(self, url):
  159. lecture_id = self._match_id(url)
  160. webpage = self._download_webpage(url, lecture_id)
  161. course_id, _ = self._extract_course_info(webpage, lecture_id)
  162. try:
  163. lecture = self._download_lecture(course_id, lecture_id)
  164. except ExtractorError as e:
  165. # Error could possibly mean we are not enrolled in the course
  166. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  167. self._enroll_course(url, webpage, course_id)
  168. lecture = self._download_lecture(course_id, lecture_id)
  169. else:
  170. raise
  171. title = lecture['title']
  172. description = lecture.get('description')
  173. asset = lecture['asset']
  174. asset_type = asset.get('asset_type') or asset.get('assetType')
  175. if asset_type != 'Video':
  176. raise ExtractorError(
  177. 'Lecture %s is not a video' % lecture_id, expected=True)
  178. stream_url = asset.get('stream_url') or asset.get('streamUrl')
  179. if stream_url:
  180. youtube_url = self._search_regex(
  181. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  182. if youtube_url:
  183. return self.url_result(youtube_url, 'Youtube')
  184. video_id = compat_str(asset['id'])
  185. thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
  186. duration = float_or_none(asset.get('data', {}).get('duration'))
  187. subtitles = {}
  188. automatic_captions = {}
  189. formats = []
  190. def extract_output_format(src, f_id):
  191. return {
  192. 'url': src.get('url'),
  193. 'format_id': '%sp' % (src.get('height') or f_id),
  194. 'width': int_or_none(src.get('width')),
  195. 'height': int_or_none(src.get('height')),
  196. 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
  197. 'vcodec': src.get('video_codec'),
  198. 'fps': int_or_none(src.get('frame_rate')),
  199. 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
  200. 'acodec': src.get('audio_codec'),
  201. 'asr': int_or_none(src.get('audio_sample_rate')),
  202. 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
  203. 'filesize': int_or_none(src.get('file_size_in_bytes')),
  204. }
  205. outputs = asset.get('data', {}).get('outputs')
  206. if not isinstance(outputs, dict):
  207. outputs = {}
  208. def add_output_format_meta(f, key):
  209. output = outputs.get(key)
  210. if isinstance(output, dict):
  211. output_format = extract_output_format(output, key)
  212. output_format.update(f)
  213. return output_format
  214. return f
  215. def extract_formats(source_list):
  216. if not isinstance(source_list, list):
  217. return
  218. for source in source_list:
  219. video_url = source.get('file') or source.get('src')
  220. if not video_url or not isinstance(video_url, compat_str):
  221. continue
  222. if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
  223. formats.extend(self._extract_m3u8_formats(
  224. video_url, video_id, 'mp4', entry_protocol='m3u8_native',
  225. m3u8_id='hls', fatal=False))
  226. continue
  227. format_id = source.get('label')
  228. f = {
  229. 'url': video_url,
  230. 'format_id': '%sp' % format_id,
  231. 'height': int_or_none(format_id),
  232. }
  233. if format_id:
  234. # Some videos contain additional metadata (e.g.
  235. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  236. f = add_output_format_meta(f, format_id)
  237. formats.append(f)
  238. def extract_subtitles(track_list):
  239. if not isinstance(track_list, list):
  240. return
  241. for track in track_list:
  242. if not isinstance(track, dict):
  243. continue
  244. if track.get('kind') != 'captions':
  245. continue
  246. src = track.get('src')
  247. if not src or not isinstance(src, compat_str):
  248. continue
  249. lang = track.get('language') or track.get(
  250. 'srclang') or track.get('label')
  251. sub_dict = automatic_captions if track.get(
  252. 'autogenerated') is True else subtitles
  253. sub_dict.setdefault(lang, []).append({
  254. 'url': src,
  255. })
  256. download_urls = asset.get('download_urls')
  257. if isinstance(download_urls, dict):
  258. extract_formats(download_urls.get('Video'))
  259. view_html = lecture.get('view_html')
  260. if view_html:
  261. view_html_urls = set()
  262. for source in re.findall(r'<source[^>]+>', view_html):
  263. attributes = extract_attributes(source)
  264. src = attributes.get('src')
  265. if not src:
  266. continue
  267. res = attributes.get('data-res')
  268. height = int_or_none(res)
  269. if src in view_html_urls:
  270. continue
  271. view_html_urls.add(src)
  272. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  273. m3u8_formats = self._extract_m3u8_formats(
  274. src, video_id, 'mp4', entry_protocol='m3u8_native',
  275. m3u8_id='hls', fatal=False)
  276. for f in m3u8_formats:
  277. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  278. if m:
  279. if not f.get('height'):
  280. f['height'] = int(m.group('height'))
  281. if not f.get('tbr'):
  282. f['tbr'] = int(m.group('tbr'))
  283. formats.extend(m3u8_formats)
  284. else:
  285. formats.append(add_output_format_meta({
  286. 'url': src,
  287. 'format_id': '%dp' % height if height else None,
  288. 'height': height,
  289. }, res))
  290. # react rendition since 2017.04.15 (see
  291. # https://github.com/rg3/youtube-dl/issues/12744)
  292. data = self._parse_json(
  293. self._search_regex(
  294. r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
  295. 'setup data', default='{}', group='data'), video_id,
  296. transform_source=unescapeHTML, fatal=False)
  297. if data and isinstance(data, dict):
  298. extract_formats(data.get('sources'))
  299. if not duration:
  300. duration = int_or_none(data.get('duration'))
  301. extract_subtitles(data.get('tracks'))
  302. if not subtitles and not automatic_captions:
  303. text_tracks = self._parse_json(
  304. self._search_regex(
  305. r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
  306. 'text tracks', default='{}', group='data'), video_id,
  307. transform_source=lambda s: js_to_json(unescapeHTML(s)),
  308. fatal=False)
  309. extract_subtitles(text_tracks)
  310. self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
  311. return {
  312. 'id': video_id,
  313. 'title': title,
  314. 'description': description,
  315. 'thumbnail': thumbnail,
  316. 'duration': duration,
  317. 'formats': formats,
  318. 'subtitles': subtitles,
  319. 'automatic_captions': automatic_captions,
  320. }
  321. class UdemyCourseIE(UdemyIE):
  322. IE_NAME = 'udemy:course'
  323. _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
  324. _TESTS = []
  325. @classmethod
  326. def suitable(cls, url):
  327. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  328. def _real_extract(self, url):
  329. course_path = self._match_id(url)
  330. webpage = self._download_webpage(url, course_path)
  331. course_id, title = self._extract_course_info(webpage, course_path)
  332. self._enroll_course(url, webpage, course_id)
  333. response = self._download_json(
  334. 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
  335. course_id, 'Downloading course curriculum', query={
  336. 'fields[chapter]': 'title,object_index',
  337. 'fields[lecture]': 'title,asset',
  338. 'page_size': '1000',
  339. })
  340. entries = []
  341. chapter, chapter_number = [None] * 2
  342. for entry in response['results']:
  343. clazz = entry.get('_class')
  344. if clazz == 'lecture':
  345. asset = entry.get('asset')
  346. if isinstance(asset, dict):
  347. asset_type = asset.get('asset_type') or asset.get('assetType')
  348. if asset_type != 'Video':
  349. continue
  350. lecture_id = entry.get('id')
  351. if lecture_id:
  352. entry = {
  353. '_type': 'url_transparent',
  354. 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
  355. 'title': entry.get('title'),
  356. 'ie_key': UdemyIE.ie_key(),
  357. }
  358. if chapter_number:
  359. entry['chapter_number'] = chapter_number
  360. if chapter:
  361. entry['chapter'] = chapter
  362. entries.append(entry)
  363. elif clazz == 'chapter':
  364. chapter_number = entry.get('object_index')
  365. chapter = entry.get('title')
  366. return self.playlist_result(entries, course_id, title)