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