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