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.

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