1 from __future__ 
import unicode_literals
 
   5 from .common 
import InfoExtractor
 
  18 class LyndaBaseIE(InfoExtractor
): 
  19     _SIGNIN_URL 
= 'https://www.lynda.com/signin' 
  20     _PASSWORD_URL 
= 'https://www.lynda.com/signin/password' 
  21     _USER_URL 
= 'https://www.lynda.com/signin/user' 
  22     _ACCOUNT_CREDENTIALS_HINT 
= 'Use --username and --password options to provide lynda.com account credentials.' 
  23     _NETRC_MACHINE 
= 'lynda' 
  25     def _real_initialize(self
): 
  29     def _check_error(json_string
, key_or_keys
): 
  30         keys 
= [key_or_keys
] if isinstance(key_or_keys
, compat_str
) else key_or_keys
 
  32             error 
= json_string
.get(key
) 
  34                 raise ExtractorError('Unable to login: %s' % error
, expected
=True) 
  36     def _login_step(self
, form_html
, fallback_action_url
, extra_form_data
, note
, referrer_url
): 
  37         action_url 
= self
._search
_regex
( 
  38             r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', form_html, 
  39             'post url
', default=fallback_action_url, group='url
') 
  41         if not action_url.startswith('http
'): 
  42             action_url = compat_urlparse.urljoin(self._SIGNIN_URL, action_url) 
  44         form_data = self._hidden_inputs(form_html) 
  45         form_data.update(extra_form_data) 
  48             response = self._download_json( 
  49                 action_url, None, note, 
  50                 data=urlencode_postdata(form_data), 
  52                     'Referer
': referrer_url, 
  53                     'X
-Requested
-With
': 'XMLHttpRequest
', 
  55         except ExtractorError as e: 
  56             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500: 
  57                 response = self._parse_json(e.cause.read().decode('utf
-8'), None) 
  58                 self._check_error(response, ('email
', 'password
')) 
  61         self._check_error(response, 'ErrorMessage
') 
  63         return response, action_url 
  66         username, password = self._get_login_info() 
  70         # Step 1: download signin page 
  71         signin_page = self._download_webpage( 
  72             self._SIGNIN_URL, None, 'Downloading signin page
') 
  75         if any(re.search(p, signin_page) for p in ( 
  76                 r'isLoggedIn\s
*:\s
*true
', r'logout\
.aspx
', r'>Log out
<')): 
  79         # Step 2: submit email 
  80         signin_form = self._search_regex( 
  81             r'(?s
)(<form
[^
>]+data
-form
-name
=["\']signin["\'][^
>]*>.+?
</form
>)', 
  82             signin_page, 'signin form
') 
  83         signin_page, signin_url = self._login_step( 
  84             signin_form, self._PASSWORD_URL, {'email
': username}, 
  85             'Submitting email
', self._SIGNIN_URL) 
  87         # Step 3: submit password 
  88         password_form = signin_page['body
'] 
  90             password_form, self._USER_URL, {'email
': username, 'password
': password}, 
  91             'Submitting password
', signin_url) 
  94 class LyndaIE(LyndaBaseIE): 
  96     IE_DESC = 'lynda
.com videos
' 
  97     _VALID_URL = r'https?
://(?
:www\
.)?
(?
:lynda\
.com|educourse\
.ga
)/(?
:[^
/]+/[^
/]+/(?P
<course_id
>\d
+)|player
/embed
)/(?P
<id>\d
+)' 
  99     _TIMECODE_REGEX = r'\
[(?P
<timecode
>\d
+:\d
+:\d
+[\
.,]\d
+)\
]' 
 102         'url
': 'https
://www
.lynda
.com
/Bootstrap
-tutorials
/Using
-exercise
-files
/110885/114408-4.html
', 
 107             'title
': 'Using the exercise files
', 
 111         'url
': 'https
://www
.lynda
.com
/player
/embed
/133770?tr
=foo
=1;bar
=g
;fizz
=rt
&fs
=0', 
 112         'only_matching
': True, 
 114         'url
': 'https
://educourse
.ga
/Bootstrap
-tutorials
/Using
-exercise
-files
/110885/114408-4.html
', 
 115         'only_matching
': True, 
 118     def _raise_unavailable(self, video_id): 
 119         self.raise_login_required( 
 120             'Video 
%s is only available 
for members
' % video_id) 
 122     def _real_extract(self, url): 
 123         mobj = re.match(self._VALID_URL, url) 
 124         video_id = mobj.group('id') 
 125         course_id = mobj.group('course_id
') 
 132         video = self._download_json( 
 133             'https
://www
.lynda
.com
/ajax
/player
', video_id, 
 134             'Downloading video JSON
', fatal=False, query=query) 
 138             query['courseId
'] = course_id 
 140             play = self._download_json( 
 141                 'https
://www
.lynda
.com
/ajax
/course
/%s/%s/play
' 
 142                 % (course_id, video_id), video_id, 'Downloading play JSON
') 
 145                 self._raise_unavailable(video_id) 
 148             for formats_dict in play: 
 149                 urls = formats_dict.get('urls
') 
 150                 if not isinstance(urls, dict): 
 152                 cdn = formats_dict.get('name
') 
 153                 for format_id, format_url in urls.items(): 
 158                         'format_id
': '%s-%s' % (cdn, format_id) if cdn else format_id, 
 159                         'height
': int_or_none(format_id), 
 161             self._sort_formats(formats) 
 163             conviva = self._download_json( 
 164                 'https
://www
.lynda
.com
/ajax
/player
/conviva
', video_id, 
 165                 'Downloading conviva JSON
', query=query) 
 169                 'title
': conviva['VideoTitle
'], 
 170                 'description
': conviva.get('VideoDescription
'), 
 171                 'release_year
': int_or_none(conviva.get('ReleaseYear
')), 
 172                 'duration
': int_or_none(conviva.get('Duration
')), 
 173                 'creator
': conviva.get('Author
'), 
 177         if 'Status
' in video: 
 178             raise ExtractorError( 
 179                 'lynda returned error
: %s' % video['Message
'], expected=True) 
 181         if video.get('HasAccess
') is False: 
 182             self._raise_unavailable(video_id) 
 184         video_id = compat_str(video.get('ID
') or video_id) 
 185         duration = int_or_none(video.get('DurationInSeconds
')) 
 186         title = video['Title
'] 
 190         fmts = video.get('Formats
') 
 194                 'ext
': f.get('Extension
'), 
 195                 'width
': int_or_none(f.get('Width
')), 
 196                 'height
': int_or_none(f.get('Height
')), 
 197                 'filesize
': int_or_none(f.get('FileSize
')), 
 198                 'format_id
': compat_str(f.get('Resolution
')) if f.get('Resolution
') else None, 
 199             } for f in fmts if f.get('Url
')]) 
 201         prioritized_streams = video.get('PrioritizedStreams
') 
 202         if prioritized_streams: 
 203             for prioritized_stream_id, prioritized_stream in prioritized_streams.items(): 
 206                     'height
': int_or_none(format_id), 
 207                     'format_id
': '%s-%s' % (prioritized_stream_id, format_id), 
 208                 } for format_id, video_url in prioritized_stream.items()]) 
 210         self._check_formats(formats, video_id) 
 211         self._sort_formats(formats) 
 213         subtitles = self.extract_subtitles(video_id) 
 218             'duration
': duration, 
 219             'subtitles
': subtitles, 
 223     def _fix_subtitles(self, subs): 
 226         for pos in range(0, len(subs) - 1): 
 227             seq_current = subs[pos] 
 228             m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode
']) 
 229             if m_current is None: 
 231             seq_next = subs[pos + 1] 
 232             m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode
']) 
 235             appear_time = m_current.group('timecode
') 
 236             disappear_time = m_next.group('timecode
') 
 237             text = seq_current['Caption
'].strip() 
 240                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text) 
 244     def _get_subtitles(self, video_id): 
 245         url = 'https
://www
.lynda
.com
/ajax
/player?videoId
=%s&type=transcript
' % video_id 
 246         subs = self._download_json(url, None, False) 
 248             return {'en
': [{'ext
': 'srt
', 'data
': self._fix_subtitles(subs)}]} 
 253 class LyndaCourseIE(LyndaBaseIE): 
 254     IE_NAME = 'lynda
:course
' 
 255     IE_DESC = 'lynda
.com online courses
' 
 257     # Course link equals to welcome/introduction video link of same course 
 258     # We will recognize it as course link 
 259     _VALID_URL = r'https?
://(?
:www|m
)\
.(?
:lynda\
.com|educourse\
.ga
)/(?P
<coursepath
>[^
/]+/[^
/]+/(?P
<courseid
>\d
+))-\d\
.html
' 
 261     def _real_extract(self, url): 
 262         mobj = re.match(self._VALID_URL, url) 
 263         course_path = mobj.group('coursepath
') 
 264         course_id = mobj.group('courseid
') 
 266         item_template = 'https
://www
.lynda
.com
/%s/%%s-4.html
' % course_path 
 268         course = self._download_json( 
 269             'https
://www
.lynda
.com
/ajax
/player?courseId
=%s&type=course
' % course_id, 
 270             course_id, 'Downloading course JSON
', fatal=False) 
 273             webpage = self._download_webpage(url, course_id) 
 276                     item_template % video_id, ie=LyndaIE.ie_key(), 
 278                 for video_id in re.findall( 
 279                     r'data
-video
-id=["\'](\d+)', webpage)] 
 280             return self.playlist_result( 
 282                 self._og_search_title(webpage, fatal=False), 
 283                 self._og_search_description(webpage)) 
 285         if course.get('Status') == 'NotFound': 
 286             raise ExtractorError( 
 287                 'Course %s does not exist' % course_id, expected=True) 
 289         unaccessible_videos = 0 
 292         # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided 
 293         # by single video API anymore 
 295         for chapter in course['Chapters']: 
 296             for video in chapter.get('Videos', []): 
 297                 if video.get('HasAccess') is False: 
 298                     unaccessible_videos += 1 
 300                 video_id = video.get('ID') 
 303                         '_type': 'url_transparent', 
 304                         'url': item_template % video_id, 
 305                         'ie_key': LyndaIE.ie_key(), 
 306                         'chapter': chapter.get('Title'), 
 307                         'chapter_number': int_or_none(chapter.get('ChapterIndex')), 
 308                         'chapter_id': compat_str(chapter.get('ID')), 
 311         if unaccessible_videos > 0: 
 312             self._downloader.report_warning( 
 313                 '%s videos are only available for members (or paid members) and will not be downloaded. ' 
 314                 % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT) 
 316         course_title = course.get('Title') 
 317         course_description = course.get('Description') 
 319         return self.playlist_result(entries, course_id, course_title, course_description)