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