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