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.

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