[udemy] Add outputs metadata to view_html 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         for format_id, output in outputs.items():
232             if isinstance(output, dict) and output.get('url'):
233                 formats.append(extract_output_format(output))
234
235         download_urls = asset.get('download_urls')
236         if isinstance(download_urls, dict):
237             video = download_urls.get('Video')
238             if isinstance(video, list):
239                 for format_ in video:
240                     video_url = format_.get('file')
241                     if not video_url:
242                         continue
243                     format_id = format_.get('label')
244                     f = {
245                         'url': format_['file'],
246                         'height': int_or_none(format_id),
247                     }
248                     if format_id:
249                         # Some videos contain additional metadata (e.g.
250                         # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
251                         f = add_output_format_meta(f, format_id, '%sp' % format_id)
252                     formats.append(f)
253
254         view_html = lecture.get('view_html')
255         if view_html:
256             view_html_urls = set()
257             for source in re.findall(r'<source[^>]+>', view_html):
258                 attributes = extract_attributes(source)
259                 src = attributes.get('src')
260                 if not src:
261                     continue
262                 res = attributes.get('data-res')
263                 height = int_or_none(res)
264                 if src in view_html_urls:
265                     continue
266                 view_html_urls.add(src)
267                 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
268                     m3u8_formats = self._extract_m3u8_formats(
269                         src, video_id, 'mp4', entry_protocol='m3u8_native',
270                         m3u8_id='hls', fatal=False)
271                     for f in m3u8_formats:
272                         m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
273                         if m:
274                             if not f.get('height'):
275                                 f['height'] = int(m.group('height'))
276                             if not f.get('tbr'):
277                                 f['tbr'] = int(m.group('tbr'))
278                     formats.extend(m3u8_formats)
279                 else:
280                     formats.append(add_output_format_meta({
281                         'url': src,
282                         'height': height,
283                     }, res, '%dp' % height if height else None))
284
285         self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
286
287         return {
288             'id': video_id,
289             'title': title,
290             'description': description,
291             'thumbnail': thumbnail,
292             'duration': duration,
293             'formats': formats
294         }
295
296
297 class UdemyCourseIE(UdemyIE):
298     IE_NAME = 'udemy:course'
299     _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
300     _TESTS = []
301
302     @classmethod
303     def suitable(cls, url):
304         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
305
306     def _real_extract(self, url):
307         course_path = self._match_id(url)
308
309         webpage = self._download_webpage(url, course_path)
310
311         response = self._download_json(
312             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
313             course_path, 'Downloading course JSON')
314
315         course_id = response['id']
316         course_title = response.get('title')
317
318         self._enroll_course(url, webpage, course_id)
319
320         response = self._download_json(
321             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
322             course_id, 'Downloading course curriculum')
323
324         entries = []
325         chapter, chapter_number = None, None
326         for asset in response:
327             asset_type = asset.get('assetType') or asset.get('asset_type')
328             if asset_type == 'Video':
329                 asset_id = asset.get('id')
330                 if asset_id:
331                     entry = {
332                         '_type': 'url_transparent',
333                         'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
334                         'ie_key': UdemyIE.ie_key(),
335                     }
336                     if chapter_number:
337                         entry['chapter_number'] = chapter_number
338                     if chapter:
339                         entry['chapter'] = chapter
340                     entries.append(entry)
341             elif asset.get('type') == 'chapter':
342                 chapter_number = asset.get('index') or asset.get('object_index')
343                 chapter = asset.get('title')
344
345         return self.playlist_result(entries, course_id, course_title)