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.

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