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.

359 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(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
  128. # already logged in
  129. if is_logged(login_popup):
  130. return
  131. login_form = self._form_hidden_inputs('login-form', login_popup)
  132. login_form.update({
  133. 'email': username,
  134. 'password': password,
  135. })
  136. response = self._download_webpage(
  137. self._LOGIN_URL, None, 'Logging in as %s' % username,
  138. data=urlencode_postdata(login_form),
  139. headers={
  140. 'Referer': self._ORIGIN_URL,
  141. 'Origin': self._ORIGIN_URL,
  142. })
  143. if not is_logged(response):
  144. error = self._html_search_regex(
  145. r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
  146. response, 'error message', default=None)
  147. if error:
  148. raise ExtractorError('Unable to login: %s' % error, expected=True)
  149. raise ExtractorError('Unable to log in')
  150. def _real_extract(self, url):
  151. lecture_id = self._match_id(url)
  152. webpage = self._download_webpage(url, lecture_id)
  153. course_id, _ = self._extract_course_info(webpage, lecture_id)
  154. try:
  155. lecture = self._download_lecture(course_id, lecture_id)
  156. except ExtractorError as e:
  157. # Error could possibly mean we are not enrolled in the course
  158. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  159. self._enroll_course(url, webpage, course_id)
  160. lecture = self._download_lecture(course_id, lecture_id)
  161. else:
  162. raise
  163. title = lecture['title']
  164. description = lecture.get('description')
  165. asset = lecture['asset']
  166. asset_type = asset.get('asset_type') or asset.get('assetType')
  167. if asset_type != 'Video':
  168. raise ExtractorError(
  169. 'Lecture %s is not a video' % lecture_id, expected=True)
  170. stream_url = asset.get('stream_url') or asset.get('streamUrl')
  171. if stream_url:
  172. youtube_url = self._search_regex(
  173. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  174. if youtube_url:
  175. return self.url_result(youtube_url, 'Youtube')
  176. video_id = asset['id']
  177. thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
  178. duration = float_or_none(asset.get('data', {}).get('duration'))
  179. formats = []
  180. def extract_output_format(src):
  181. return {
  182. 'url': src['url'],
  183. 'format_id': '%sp' % (src.get('height') or format_id),
  184. 'width': int_or_none(src.get('width')),
  185. 'height': int_or_none(src.get('height')),
  186. 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
  187. 'vcodec': src.get('video_codec'),
  188. 'fps': int_or_none(src.get('frame_rate')),
  189. 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
  190. 'acodec': src.get('audio_codec'),
  191. 'asr': int_or_none(src.get('audio_sample_rate')),
  192. 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
  193. 'filesize': int_or_none(src.get('file_size_in_bytes')),
  194. }
  195. outputs = asset.get('data', {}).get('outputs')
  196. if not isinstance(outputs, dict):
  197. outputs = {}
  198. def add_output_format_meta(f, key):
  199. output = outputs.get(key)
  200. if isinstance(output, dict):
  201. output_format = extract_output_format(output)
  202. output_format.update(f)
  203. return output_format
  204. return f
  205. download_urls = asset.get('download_urls')
  206. if isinstance(download_urls, dict):
  207. video = download_urls.get('Video')
  208. if isinstance(video, list):
  209. for format_ in video:
  210. video_url = format_.get('file')
  211. if not video_url:
  212. continue
  213. format_id = format_.get('label')
  214. f = {
  215. 'url': format_['file'],
  216. 'format_id': '%sp' % format_id,
  217. 'height': int_or_none(format_id),
  218. }
  219. if format_id:
  220. # Some videos contain additional metadata (e.g.
  221. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  222. f = add_output_format_meta(f, format_id)
  223. formats.append(f)
  224. view_html = lecture.get('view_html')
  225. if view_html:
  226. view_html_urls = set()
  227. for source in re.findall(r'<source[^>]+>', view_html):
  228. attributes = extract_attributes(source)
  229. src = attributes.get('src')
  230. if not src:
  231. continue
  232. res = attributes.get('data-res')
  233. height = int_or_none(res)
  234. if src in view_html_urls:
  235. continue
  236. view_html_urls.add(src)
  237. if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
  238. m3u8_formats = self._extract_m3u8_formats(
  239. src, video_id, 'mp4', entry_protocol='m3u8_native',
  240. m3u8_id='hls', fatal=False)
  241. for f in m3u8_formats:
  242. m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
  243. if m:
  244. if not f.get('height'):
  245. f['height'] = int(m.group('height'))
  246. if not f.get('tbr'):
  247. f['tbr'] = int(m.group('tbr'))
  248. formats.extend(m3u8_formats)
  249. else:
  250. formats.append(add_output_format_meta({
  251. 'url': src,
  252. 'format_id': '%dp' % height if height else None,
  253. 'height': height,
  254. }, res))
  255. self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
  256. return {
  257. 'id': video_id,
  258. 'title': title,
  259. 'description': description,
  260. 'thumbnail': thumbnail,
  261. 'duration': duration,
  262. 'formats': formats
  263. }
  264. class UdemyCourseIE(UdemyIE):
  265. IE_NAME = 'udemy:course'
  266. _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[^/?#&]+)'
  267. _TESTS = []
  268. @classmethod
  269. def suitable(cls, url):
  270. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  271. def _real_extract(self, url):
  272. course_path = self._match_id(url)
  273. webpage = self._download_webpage(url, course_path)
  274. course_id, title = self._extract_course_info(webpage, course_path)
  275. self._enroll_course(url, webpage, course_id)
  276. response = self._download_json(
  277. 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
  278. course_id, 'Downloading course curriculum', query={
  279. 'fields[chapter]': 'title,object_index',
  280. 'fields[lecture]': 'title,asset',
  281. 'page_size': '1000',
  282. })
  283. entries = []
  284. chapter, chapter_number = [None] * 2
  285. for entry in response['results']:
  286. clazz = entry.get('_class')
  287. if clazz == 'lecture':
  288. asset = entry.get('asset')
  289. if isinstance(asset, dict):
  290. asset_type = asset.get('asset_type') or asset.get('assetType')
  291. if asset_type != 'Video':
  292. continue
  293. lecture_id = entry.get('id')
  294. if lecture_id:
  295. entry = {
  296. '_type': 'url_transparent',
  297. 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
  298. 'title': entry.get('title'),
  299. 'ie_key': UdemyIE.ie_key(),
  300. }
  301. if chapter_number:
  302. entry['chapter_number'] = chapter_number
  303. if chapter:
  304. entry['chapter'] = chapter
  305. entries.append(entry)
  306. elif clazz == 'chapter':
  307. chapter_number = entry.get('object_index')
  308. chapter = entry.get('title')
  309. return self.playlist_result(entries, course_id, title)