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