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.

274 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+)', r'&quot;id&quot;\s*:\s*(\d+)'),
  124. webpage, 'course id')
  125. try:
  126. lecture = self._download_lecture(course_id, lecture_id)
  127. except ExtractorError as e:
  128. # Error could possibly mean we are not enrolled in the course
  129. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  130. self._enroll_course(webpage, course_id)
  131. lecture = self._download_lecture(course_id, lecture_id)
  132. else:
  133. raise
  134. title = lecture['title']
  135. description = lecture.get('description')
  136. asset = lecture['asset']
  137. asset_type = asset.get('assetType') or asset.get('asset_type')
  138. if asset_type != 'Video':
  139. raise ExtractorError(
  140. 'Lecture %s is not a video' % lecture_id, expected=True)
  141. stream_url = asset.get('streamUrl') or asset.get('stream_url')
  142. if stream_url:
  143. youtube_url = self._search_regex(
  144. r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
  145. if youtube_url:
  146. return self.url_result(youtube_url, 'Youtube')
  147. video_id = asset['id']
  148. thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
  149. duration = float_or_none(asset.get('data', {}).get('duration'))
  150. outputs = asset.get('data', {}).get('outputs', {})
  151. formats = []
  152. for format_ in asset.get('download_urls', {}).get('Video', []):
  153. video_url = format_.get('file')
  154. if not video_url:
  155. continue
  156. format_id = format_.get('label')
  157. f = {
  158. 'url': format_['file'],
  159. 'height': int_or_none(format_id),
  160. }
  161. if format_id:
  162. # Some videos contain additional metadata (e.g.
  163. # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
  164. output = outputs.get(format_id)
  165. if isinstance(output, dict):
  166. f.update({
  167. 'format_id': '%sp' % (output.get('label') or format_id),
  168. 'width': int_or_none(output.get('width')),
  169. 'height': int_or_none(output.get('height')),
  170. 'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
  171. 'vcodec': output.get('video_codec'),
  172. 'fps': int_or_none(output.get('frame_rate')),
  173. 'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
  174. 'acodec': output.get('audio_codec'),
  175. 'asr': int_or_none(output.get('audio_sample_rate')),
  176. 'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
  177. 'filesize': int_or_none(output.get('file_size_in_bytes')),
  178. })
  179. else:
  180. f['format_id'] = '%sp' % format_id
  181. formats.append(f)
  182. self._sort_formats(formats)
  183. return {
  184. 'id': video_id,
  185. 'title': title,
  186. 'description': description,
  187. 'thumbnail': thumbnail,
  188. 'duration': duration,
  189. 'formats': formats
  190. }
  191. class UdemyCourseIE(UdemyIE):
  192. IE_NAME = 'udemy:course'
  193. _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
  194. _TESTS = []
  195. @classmethod
  196. def suitable(cls, url):
  197. return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
  198. def _real_extract(self, url):
  199. course_path = self._match_id(url)
  200. webpage = self._download_webpage(url, course_path)
  201. response = self._download_json(
  202. 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
  203. course_path, 'Downloading course JSON')
  204. course_id = response['id']
  205. course_title = response.get('title')
  206. self._enroll_course(webpage, course_id)
  207. response = self._download_json(
  208. 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
  209. course_id, 'Downloading course curriculum')
  210. entries = []
  211. chapter, chapter_number = None, None
  212. for asset in response:
  213. asset_type = asset.get('assetType') or asset.get('asset_type')
  214. if asset_type == 'Video':
  215. asset_id = asset.get('id')
  216. if asset_id:
  217. entry = {
  218. '_type': 'url_transparent',
  219. 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
  220. 'ie_key': UdemyIE.ie_key(),
  221. }
  222. if chapter_number:
  223. entry['chapter_number'] = chapter_number
  224. if chapter:
  225. entry['chapter'] = chapter
  226. entries.append(entry)
  227. elif asset.get('type') == 'chapter':
  228. chapter_number = asset.get('index') or asset.get('object_index')
  229. chapter = asset.get('title')
  230. return self.playlist_result(entries, course_id, course_title)