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