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