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.

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