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