[udemy] Improve course id v4 regex
[youtube-dl] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 from .common import InfoExtractor
4 from ..compat import (
5     compat_HTTPError,
6     compat_urllib_parse,
7     compat_urllib_request,
8 )
9 from ..utils import (
10     ExtractorError,
11     float_or_none,
12     int_or_none,
13     sanitized_Request,
14     unescapeHTML,
15 )
16
17
18 class UdemyIE(InfoExtractor):
19     IE_NAME = 'udemy'
20     _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
21     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
22     _ORIGIN_URL = 'https://www.udemy.com'
23     _NETRC_MACHINE = 'udemy'
24
25     _TESTS = [{
26         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
27         'md5': '98eda5b657e752cf945d8445e261b5c5',
28         'info_dict': {
29             'id': '160614',
30             'ext': 'mp4',
31             'title': 'Introduction and Installation',
32             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
33             'duration': 579.29,
34         },
35         'skip': 'Requires udemy account credentials',
36     }]
37
38     def _enroll_course(self, webpage, course_id):
39         checkout_url = unescapeHTML(self._search_regex(
40             r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1',
41             webpage, 'checkout url', group='url', default=None))
42         if checkout_url:
43             raise ExtractorError(
44                 'Course %s is not free. You have to pay for it before you can download. '
45                 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True)
46
47         enroll_url = unescapeHTML(self._search_regex(
48             r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/course/subscribe/.+?)\1',
49             webpage, 'enroll url', group='url', default=None))
50         if enroll_url:
51             webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
52             if '>You have enrolled in' in webpage:
53                 self.to_screen('%s: Successfully enrolled in the course' % course_id)
54
55     def _download_lecture(self, course_id, lecture_id):
56         return self._download_json(
57             'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
58                 course_id, lecture_id, compat_urllib_parse.urlencode({
59                     'video_only': '',
60                     'auto_play': '',
61                     'fields[lecture]': 'title,description,asset',
62                     'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
63                     'instructorPreviewMode': 'False',
64                 })),
65             lecture_id, 'Downloading lecture JSON')
66
67     def _handle_error(self, response):
68         if not isinstance(response, dict):
69             return
70         error = response.get('error')
71         if error:
72             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
73             error_data = error.get('data')
74             if error_data:
75                 error_str += ' - %s' % error_data.get('formErrors')
76             raise ExtractorError(error_str, expected=True)
77
78     def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
79         headers = {
80             'X-Udemy-Snail-Case': 'true',
81             'X-Requested-With': 'XMLHttpRequest',
82         }
83         for cookie in self._downloader.cookiejar:
84             if cookie.name == 'client_id':
85                 headers['X-Udemy-Client-Id'] = cookie.value
86             elif cookie.name == 'access_token':
87                 headers['X-Udemy-Bearer-Token'] = cookie.value
88                 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
89
90         if isinstance(url_or_request, compat_urllib_request.Request):
91             for header, value in headers.items():
92                 url_or_request.add_header(header, value)
93         else:
94             url_or_request = sanitized_Request(url_or_request, headers=headers)
95
96         response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
97         self._handle_error(response)
98         return response
99
100     def _real_initialize(self):
101         self._login()
102
103     def _login(self):
104         (username, password) = self._get_login_info()
105         if username is None:
106             return
107
108         login_popup = self._download_webpage(
109             self._LOGIN_URL, None, 'Downloading login popup')
110
111         def is_logged(webpage):
112             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
113
114         # already logged in
115         if is_logged(login_popup):
116             return
117
118         login_form = self._form_hidden_inputs('login-form', login_popup)
119
120         login_form.update({
121             'email': username.encode('utf-8'),
122             'password': password.encode('utf-8'),
123         })
124
125         request = sanitized_Request(
126             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
127         request.add_header('Referer', self._ORIGIN_URL)
128         request.add_header('Origin', self._ORIGIN_URL)
129
130         response = self._download_webpage(
131             request, None, 'Logging in as %s' % username)
132
133         if not is_logged(response):
134             error = self._html_search_regex(
135                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
136                 response, 'error message', default=None)
137             if error:
138                 raise ExtractorError('Unable to login: %s' % error, expected=True)
139             raise ExtractorError('Unable to log in')
140
141     def _real_extract(self, url):
142         lecture_id = self._match_id(url)
143
144         webpage = self._download_webpage(url, lecture_id)
145
146         course_id = self._search_regex(
147             (r'data-course-id=["\'](\d+)', r'&quot;id&quot;\s*:\s*(\d+)'),
148             webpage, 'course id')
149
150         try:
151             lecture = self._download_lecture(course_id, lecture_id)
152         except ExtractorError as e:
153             # Error could possibly mean we are not enrolled in the course
154             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
155                 self._enroll_course(webpage, course_id)
156                 lecture = self._download_lecture(course_id, lecture_id)
157             else:
158                 raise
159
160         title = lecture['title']
161         description = lecture.get('description')
162
163         asset = lecture['asset']
164
165         asset_type = asset.get('assetType') or asset.get('asset_type')
166         if asset_type != 'Video':
167             raise ExtractorError(
168                 'Lecture %s is not a video' % lecture_id, expected=True)
169
170         stream_url = asset.get('streamUrl') or asset.get('stream_url')
171         if stream_url:
172             youtube_url = self._search_regex(
173                 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
174             if youtube_url:
175                 return self.url_result(youtube_url, 'Youtube')
176
177         video_id = asset['id']
178         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
179         duration = float_or_none(asset.get('data', {}).get('duration'))
180         outputs = asset.get('data', {}).get('outputs', {})
181
182         formats = []
183         for format_ in asset.get('download_urls', {}).get('Video', []):
184             video_url = format_.get('file')
185             if not video_url:
186                 continue
187             format_id = format_.get('label')
188             f = {
189                 'url': format_['file'],
190                 'height': int_or_none(format_id),
191             }
192             if format_id:
193                 # Some videos contain additional metadata (e.g.
194                 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
195                 output = outputs.get(format_id)
196                 if isinstance(output, dict):
197                     f.update({
198                         'format_id': '%sp' % (output.get('label') or format_id),
199                         'width': int_or_none(output.get('width')),
200                         'height': int_or_none(output.get('height')),
201                         'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
202                         'vcodec': output.get('video_codec'),
203                         'fps': int_or_none(output.get('frame_rate')),
204                         'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
205                         'acodec': output.get('audio_codec'),
206                         'asr': int_or_none(output.get('audio_sample_rate')),
207                         'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
208                         'filesize': int_or_none(output.get('file_size_in_bytes')),
209                     })
210                 else:
211                     f['format_id'] = '%sp' % format_id
212             formats.append(f)
213
214         self._sort_formats(formats)
215
216         return {
217             'id': video_id,
218             'title': title,
219             'description': description,
220             'thumbnail': thumbnail,
221             'duration': duration,
222             'formats': formats
223         }
224
225
226 class UdemyCourseIE(UdemyIE):
227     IE_NAME = 'udemy:course'
228     _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
229     _TESTS = []
230
231     @classmethod
232     def suitable(cls, url):
233         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
234
235     def _real_extract(self, url):
236         course_path = self._match_id(url)
237
238         webpage = self._download_webpage(url, course_path)
239
240         response = self._download_json(
241             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
242             course_path, 'Downloading course JSON')
243
244         course_id = response['id']
245         course_title = response.get('title')
246
247         self._enroll_course(webpage, course_id)
248
249         response = self._download_json(
250             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
251             course_id, 'Downloading course curriculum')
252
253         entries = []
254         chapter, chapter_number = None, None
255         for asset in response:
256             asset_type = asset.get('assetType') or asset.get('asset_type')
257             if asset_type == 'Video':
258                 asset_id = asset.get('id')
259                 if asset_id:
260                     entry = {
261                         '_type': 'url_transparent',
262                         'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
263                         'ie_key': UdemyIE.ie_key(),
264                     }
265                     if chapter_number:
266                         entry['chapter_number'] = chapter_number
267                     if chapter:
268                         entry['chapter'] = chapter
269                     entries.append(entry)
270             elif asset.get('type') == 'chapter':
271                 chapter_number = asset.get('index') or asset.get('object_index')
272                 chapter = asset.get('title')
273
274         return self.playlist_result(entries, course_id, course_title)