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.

250 lines
9.0 KiB

9 years ago
11 years ago
10 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_HTTPError,
  6. compat_str,
  7. compat_urlparse,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. int_or_none,
  12. urlencode_postdata,
  13. )
  14. class LyndaBaseIE(InfoExtractor):
  15. _SIGNIN_URL = 'https://www.lynda.com/signin'
  16. _PASSWORD_URL = 'https://www.lynda.com/signin/password'
  17. _USER_URL = 'https://www.lynda.com/signin/user'
  18. _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
  19. _NETRC_MACHINE = 'lynda'
  20. def _real_initialize(self):
  21. self._login()
  22. @staticmethod
  23. def _check_error(json_string, key_or_keys):
  24. keys = [key_or_keys] if isinstance(key_or_keys, compat_str) else key_or_keys
  25. for key in keys:
  26. error = json_string.get(key)
  27. if error:
  28. raise ExtractorError('Unable to login: %s' % error, expected=True)
  29. def _login_step(self, form_html, fallback_action_url, extra_form_data, note, referrer_url):
  30. action_url = self._search_regex(
  31. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', form_html,
  32. 'post url', default=fallback_action_url, group='url')
  33. if not action_url.startswith('http'):
  34. action_url = compat_urlparse.urljoin(self._SIGNIN_URL, action_url)
  35. form_data = self._hidden_inputs(form_html)
  36. form_data.update(extra_form_data)
  37. try:
  38. response = self._download_json(
  39. action_url, None, note,
  40. data=urlencode_postdata(form_data),
  41. headers={
  42. 'Referer': referrer_url,
  43. 'X-Requested-With': 'XMLHttpRequest',
  44. })
  45. except ExtractorError as e:
  46. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  47. response = self._parse_json(e.cause.read().decode('utf-8'), None)
  48. self._check_error(response, ('email', 'password'))
  49. raise
  50. self._check_error(response, 'ErrorMessage')
  51. return response, action_url
  52. def _login(self):
  53. username, password = self._get_login_info()
  54. if username is None:
  55. return
  56. # Step 1: download signin page
  57. signin_page = self._download_webpage(
  58. self._SIGNIN_URL, None, 'Downloading signin page')
  59. # Already logged in
  60. if any(re.search(p, signin_page) for p in (
  61. 'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
  62. return
  63. # Step 2: submit email
  64. signin_form = self._search_regex(
  65. r'(?s)(<form[^>]+data-form-name=["\']signin["\'][^>]*>.+?</form>)',
  66. signin_page, 'signin form')
  67. signin_page, signin_url = self._login_step(
  68. signin_form, self._PASSWORD_URL, {'email': username},
  69. 'Submitting email', self._SIGNIN_URL)
  70. # Step 3: submit password
  71. password_form = signin_page['body']
  72. self._login_step(
  73. password_form, self._USER_URL, {'email': username, 'password': password},
  74. 'Submitting password', signin_url)
  75. class LyndaIE(LyndaBaseIE):
  76. IE_NAME = 'lynda'
  77. IE_DESC = 'lynda.com videos'
  78. _VALID_URL = r'https?://www\.lynda\.com/(?:[^/]+/[^/]+/\d+|player/embed)/(?P<id>\d+)'
  79. _NETRC_MACHINE = 'lynda'
  80. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  81. _TESTS = [{
  82. 'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  83. 'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
  84. 'info_dict': {
  85. 'id': '114408',
  86. 'ext': 'mp4',
  87. 'title': 'Using the exercise files',
  88. 'duration': 68
  89. }
  90. }, {
  91. 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
  92. 'only_matching': True,
  93. }]
  94. def _real_extract(self, url):
  95. video_id = self._match_id(url)
  96. video = self._download_json(
  97. 'http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
  98. video_id, 'Downloading video JSON')
  99. if 'Status' in video:
  100. raise ExtractorError(
  101. 'lynda returned error: %s' % video['Message'], expected=True)
  102. if video.get('HasAccess') is False:
  103. self.raise_login_required('Video %s is only available for members' % video_id)
  104. video_id = compat_str(video.get('ID') or video_id)
  105. duration = int_or_none(video.get('DurationInSeconds'))
  106. title = video['Title']
  107. formats = []
  108. fmts = video.get('Formats')
  109. if fmts:
  110. formats.extend([{
  111. 'url': f['Url'],
  112. 'ext': f.get('Extension'),
  113. 'width': int_or_none(f.get('Width')),
  114. 'height': int_or_none(f.get('Height')),
  115. 'filesize': int_or_none(f.get('FileSize')),
  116. 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
  117. } for f in fmts if f.get('Url')])
  118. prioritized_streams = video.get('PrioritizedStreams')
  119. if prioritized_streams:
  120. for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
  121. formats.extend([{
  122. 'url': video_url,
  123. 'width': int_or_none(format_id),
  124. 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
  125. } for format_id, video_url in prioritized_stream.items()])
  126. self._check_formats(formats, video_id)
  127. self._sort_formats(formats)
  128. subtitles = self.extract_subtitles(video_id)
  129. return {
  130. 'id': video_id,
  131. 'title': title,
  132. 'duration': duration,
  133. 'subtitles': subtitles,
  134. 'formats': formats
  135. }
  136. def _fix_subtitles(self, subs):
  137. srt = ''
  138. seq_counter = 0
  139. for pos in range(0, len(subs) - 1):
  140. seq_current = subs[pos]
  141. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  142. if m_current is None:
  143. continue
  144. seq_next = subs[pos + 1]
  145. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  146. if m_next is None:
  147. continue
  148. appear_time = m_current.group('timecode')
  149. disappear_time = m_next.group('timecode')
  150. text = seq_current['Caption'].strip()
  151. if text:
  152. seq_counter += 1
  153. srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
  154. if srt:
  155. return srt
  156. def _get_subtitles(self, video_id):
  157. url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
  158. subs = self._download_json(url, None, False)
  159. if subs:
  160. return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
  161. else:
  162. return {}
  163. class LyndaCourseIE(LyndaBaseIE):
  164. IE_NAME = 'lynda:course'
  165. IE_DESC = 'lynda.com online courses'
  166. # Course link equals to welcome/introduction video link of same course
  167. # We will recognize it as course link
  168. _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
  169. def _real_extract(self, url):
  170. mobj = re.match(self._VALID_URL, url)
  171. course_path = mobj.group('coursepath')
  172. course_id = mobj.group('courseid')
  173. course = self._download_json(
  174. 'http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
  175. course_id, 'Downloading course JSON')
  176. if course.get('Status') == 'NotFound':
  177. raise ExtractorError(
  178. 'Course %s does not exist' % course_id, expected=True)
  179. unaccessible_videos = 0
  180. entries = []
  181. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  182. # by single video API anymore
  183. for chapter in course['Chapters']:
  184. for video in chapter.get('Videos', []):
  185. if video.get('HasAccess') is False:
  186. unaccessible_videos += 1
  187. continue
  188. video_id = video.get('ID')
  189. if video_id:
  190. entries.append({
  191. '_type': 'url_transparent',
  192. 'url': 'http://www.lynda.com/%s/%s-4.html' % (course_path, video_id),
  193. 'ie_key': LyndaIE.ie_key(),
  194. 'chapter': chapter.get('Title'),
  195. 'chapter_number': int_or_none(chapter.get('ChapterIndex')),
  196. 'chapter_id': compat_str(chapter.get('ID')),
  197. })
  198. if unaccessible_videos > 0:
  199. self._downloader.report_warning(
  200. '%s videos are only available for members (or paid members) and will not be downloaded. '
  201. % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
  202. course_title = course.get('Title')
  203. course_description = course.get('Description')
  204. return self.playlist_result(entries, course_id, course_title, course_description)