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.

416 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=({.+?});', webpage, 'course', default='{}')),
  60. video_id, fatal=False) or {}
  61. course_id = course.get('id') or self._search_regex(
  62. (r'&quot;id&quot;\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'),
  63. 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. format_id = source.get('label')
  223. f = {
  224. 'url': video_url,
  225. 'format_id': '%sp' % format_id,
  226. 'height': int_or_none(format_id),
  227. }
  228. if format_id:
  229. # Some videos contain additional metadata (e.g.
  230. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  231. f = add_output_format_meta(f, format_id)
  232. formats.append(f)
  233. def extract_subtitles(track_list):
  234. if not isinstance(track_list, list):
  235. return
  236. for track in track_list:
  237. if not isinstance(track, dict):
  238. continue
  239. if track.get('kind') != 'captions':
  240. continue
  241. src = track.get('src')
  242. if not src or not isinstance(src, compat_str):
  243. continue
  244. lang = track.get('language') or track.get(
  245. 'srclang') or track.get('label')
  246. sub_dict = automatic_captions if track.get(
  247. 'autogenerated') is True else subtitles
  248. sub_dict.setdefault(lang, []).append({
  249. 'url': src,
  250. })
  251. download_urls = asset.get('download_urls')
  252. if isinstance(download_urls, dict):
  253. extract_formats(download_urls.get('Video'))
  254. view_html = lecture.get('view_html')
  255. if view_html:
  256. view_html_urls = set()
  257. for source in re.findall(r'<source[^>]+>', view_html):
  258. attributes = extract_attributes(source)
  259. src = attributes.get('src')
  260. if not src:
  261. continue
  262. res = attributes.get('data-res')
  263. height = int_or_none(res)
  264. if src in view_html_urls:
  265. continue
  266. view_html_urls.add(src)
  267. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  268. m3u8_formats = self._extract_m3u8_formats(
  269. src, video_id, 'mp4', entry_protocol='m3u8_native',
  270. m3u8_id='hls', fatal=False)
  271. for f in m3u8_formats:
  272. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  273. if m:
  274. if not f.get('height'):
  275. f['height'] = int(m.group('height'))
  276. if not f.get('tbr'):
  277. f['tbr'] = int(m.group('tbr'))
  278. formats.extend(m3u8_formats)
  279. else:
  280. formats.append(add_output_format_meta({
  281. 'url': src,
  282. 'format_id': '%dp' % height if height else None,
  283. 'height': height,
  284. }, res))
  285. # react rendition since 2017.04.15 (see
  286. # https://github.com/rg3/youtube-dl/issues/12744)
  287. data = self._parse_json(
  288. self._search_regex(
  289. r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
  290. 'setup data', default='{}', group='data'), video_id,
  291. transform_source=unescapeHTML, fatal=False)
  292. if data and isinstance(data, dict):
  293. extract_formats(data.get('sources'))
  294. if not duration:
  295. duration = int_or_none(data.get('duration'))
  296. extract_subtitles(data.get('tracks'))
  297. if not subtitles and not automatic_captions:
  298. text_tracks = self._parse_json(
  299. self._search_regex(
  300. r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
  301. 'text tracks', default='{}', group='data'), video_id,
  302. transform_source=lambda s: js_to_json(unescapeHTML(s)),
  303. fatal=False)
  304. extract_subtitles(text_tracks)
  305. self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
  306. return {
  307. 'id': video_id,
  308. 'title': title,
  309. 'description': description,
  310. 'thumbnail': thumbnail,
  311. 'duration': duration,
  312. 'formats': formats,
  313. 'subtitles': subtitles,
  314. 'automatic_captions': automatic_captions,
  315. }
  316. class UdemyCourseIE(UdemyIE):
  317. IE_NAME = 'udemy:course'
  318. _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
  319. _TESTS = []
  320. @classmethod
  321. def suitable(cls, url):
  322. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  323. def _real_extract(self, url):
  324. course_path = self._match_id(url)
  325. webpage = self._download_webpage(url, course_path)
  326. course_id, title = self._extract_course_info(webpage, course_path)
  327. self._enroll_course(url, webpage, course_id)
  328. response = self._download_json(
  329. 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
  330. course_id, 'Downloading course curriculum', query={
  331. 'fields[chapter]': 'title,object_index',
  332. 'fields[lecture]': 'title,asset',
  333. 'page_size': '1000',
  334. })
  335. entries = []
  336. chapter, chapter_number = [None] * 2
  337. for entry in response['results']:
  338. clazz = entry.get('_class')
  339. if clazz == 'lecture':
  340. asset = entry.get('asset')
  341. if isinstance(asset, dict):
  342. asset_type = asset.get('asset_type') or asset.get('assetType')
  343. if asset_type != 'Video':
  344. continue
  345. lecture_id = entry.get('id')
  346. if lecture_id:
  347. entry = {
  348. '_type': 'url_transparent',
  349. 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
  350. 'title': entry.get('title'),
  351. 'ie_key': UdemyIE.ie_key(),
  352. }
  353. if chapter_number:
  354. entry['chapter_number'] = chapter_number
  355. if chapter:
  356. entry['chapter'] = chapter
  357. entries.append(entry)
  358. elif clazz == 'chapter':
  359. chapter_number = entry.get('object_index')
  360. chapter = entry.get('title')
  361. return self.playlist_result(entries, course_id, title)