]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/udemy.py
cf7bd0ae5e8e3b9879066da7c30e07937471b438
[youtube-dl.git] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     compat_urllib_parse,
8     compat_urllib_request,
9     ExtractorError,
10 )
11
12
13 class UdemyIE(InfoExtractor):
14     IE_NAME = 'udemy'
15     _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
16     _LOGIN_URL = 'https://www.udemy.com/join/login-submit/'
17     _NETRC_MACHINE = 'udemy'
18
19     _TESTS = [{
20         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
21         'md5': '98eda5b657e752cf945d8445e261b5c5',
22         'info_dict': {
23             'id': '160614',
24             'ext': 'mp4',
25             'title': 'Introduction and Installation',
26             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
27             'duration': 579.29,
28         },
29         'skip': 'Requires udemy account credentials',
30     }]
31
32     def _handle_error(self, response):
33         if not isinstance(response, dict):
34             return
35         error = response.get('error')
36         if error:
37             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
38             error_data = error.get('data')
39             if error_data:
40                 error_str += ' - %s' % error_data.get('formErrors')
41             raise ExtractorError(error_str, expected=True)
42
43     def _download_json(self, url, video_id, note='Downloading JSON metadata'):
44         response = super(UdemyIE, self)._download_json(url, video_id, note)
45         self._handle_error(response)
46         return response
47
48     def _download_json_cookies(self, url, video_id, note):
49         headers = {
50             'X-Udemy-Snail-Case': 'true',
51             'X-Requested-With': 'XMLHttpRequest',
52         }
53         for cookie in self._downloader.cookiejar:
54             if cookie.name == 'client_id':
55                 headers['X-Udemy-Client-Id'] = cookie.value
56             elif cookie.name == 'access_token':
57                 headers['X-Udemy-Bearer-Token'] = cookie.value
58         request = compat_urllib_request.Request(url, headers=headers)
59         return self._download_json(request, video_id, note)
60
61     def _real_initialize(self):
62         self._login()
63
64     def _login(self):
65         (username, password) = self._get_login_info()
66         if username is None:
67             raise ExtractorError(
68                 'Udemy account is required, use --username and --password options to provide account credentials.',
69                 expected=True)
70
71         login_popup = self._download_webpage(
72             'https://www.udemy.com/join/login-popup?displayType=ajax&showSkipButton=1', None,
73             'Downloading login popup')
74
75         if login_popup == '<div class="run-command close-popup redirect" data-url="https://www.udemy.com/"></div>':
76             return
77
78         csrf = self._html_search_regex(
79             r'<input type="hidden" name="csrf" value="(.+?)"',
80             login_popup, 'csrf token')
81
82         login_form = {
83             'email': username,
84             'password': password,
85             'csrf': csrf,
86             'displayType': 'json',
87             'isSubmitted': '1',
88         }
89         request = compat_urllib_request.Request(
90             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
91         response = self._download_json(
92             request, None, 'Logging in as %s' % username)
93
94         if 'returnUrl' not in response:
95             raise ExtractorError('Unable to log in')
96
97
98
99     def _real_extract(self, url):
100         mobj = re.match(self._VALID_URL, url)
101         lecture_id = mobj.group('id')
102
103         lecture = self._download_json_cookies(
104             'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
105             lecture_id, 'Downloading lecture JSON')
106
107         asset_type = lecture.get('assetType') or lecture.get('asset_type')
108         if asset_type != 'Video':
109             raise ExtractorError(
110                 'Lecture %s is not a video' % lecture_id, expected=True)
111
112         asset = lecture['asset']
113
114         stream_url = asset.get('streamUrl') or asset.get('stream_url')
115         mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
116         if mobj:
117             return self.url_result(mobj.group(1), 'Youtube')
118
119         video_id = asset['id']
120         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
121         duration = asset['data']['duration']
122
123         download_url = asset.get('downloadUrl') or asset.get('download_url')
124
125         video = download_url.get('Video') or download_url.get('video')
126         video_480p = download_url.get('Video480p') or download_url.get('video_480p')
127
128         formats = [
129             {
130                 'url': video_480p[0],
131                 'format_id': '360p',
132             },
133             {
134                 'url': video[0],
135                 'format_id': '720p',
136             },
137         ]
138
139         title = lecture['title']
140         description = lecture['description']
141
142         return {
143             'id': video_id,
144             'title': title,
145             'description': description,
146             'thumbnail': thumbnail,
147             'duration': duration,
148             'formats': formats
149         }
150
151
152 class UdemyCourseIE(UdemyIE):
153     IE_NAME = 'udemy:course'
154     _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
155     _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
156     _ALREADY_ENROLLED = '>You are already taking this course.<'
157     _TESTS = []
158
159     @classmethod
160     def suitable(cls, url):
161         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
162
163     def _real_extract(self, url):
164         mobj = re.match(self._VALID_URL, url)
165         course_path = mobj.group('coursepath')
166
167         response = self._download_json_cookies(
168             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
169             course_path, 'Downloading course JSON')
170
171         course_id = int(response['id'])
172         course_title = response['title']
173
174         webpage = self._download_webpage(
175             'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
176             course_id, 'Enrolling in the course')
177
178         if self._SUCCESSFULLY_ENROLLED in webpage:
179             self.to_screen('%s: Successfully enrolled in' % course_id)
180         elif self._ALREADY_ENROLLED in webpage:
181             self.to_screen('%s: Already enrolled in' % course_id)
182
183         response = self._download_json_cookies(
184             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
185             course_id, 'Downloading course curriculum')
186
187         entries = [
188             self.url_result(
189                 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
190             for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
191         ]
192
193         return self.playlist_result(entries, course_id, course_title)