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