lynda.py 8.1 KB

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