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