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.

362 lines
14 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. formats = []
  183. def extract_output_format(src):
  184. return {
  185. 'url': src['url'],
  186. 'format_id': '%sp' % (src.get('height') or format_id),
  187. 'width': int_or_none(src.get('width')),
  188. 'height': int_or_none(src.get('height')),
  189. 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
  190. 'vcodec': src.get('video_codec'),
  191. 'fps': int_or_none(src.get('frame_rate')),
  192. 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
  193. 'acodec': src.get('audio_codec'),
  194. 'asr': int_or_none(src.get('audio_sample_rate')),
  195. 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
  196. 'filesize': int_or_none(src.get('file_size_in_bytes')),
  197. }
  198. outputs = asset.get('data', {}).get('outputs')
  199. if not isinstance(outputs, dict):
  200. outputs = {}
  201. def add_output_format_meta(f, key):
  202. output = outputs.get(key)
  203. if isinstance(output, dict):
  204. output_format = extract_output_format(output)
  205. output_format.update(f)
  206. return output_format
  207. return f
  208. download_urls = asset.get('download_urls')
  209. if isinstance(download_urls, dict):
  210. video = download_urls.get('Video')
  211. if isinstance(video, list):
  212. for format_ in video:
  213. video_url = format_.get('file')
  214. if not video_url:
  215. continue
  216. format_id = format_.get('label')
  217. f = {
  218. 'url': format_['file'],
  219. 'format_id': '%sp' % format_id,
  220. 'height': int_or_none(format_id),
  221. }
  222. if format_id:
  223. # Some videos contain additional metadata (e.g.
  224. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  225. f = add_output_format_meta(f, format_id)
  226. formats.append(f)
  227. view_html = lecture.get('view_html')
  228. if view_html:
  229. view_html_urls = set()
  230. for source in re.findall(r'<source[^>]+>', view_html):
  231. attributes = extract_attributes(source)
  232. src = attributes.get('src')
  233. if not src:
  234. continue
  235. res = attributes.get('data-res')
  236. height = int_or_none(res)
  237. if src in view_html_urls:
  238. continue
  239. view_html_urls.add(src)
  240. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  241. m3u8_formats = self._extract_m3u8_formats(
  242. src, video_id, 'mp4', entry_protocol='m3u8_native',
  243. m3u8_id='hls', fatal=False)
  244. for f in m3u8_formats:
  245. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  246. if m:
  247. if not f.get('height'):
  248. f['height'] = int(m.group('height'))
  249. if not f.get('tbr'):
  250. f['tbr'] = int(m.group('tbr'))
  251. formats.extend(m3u8_formats)
  252. else:
  253. formats.append(add_output_format_meta({
  254. 'url': src,
  255. 'format_id': '%dp' % height if height else None,
  256. 'height': height,
  257. }, res))
  258. self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
  259. return {
  260. 'id': video_id,
  261. 'title': title,
  262. 'description': description,
  263. 'thumbnail': thumbnail,
  264. 'duration': duration,
  265. 'formats': formats
  266. }
  267. class UdemyCourseIE(UdemyIE):
  268. IE_NAME = 'udemy:course'
  269. _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
  270. _TESTS = []
  271. @classmethod
  272. def suitable(cls, url):
  273. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  274. def _real_extract(self, url):
  275. course_path = self._match_id(url)
  276. webpage = self._download_webpage(url, course_path)
  277. course_id, title = self._extract_course_info(webpage, course_path)
  278. self._enroll_course(url, webpage, course_id)
  279. response = self._download_json(
  280. 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
  281. course_id, 'Downloading course curriculum', query={
  282. 'fields[chapter]': 'title,object_index',
  283. 'fields[lecture]': 'title,asset',
  284. 'page_size': '1000',
  285. })
  286. entries = []
  287. chapter, chapter_number = [None] * 2
  288. for entry in response['results']:
  289. clazz = entry.get('_class')
  290. if clazz == 'lecture':
  291. asset = entry.get('asset')
  292. if isinstance(asset, dict):
  293. asset_type = asset.get('asset_type') or asset.get('assetType')
  294. if asset_type != 'Video':
  295. continue
  296. lecture_id = entry.get('id')
  297. if lecture_id:
  298. entry = {
  299. '_type': 'url_transparent',
  300. 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
  301. 'title': entry.get('title'),
  302. 'ie_key': UdemyIE.ie_key(),
  303. }
  304. if chapter_number:
  305. entry['chapter_number'] = chapter_number
  306. if chapter:
  307. entry['chapter'] = chapter
  308. entries.append(entry)
  309. elif clazz == 'chapter':
  310. chapter_number = entry.get('object_index')
  311. chapter = entry.get('title')
  312. return self.playlist_result(entries, course_id, title)