]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/lynda.py
Update changelog.
[youtubedl] / youtube_dl / extractor / lynda.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .subtitles import SubtitlesInfoExtractor
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_str,
10 compat_urllib_parse,
11 compat_urllib_request,
12 )
13 from ..utils import (
14 ExtractorError,
15 int_or_none,
16 )
17
18
19 class LyndaIE(SubtitlesInfoExtractor):
20 IE_NAME = 'lynda'
21 IE_DESC = 'lynda.com videos'
22 _VALID_URL = r'https?://www\.lynda\.com/[^/]+/[^/]+/\d+/(\d+)-\d\.html'
23 _LOGIN_URL = 'https://www.lynda.com/login/login.aspx'
24 _NETRC_MACHINE = 'lynda'
25
26 _SUCCESSFUL_LOGIN_REGEX = r'isLoggedIn: true'
27 _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
28
29 ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
30
31 _TEST = {
32 'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
33 'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
34 'info_dict': {
35 'id': '114408',
36 'ext': 'mp4',
37 'title': 'Using the exercise files',
38 'duration': 68
39 }
40 }
41
42 def _real_initialize(self):
43 self._login()
44
45 def _real_extract(self, url):
46 mobj = re.match(self._VALID_URL, url)
47 video_id = mobj.group(1)
48
49 page = self._download_webpage('http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id, video_id,
50 'Downloading video JSON')
51 video_json = json.loads(page)
52
53 if 'Status' in video_json:
54 raise ExtractorError('lynda returned error: %s' % video_json['Message'], expected=True)
55
56 if video_json['HasAccess'] is False:
57 raise ExtractorError(
58 'Video %s is only available for members. ' % video_id + self.ACCOUNT_CREDENTIALS_HINT, expected=True)
59
60 video_id = compat_str(video_json['ID'])
61 duration = video_json['DurationInSeconds']
62 title = video_json['Title']
63
64 formats = []
65
66 fmts = video_json.get('Formats')
67 if fmts:
68 formats.extend([
69 {
70 'url': fmt['Url'],
71 'ext': fmt['Extension'],
72 'width': fmt['Width'],
73 'height': fmt['Height'],
74 'filesize': fmt['FileSize'],
75 'format_id': str(fmt['Resolution'])
76 } for fmt in fmts])
77
78 prioritized_streams = video_json.get('PrioritizedStreams')
79 if prioritized_streams:
80 formats.extend([
81 {
82 'url': video_url,
83 'width': int_or_none(format_id),
84 'format_id': format_id,
85 } for format_id, video_url in prioritized_streams['0'].items()
86 ])
87
88 self._check_formats(formats, video_id)
89 self._sort_formats(formats)
90
91 if self._downloader.params.get('listsubtitles', False):
92 self._list_available_subtitles(video_id, page)
93 return
94
95 subtitles = self._fix_subtitles(self.extract_subtitles(video_id, page))
96
97 return {
98 'id': video_id,
99 'title': title,
100 'duration': duration,
101 'subtitles': subtitles,
102 'formats': formats
103 }
104
105 def _login(self):
106 (username, password) = self._get_login_info()
107 if username is None:
108 return
109
110 login_form = {
111 'username': username,
112 'password': password,
113 'remember': 'false',
114 'stayPut': 'false'
115 }
116 request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
117 login_page = self._download_webpage(request, None, 'Logging in as %s' % username)
118
119 # Not (yet) logged in
120 m = re.search(r'loginResultJson = \'(?P<json>[^\']+)\';', login_page)
121 if m is not None:
122 response = m.group('json')
123 response_json = json.loads(response)
124 state = response_json['state']
125
126 if state == 'notlogged':
127 raise ExtractorError('Unable to login, incorrect username and/or password', expected=True)
128
129 # This is when we get popup:
130 # > You're already logged in to lynda.com on two devices.
131 # > If you log in here, we'll log you out of another device.
132 # So, we need to confirm this.
133 if state == 'conflicted':
134 confirm_form = {
135 'username': '',
136 'password': '',
137 'resolve': 'true',
138 'remember': 'false',
139 'stayPut': 'false',
140 }
141 request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(confirm_form))
142 login_page = self._download_webpage(request, None, 'Confirming log in and log out from another device')
143
144 if re.search(self._SUCCESSFUL_LOGIN_REGEX, login_page) is None:
145 raise ExtractorError('Unable to log in')
146
147 def _fix_subtitles(self, subtitles):
148 if subtitles is None:
149 return subtitles # subtitles not requested
150
151 fixed_subtitles = {}
152 for k, v in subtitles.items():
153 subs = json.loads(v)
154 if len(subs) == 0:
155 continue
156 srt = ''
157 for pos in range(0, len(subs) - 1):
158 seq_current = subs[pos]
159 m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
160 if m_current is None:
161 continue
162 seq_next = subs[pos + 1]
163 m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
164 if m_next is None:
165 continue
166 appear_time = m_current.group('timecode')
167 disappear_time = m_next.group('timecode')
168 text = seq_current['Caption']
169 srt += '%s\r\n%s --> %s\r\n%s' % (str(pos), appear_time, disappear_time, text)
170 if srt:
171 fixed_subtitles[k] = srt
172 return fixed_subtitles
173
174 def _get_available_subtitles(self, video_id, webpage):
175 url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
176 sub = self._download_webpage(url, None, False)
177 sub_json = json.loads(sub)
178 return {'en': url} if len(sub_json) > 0 else {}
179
180
181 class LyndaCourseIE(InfoExtractor):
182 IE_NAME = 'lynda:course'
183 IE_DESC = 'lynda.com online courses'
184
185 # Course link equals to welcome/introduction video link of same course
186 # We will recognize it as course link
187 _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
188
189 def _real_extract(self, url):
190 mobj = re.match(self._VALID_URL, url)
191 course_path = mobj.group('coursepath')
192 course_id = mobj.group('courseid')
193
194 page = self._download_webpage('http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
195 course_id, 'Downloading course JSON')
196 course_json = json.loads(page)
197
198 if 'Status' in course_json and course_json['Status'] == 'NotFound':
199 raise ExtractorError('Course %s does not exist' % course_id, expected=True)
200
201 unaccessible_videos = 0
202 videos = []
203 (username, _) = self._get_login_info()
204
205 # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
206 # by single video API anymore
207
208 for chapter in course_json['Chapters']:
209 for video in chapter['Videos']:
210 if username is None and video['HasAccess'] is False:
211 unaccessible_videos += 1
212 continue
213 videos.append(video['ID'])
214
215 if unaccessible_videos > 0:
216 self._downloader.report_warning('%s videos are only available for members and will not be downloaded. '
217 % unaccessible_videos + LyndaIE.ACCOUNT_CREDENTIALS_HINT)
218
219 entries = [
220 self.url_result('http://www.lynda.com/%s/%s-4.html' %
221 (course_path, video_id),
222 'Lynda')
223 for video_id in videos]
224
225 course_title = course_json['Title']
226
227 return self.playlist_result(entries, course_id, course_title)