365d8b4bfe19a6d89965a68957ea4901d7722037
[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_urllib_parse,
8     compat_urllib_request,
9 )
10 from ..utils import (
11     ExtractorError,
12 )
13
14
15 class UdemyIE(InfoExtractor):
16     IE_NAME = 'udemy'
17     _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
18     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
19     _ORIGIN_URL = 'https://www.udemy.com'
20     _NETRC_MACHINE = 'udemy'
21
22     _TESTS = [{
23         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
24         'md5': '98eda5b657e752cf945d8445e261b5c5',
25         'info_dict': {
26             'id': '160614',
27             'ext': 'mp4',
28             'title': 'Introduction and Installation',
29             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
30             'duration': 579.29,
31         },
32         'skip': 'Requires udemy account credentials',
33     }]
34
35     def _handle_error(self, response):
36         if not isinstance(response, dict):
37             return
38         error = response.get('error')
39         if error:
40             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
41             error_data = error.get('data')
42             if error_data:
43                 error_str += ' - %s' % error_data.get('formErrors')
44             raise ExtractorError(error_str, expected=True)
45
46     def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
47         headers = {
48             'X-Udemy-Snail-Case': 'true',
49             'X-Requested-With': 'XMLHttpRequest',
50         }
51         for cookie in self._downloader.cookiejar:
52             if cookie.name == 'client_id':
53                 headers['X-Udemy-Client-Id'] = cookie.value
54             elif cookie.name == 'access_token':
55                 headers['X-Udemy-Bearer-Token'] = cookie.value
56
57         if isinstance(url_or_request, compat_urllib_request.Request):
58             for header, value in headers.items():
59                 url_or_request.add_header(header, value)
60         else:
61             url_or_request = compat_urllib_request.Request(url_or_request, headers=headers)
62
63         response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
64         self._handle_error(response)
65         return response
66
67     def _real_initialize(self):
68         self._login()
69
70     def _login(self):
71         (username, password) = self._get_login_info()
72         if username is None:
73             self.raise_login_required('Udemy account is required')
74
75         login_popup = self._download_webpage(
76             self._LOGIN_URL, None, 'Downloading login popup')
77
78         def is_logged(webpage):
79             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
80
81         # already logged in
82         if is_logged(login_popup):
83             return
84
85         login_form = self._form_hidden_inputs('login-form', login_popup)
86
87         login_form.update({
88             'email': username.encode('utf-8'),
89             'password': password.encode('utf-8'),
90         })
91
92         request = compat_urllib_request.Request(
93             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
94         request.add_header('Referer', self._ORIGIN_URL)
95         request.add_header('Origin', self._ORIGIN_URL)
96
97         response = self._download_webpage(
98             request, None, 'Logging in as %s' % username)
99
100         if not is_logged(response):
101             error = self._html_search_regex(
102                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
103                 response, 'error message', default=None)
104             if error:
105                 raise ExtractorError('Unable to login: %s' % error, expected=True)
106             raise ExtractorError('Unable to log in')
107
108     def _real_extract(self, url):
109         lecture_id = self._match_id(url)
110
111         lecture = self._download_json(
112             'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
113             lecture_id, 'Downloading lecture JSON')
114
115         asset_type = lecture.get('assetType') or lecture.get('asset_type')
116         if asset_type != 'Video':
117             raise ExtractorError(
118                 'Lecture %s is not a video' % lecture_id, expected=True)
119
120         asset = lecture['asset']
121
122         stream_url = asset.get('streamUrl') or asset.get('stream_url')
123         mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
124         if mobj:
125             return self.url_result(mobj.group(1), 'Youtube')
126
127         video_id = asset['id']
128         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
129         duration = asset['data']['duration']
130
131         download_url = asset.get('downloadUrl') or asset.get('download_url')
132
133         video = download_url.get('Video') or download_url.get('video')
134         video_480p = download_url.get('Video480p') or download_url.get('video_480p')
135
136         formats = [
137             {
138                 'url': video_480p[0],
139                 'format_id': '360p',
140             },
141             {
142                 'url': video[0],
143                 'format_id': '720p',
144             },
145         ]
146
147         title = lecture['title']
148         description = lecture['description']
149
150         return {
151             'id': video_id,
152             'title': title,
153             'description': description,
154             'thumbnail': thumbnail,
155             'duration': duration,
156             'formats': formats
157         }
158
159
160 class UdemyCourseIE(UdemyIE):
161     IE_NAME = 'udemy:course'
162     _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
163     _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
164     _ALREADY_ENROLLED = '>You are already taking this course.<'
165     _TESTS = []
166
167     @classmethod
168     def suitable(cls, url):
169         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
170
171     def _real_extract(self, url):
172         mobj = re.match(self._VALID_URL, url)
173         course_path = mobj.group('coursepath')
174
175         response = self._download_json(
176             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
177             course_path, 'Downloading course JSON')
178
179         course_id = int(response['id'])
180         course_title = response['title']
181
182         webpage = self._download_webpage(
183             'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
184             course_id, 'Enrolling in the course')
185
186         if self._SUCCESSFULLY_ENROLLED in webpage:
187             self.to_screen('%s: Successfully enrolled in' % course_id)
188         elif self._ALREADY_ENROLLED in webpage:
189             self.to_screen('%s: Already enrolled in' % course_id)
190
191         response = self._download_json(
192             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
193             course_id, 'Downloading course curriculum')
194
195         entries = [
196             self.url_result(
197                 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
198             for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
199         ]
200
201         return self.playlist_result(entries, course_id, course_title)