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.

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