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.

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