[udemy] Add support for react rendition (closes #12744)
[youtube-dl] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_HTTPError,
8     compat_str,
9     compat_urllib_request,
10     compat_urlparse,
11 )
12 from ..utils import (
13     determine_ext,
14     extract_attributes,
15     ExtractorError,
16     float_or_none,
17     int_or_none,
18     sanitized_Request,
19     unescapeHTML,
20     urlencode_postdata,
21 )
22
23
24 class UdemyIE(InfoExtractor):
25     IE_NAME = 'udemy'
26     _VALID_URL = r'''(?x)
27                     https?://
28                         www\.udemy\.com/
29                         (?:
30                             [^#]+\#/lecture/|
31                             lecture/view/?\?lectureId=|
32                             [^/]+/learn/v4/t/lecture/
33                         )
34                         (?P<id>\d+)
35                     '''
36     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
37     _ORIGIN_URL = 'https://www.udemy.com'
38     _NETRC_MACHINE = 'udemy'
39
40     _TESTS = [{
41         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
42         'md5': '98eda5b657e752cf945d8445e261b5c5',
43         'info_dict': {
44             'id': '160614',
45             'ext': 'mp4',
46             'title': 'Introduction and Installation',
47             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
48             'duration': 579.29,
49         },
50         'skip': 'Requires udemy account credentials',
51     }, {
52         # new URL schema
53         'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
54         'only_matching': True,
55     }]
56
57     def _extract_course_info(self, webpage, video_id):
58         course = self._parse_json(
59             unescapeHTML(self._search_regex(
60                 r'ng-init=["\'].*\bcourse=({.+?});', webpage, 'course', default='{}')),
61             video_id, fatal=False) or {}
62         course_id = course.get('id') or self._search_regex(
63             (r'&quot;id&quot;\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'),
64             webpage, 'course id')
65         return course_id, course.get('title')
66
67     def _enroll_course(self, base_url, webpage, course_id):
68         def combine_url(base_url, url):
69             return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
70
71         checkout_url = unescapeHTML(self._search_regex(
72             r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1',
73             webpage, 'checkout url', group='url', default=None))
74         if checkout_url:
75             raise ExtractorError(
76                 'Course %s is not free. You have to pay for it before you can download. '
77                 'Use this URL to confirm purchase: %s'
78                 % (course_id, combine_url(base_url, checkout_url)),
79                 expected=True)
80
81         enroll_url = unescapeHTML(self._search_regex(
82             r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
83             webpage, 'enroll url', group='url', default=None))
84         if enroll_url:
85             webpage = self._download_webpage(
86                 combine_url(base_url, enroll_url),
87                 course_id, 'Enrolling in the course',
88                 headers={'Referer': base_url})
89             if '>You have enrolled in' in webpage:
90                 self.to_screen('%s: Successfully enrolled in the course' % course_id)
91
92     def _download_lecture(self, course_id, lecture_id):
93         return self._download_json(
94             'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
95             % (course_id, lecture_id),
96             lecture_id, 'Downloading lecture JSON', query={
97                 'fields[lecture]': 'title,description,view_html,asset',
98                 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
99             })
100
101     def _handle_error(self, response):
102         if not isinstance(response, dict):
103             return
104         error = response.get('error')
105         if error:
106             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
107             error_data = error.get('data')
108             if error_data:
109                 error_str += ' - %s' % error_data.get('formErrors')
110             raise ExtractorError(error_str, expected=True)
111
112     def _download_json(self, url_or_request, *args, **kwargs):
113         headers = {
114             'X-Udemy-Snail-Case': 'true',
115             'X-Requested-With': 'XMLHttpRequest',
116         }
117         for cookie in self._downloader.cookiejar:
118             if cookie.name == 'client_id':
119                 headers['X-Udemy-Client-Id'] = cookie.value
120             elif cookie.name == 'access_token':
121                 headers['X-Udemy-Bearer-Token'] = cookie.value
122                 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
123
124         if isinstance(url_or_request, compat_urllib_request.Request):
125             for header, value in headers.items():
126                 url_or_request.add_header(header, value)
127         else:
128             url_or_request = sanitized_Request(url_or_request, headers=headers)
129
130         response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
131         self._handle_error(response)
132         return response
133
134     def _real_initialize(self):
135         self._login()
136
137     def _login(self):
138         (username, password) = self._get_login_info()
139         if username is None:
140             return
141
142         login_popup = self._download_webpage(
143             self._LOGIN_URL, None, 'Downloading login popup')
144
145         def is_logged(webpage):
146             return any(re.search(p, webpage) for p in (
147                 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
148                 r'>Logout<'))
149
150         # already logged in
151         if is_logged(login_popup):
152             return
153
154         login_form = self._form_hidden_inputs('login-form', login_popup)
155
156         login_form.update({
157             'email': username,
158             'password': password,
159         })
160
161         response = self._download_webpage(
162             self._LOGIN_URL, None, 'Logging in as %s' % username,
163             data=urlencode_postdata(login_form),
164             headers={
165                 'Referer': self._ORIGIN_URL,
166                 'Origin': self._ORIGIN_URL,
167             })
168
169         if not is_logged(response):
170             error = self._html_search_regex(
171                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
172                 response, 'error message', default=None)
173             if error:
174                 raise ExtractorError('Unable to login: %s' % error, expected=True)
175             raise ExtractorError('Unable to log in')
176
177     def _real_extract(self, url):
178         lecture_id = self._match_id(url)
179
180         webpage = self._download_webpage(url, lecture_id)
181
182         course_id, _ = self._extract_course_info(webpage, lecture_id)
183
184         try:
185             lecture = self._download_lecture(course_id, lecture_id)
186         except ExtractorError as e:
187             # Error could possibly mean we are not enrolled in the course
188             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
189                 self._enroll_course(url, webpage, course_id)
190                 lecture = self._download_lecture(course_id, lecture_id)
191             else:
192                 raise
193
194         title = lecture['title']
195         description = lecture.get('description')
196
197         asset = lecture['asset']
198
199         asset_type = asset.get('asset_type') or asset.get('assetType')
200         if asset_type != 'Video':
201             raise ExtractorError(
202                 'Lecture %s is not a video' % lecture_id, expected=True)
203
204         stream_url = asset.get('stream_url') or asset.get('streamUrl')
205         if stream_url:
206             youtube_url = self._search_regex(
207                 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
208             if youtube_url:
209                 return self.url_result(youtube_url, 'Youtube')
210
211         video_id = compat_str(asset['id'])
212         thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
213         duration = float_or_none(asset.get('data', {}).get('duration'))
214
215         subtitles = {}
216         automatic_captions = {}
217
218         formats = []
219
220         def extract_output_format(src, f_id):
221             return {
222                 'url': src['url'],
223                 'format_id': '%sp' % (src.get('height') or f_id),
224                 'width': int_or_none(src.get('width')),
225                 'height': int_or_none(src.get('height')),
226                 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
227                 'vcodec': src.get('video_codec'),
228                 'fps': int_or_none(src.get('frame_rate')),
229                 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
230                 'acodec': src.get('audio_codec'),
231                 'asr': int_or_none(src.get('audio_sample_rate')),
232                 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
233                 'filesize': int_or_none(src.get('file_size_in_bytes')),
234             }
235
236         outputs = asset.get('data', {}).get('outputs')
237         if not isinstance(outputs, dict):
238             outputs = {}
239
240         def add_output_format_meta(f, key):
241             output = outputs.get(key)
242             if isinstance(output, dict):
243                 output_format = extract_output_format(output, key)
244                 output_format.update(f)
245                 return output_format
246             return f
247
248         def extract_formats(source_list):
249             if not isinstance(source_list, list):
250                 return
251             for source in source_list:
252                 video_url = source.get('file') or source.get('src')
253                 if not video_url or not isinstance(video_url, compat_str):
254                     continue
255                 format_id = source.get('label')
256                 f = {
257                     'url': video_url,
258                     'format_id': '%sp' % format_id,
259                     'height': int_or_none(format_id),
260                 }
261                 if format_id:
262                     # Some videos contain additional metadata (e.g.
263                     # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
264                     f = add_output_format_meta(f, format_id)
265                 formats.append(f)
266
267         download_urls = asset.get('download_urls')
268         if isinstance(download_urls, dict):
269             extract_formats(download_urls.get('Video'))
270
271         view_html = lecture.get('view_html')
272         if view_html:
273             view_html_urls = set()
274             for source in re.findall(r'<source[^>]+>', view_html):
275                 attributes = extract_attributes(source)
276                 src = attributes.get('src')
277                 if not src:
278                     continue
279                 res = attributes.get('data-res')
280                 height = int_or_none(res)
281                 if src in view_html_urls:
282                     continue
283                 view_html_urls.add(src)
284                 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
285                     m3u8_formats = self._extract_m3u8_formats(
286                         src, video_id, 'mp4', entry_protocol='m3u8_native',
287                         m3u8_id='hls', fatal=False)
288                     for f in m3u8_formats:
289                         m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
290                         if m:
291                             if not f.get('height'):
292                                 f['height'] = int(m.group('height'))
293                             if not f.get('tbr'):
294                                 f['tbr'] = int(m.group('tbr'))
295                     formats.extend(m3u8_formats)
296                 else:
297                     formats.append(add_output_format_meta({
298                         'url': src,
299                         'format_id': '%dp' % height if height else None,
300                         'height': height,
301                     }, res))
302
303             # react rendition since 2017.04.15 (see
304             # https://github.com/rg3/youtube-dl/issues/12744)
305             data = self._parse_json(
306                 self._search_regex(
307                     r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
308                     'setup data', default='{}', group='data'), video_id,
309                 transform_source=unescapeHTML, fatal=False)
310             if data and isinstance(data, dict):
311                 extract_formats(data.get('sources'))
312                 if not duration:
313                     duration = int_or_none(data.get('duration'))
314                 tracks = data.get('tracks')
315                 if isinstance(tracks, list):
316                     for track in tracks:
317                         if not isinstance(track, dict):
318                             continue
319                         if track.get('kind') != 'captions':
320                             continue
321                         src = track.get('src')
322                         if not src or not isinstance(src, compat_str):
323                             continue
324                         lang = track.get('language') or track.get(
325                             'srclang') or track.get('label')
326                         sub_dict = automatic_captions if track.get(
327                             'autogenerated') is True else subtitles
328                         sub_dict.setdefault(lang, []).append({
329                             'url': src,
330                         })
331
332         self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
333
334         return {
335             'id': video_id,
336             'title': title,
337             'description': description,
338             'thumbnail': thumbnail,
339             'duration': duration,
340             'formats': formats,
341             'subtitles': subtitles,
342             'automatic_captions': automatic_captions,
343         }
344
345
346 class UdemyCourseIE(UdemyIE):
347     IE_NAME = 'udemy:course'
348     _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
349     _TESTS = []
350
351     @classmethod
352     def suitable(cls, url):
353         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
354
355     def _real_extract(self, url):
356         course_path = self._match_id(url)
357
358         webpage = self._download_webpage(url, course_path)
359
360         course_id, title = self._extract_course_info(webpage, course_path)
361
362         self._enroll_course(url, webpage, course_id)
363
364         response = self._download_json(
365             'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
366             course_id, 'Downloading course curriculum', query={
367                 'fields[chapter]': 'title,object_index',
368                 'fields[lecture]': 'title,asset',
369                 'page_size': '1000',
370             })
371
372         entries = []
373         chapter, chapter_number = [None] * 2
374         for entry in response['results']:
375             clazz = entry.get('_class')
376             if clazz == 'lecture':
377                 asset = entry.get('asset')
378                 if isinstance(asset, dict):
379                     asset_type = asset.get('asset_type') or asset.get('assetType')
380                     if asset_type != 'Video':
381                         continue
382                 lecture_id = entry.get('id')
383                 if lecture_id:
384                     entry = {
385                         '_type': 'url_transparent',
386                         'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
387                         'title': entry.get('title'),
388                         'ie_key': UdemyIE.ie_key(),
389                     }
390                     if chapter_number:
391                         entry['chapter_number'] = chapter_number
392                     if chapter:
393                         entry['chapter'] = chapter
394                     entries.append(entry)
395             elif clazz == 'chapter':
396                 chapter_number = entry.get('object_index')
397                 chapter = entry.get('title')
398
399         return self.playlist_result(entries, course_id, title)