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.

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