]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/lynda.py
[nrk:playlist] Relax video id regex and improve _VALID_URL
[yt-dlp.git] / youtube_dl / extractor / lynda.py
CommitLineData
a7c26e73
PH
1from __future__ import unicode_literals
2
c7f8537d 3import re
4import json
5
6from .common import InfoExtractor
1cc79574
PH
7from ..compat import (
8 compat_str,
7ee40b5d 9 compat_urllib_parse,
10 compat_urllib_request,
1cc79574
PH
11)
12from ..utils import (
16ff7ebc
S
13 ExtractorError,
14 int_or_none,
7ee40b5d 15)
c7f8537d 16
17
30cbd4e0
S
18class LyndaBaseIE(InfoExtractor):
19 _LOGIN_URL = 'https://www.lynda.com/login/login.aspx'
20 _SUCCESSFUL_LOGIN_REGEX = r'isLoggedIn: true'
21 _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
499bfcbf 22 _NETRC_MACHINE = 'lynda'
30cbd4e0
S
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,
34 'password': password,
35 'remember': 'false',
36 'stayPut': 'false'
37 }
38 request = compat_urllib_request.Request(
39 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
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 = \'(?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))
69 login_page = self._download_webpage(
70 request, None,
71 'Confirming log in and log out from another device')
72
73 if re.search(self._SUCCESSFUL_LOGIN_REGEX, login_page) is None:
74 raise ExtractorError('Unable to log in')
75
76
77class LyndaIE(LyndaBaseIE):
a7c26e73
PH
78 IE_NAME = 'lynda'
79 IE_DESC = 'lynda.com videos'
30cbd4e0 80 _VALID_URL = r'https?://www\.lynda\.com/(?:[^/]+/[^/]+/\d+|player/embed)/(?P<id>\d+)'
7ee40b5d 81 _NETRC_MACHINE = 'lynda'
82
7ee40b5d 83 _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
84
a0d64613 85 _TESTS = [{
a7c26e73 86 'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
a7c26e73 87 'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
ac260dd8 88 'info_dict': {
136db788
S
89 'id': '114408',
90 'ext': 'mp4',
a7c26e73
PH
91 'title': 'Using the exercise files',
92 'duration': 68
c7f8537d 93 }
a0d64613
S
94 }, {
95 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
96 'only_matching': True,
97 }]
7ee40b5d 98
c7f8537d 99 def _real_extract(self, url):
30cbd4e0 100 video_id = self._match_id(url)
c7f8537d 101
30cbd4e0
S
102 page = self._download_webpage(
103 'http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
104 video_id, 'Downloading video JSON')
c7f8537d 105 video_json = json.loads(page)
106
7ee40b5d 107 if 'Status' in video_json:
30cbd4e0
S
108 raise ExtractorError(
109 'lynda returned error: %s' % video_json['Message'], expected=True)
c7f8537d 110
a7c26e73 111 if video_json['HasAccess'] is False:
136db788 112 raise ExtractorError(
30cbd4e0
S
113 'Video %s is only available for members. '
114 % video_id + self._ACCOUNT_CREDENTIALS_HINT, expected=True)
c7f8537d 115
136db788 116 video_id = compat_str(video_json['ID'])
a7c26e73
PH
117 duration = video_json['DurationInSeconds']
118 title = video_json['Title']
c7f8537d 119
16ff7ebc
S
120 formats = []
121
122 fmts = video_json.get('Formats')
123 if fmts:
124 formats.extend([
125 {
126 'url': fmt['Url'],
a7c26e73
PH
127 'ext': fmt['Extension'],
128 'width': fmt['Width'],
129 'height': fmt['Height'],
130 'filesize': fmt['FileSize'],
62bcfa8c 131 'format_id': str(fmt['Resolution'])
16ff7ebc
S
132 } for fmt in fmts])
133
134 prioritized_streams = video_json.get('PrioritizedStreams')
135 if prioritized_streams:
136 formats.extend([
137 {
138 'url': video_url,
139 'width': int_or_none(format_id),
140 'format_id': format_id,
141 } for format_id, video_url in prioritized_streams['0'].items()
142 ])
c7f8537d 143
a57e8ce6 144 self._check_formats(formats, video_id)
c7f8537d 145 self._sort_formats(formats)
7ee40b5d 146
311c3938 147 subtitles = self.extract_subtitles(video_id, page)
7ee40b5d 148
c7f8537d 149 return {
150 'id': video_id,
151 'title': title,
152 'duration': duration,
62bcfa8c 153 'subtitles': subtitles,
c7f8537d 154 'formats': formats
155 }
7ee40b5d 156
311c3938
JMF
157 def _fix_subtitles(self, subs):
158 srt = ''
7594be85 159 seq_counter = 0
311c3938
JMF
160 for pos in range(0, len(subs) - 1):
161 seq_current = subs[pos]
162 m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
163 if m_current is None:
164 continue
165 seq_next = subs[pos + 1]
166 m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
167 if m_next is None:
62bcfa8c 168 continue
311c3938
JMF
169 appear_time = m_current.group('timecode')
170 disappear_time = m_next.group('timecode')
7594be85
S
171 text = seq_current['Caption'].strip()
172 if text:
173 seq_counter += 1
174 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
311c3938
JMF
175 if srt:
176 return srt
177
178 def _get_subtitles(self, video_id, webpage):
62bcfa8c 179 url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
311c3938
JMF
180 subs = self._download_json(url, None, False)
181 if subs:
182 return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
183 else:
184 return {}
c7f8537d 185
186
30cbd4e0 187class LyndaCourseIE(LyndaBaseIE):
a7c26e73
PH
188 IE_NAME = 'lynda:course'
189 IE_DESC = 'lynda.com online courses'
c7f8537d 190
191 # Course link equals to welcome/introduction video link of same course
192 # We will recognize it as course link
193 _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
194
195 def _real_extract(self, url):
196 mobj = re.match(self._VALID_URL, url)
197 course_path = mobj.group('coursepath')
198 course_id = mobj.group('courseid')
5f6a1245 199
30cbd4e0
S
200 page = self._download_webpage(
201 'http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
202 course_id, 'Downloading course JSON')
c7f8537d 203 course_json = json.loads(page)
204
a7c26e73 205 if 'Status' in course_json and course_json['Status'] == 'NotFound':
30cbd4e0
S
206 raise ExtractorError(
207 'Course %s does not exist' % course_id, expected=True)
c7f8537d 208
209 unaccessible_videos = 0
210 videos = []
211
16ff7ebc
S
212 # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
213 # by single video API anymore
214
a7c26e73
PH
215 for chapter in course_json['Chapters']:
216 for video in chapter['Videos']:
30cbd4e0 217 if video['HasAccess'] is False:
c7f8537d 218 unaccessible_videos += 1
219 continue
a7c26e73 220 videos.append(video['ID'])
c7f8537d 221
222 if unaccessible_videos > 0:
30cbd4e0
S
223 self._downloader.report_warning(
224 '%s videos are only available for members (or paid members) and will not be downloaded. '
225 % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
c7f8537d 226
a7c26e73 227 entries = [
30cbd4e0
S
228 self.url_result(
229 'http://www.lynda.com/%s/%s-4.html' % (course_path, video_id),
230 'Lynda')
a7c26e73 231 for video_id in videos]
c7f8537d 232
a7c26e73 233 course_title = course_json['Title']
c7f8537d 234
5f6a1245 235 return self.playlist_result(entries, course_id, course_title)