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.

235 lines
8.0 KiB

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