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