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