You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
7.6 KiB

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