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.

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