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