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