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