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