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