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.

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