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