Merge branch 'shahid' of https://github.com/remitamine/youtube-dl into remitamine...
[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             raise ExtractorError(
74                 'Udemy account is required, use --username and --password options to provide account credentials.',
75                 expected=True)
76
77         login_popup = self._download_webpage(
78             self._LOGIN_URL, None, 'Downloading login popup')
79
80         def is_logged(webpage):
81             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
82
83         # already logged in
84         if is_logged(login_popup):
85             return
86
87         login_form = self._form_hidden_inputs('login-form', login_popup)
88
89         login_form.update({
90             'email': username.encode('utf-8'),
91             'password': password.encode('utf-8'),
92         })
93
94         request = compat_urllib_request.Request(
95             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
96         request.add_header('Referer', self._ORIGIN_URL)
97         request.add_header('Origin', self._ORIGIN_URL)
98
99         response = self._download_webpage(
100             request, None, 'Logging in as %s' % username)
101
102         if not is_logged(response):
103             error = self._html_search_regex(
104                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
105                 response, 'error message', default=None)
106             if error:
107                 raise ExtractorError('Unable to login: %s' % error, expected=True)
108             raise ExtractorError('Unable to log in')
109
110     def _real_extract(self, url):
111         lecture_id = self._match_id(url)
112
113         lecture = self._download_json(
114             'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
115             lecture_id, 'Downloading lecture JSON')
116
117         asset_type = lecture.get('assetType') or lecture.get('asset_type')
118         if asset_type != 'Video':
119             raise ExtractorError(
120                 'Lecture %s is not a video' % lecture_id, expected=True)
121
122         asset = lecture['asset']
123
124         stream_url = asset.get('streamUrl') or asset.get('stream_url')
125         mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
126         if mobj:
127             return self.url_result(mobj.group(1), 'Youtube')
128
129         video_id = asset['id']
130         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
131         duration = asset['data']['duration']
132
133         download_url = asset.get('downloadUrl') or asset.get('download_url')
134
135         video = download_url.get('Video') or download_url.get('video')
136         video_480p = download_url.get('Video480p') or download_url.get('video_480p')
137
138         formats = [
139             {
140                 'url': video_480p[0],
141                 'format_id': '360p',
142             },
143             {
144                 'url': video[0],
145                 'format_id': '720p',
146             },
147         ]
148
149         title = lecture['title']
150         description = lecture['description']
151
152         return {
153             'id': video_id,
154             'title': title,
155             'description': description,
156             'thumbnail': thumbnail,
157             'duration': duration,
158             'formats': formats
159         }
160
161
162 class UdemyCourseIE(UdemyIE):
163     IE_NAME = 'udemy:course'
164     _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
165     _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
166     _ALREADY_ENROLLED = '>You are already taking this course.<'
167     _TESTS = []
168
169     @classmethod
170     def suitable(cls, url):
171         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
172
173     def _real_extract(self, url):
174         mobj = re.match(self._VALID_URL, url)
175         course_path = mobj.group('coursepath')
176
177         response = self._download_json(
178             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
179             course_path, 'Downloading course JSON')
180
181         course_id = int(response['id'])
182         course_title = response['title']
183
184         webpage = self._download_webpage(
185             'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
186             course_id, 'Enrolling in the course')
187
188         if self._SUCCESSFULLY_ENROLLED in webpage:
189             self.to_screen('%s: Successfully enrolled in' % course_id)
190         elif self._ALREADY_ENROLLED in webpage:
191             self.to_screen('%s: Already enrolled in' % course_id)
192
193         response = self._download_json(
194             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
195             course_id, 'Downloading course curriculum')
196
197         entries = [
198             self.url_result(
199                 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
200             for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
201         ]
202
203         return self.playlist_result(entries, course_id, course_title)