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.

249 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. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  80. _TESTS = [{
  81. 'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  82. # md5 is unstable
  83. 'info_dict': {
  84. 'id': '114408',
  85. 'ext': 'mp4',
  86. 'title': 'Using the exercise files',
  87. 'duration': 68
  88. }
  89. }, {
  90. 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
  91. 'only_matching': True,
  92. }]
  93. def _real_extract(self, url):
  94. video_id = self._match_id(url)
  95. video = self._download_json(
  96. 'http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
  97. video_id, 'Downloading video JSON')
  98. if 'Status' in video:
  99. raise ExtractorError(
  100. 'lynda returned error: %s' % video['Message'], expected=True)
  101. if video.get('HasAccess') is False:
  102. self.raise_login_required('Video %s is only available for members' % video_id)
  103. video_id = compat_str(video.get('ID') or video_id)
  104. duration = int_or_none(video.get('DurationInSeconds'))
  105. title = video['Title']
  106. formats = []
  107. fmts = video.get('Formats')
  108. if fmts:
  109. formats.extend([{
  110. 'url': f['Url'],
  111. 'ext': f.get('Extension'),
  112. 'width': int_or_none(f.get('Width')),
  113. 'height': int_or_none(f.get('Height')),
  114. 'filesize': int_or_none(f.get('FileSize')),
  115. 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
  116. } for f in fmts if f.get('Url')])
  117. prioritized_streams = video.get('PrioritizedStreams')
  118. if prioritized_streams:
  119. for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
  120. formats.extend([{
  121. 'url': video_url,
  122. 'width': int_or_none(format_id),
  123. 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
  124. } for format_id, video_url in prioritized_stream.items()])
  125. self._check_formats(formats, video_id)
  126. self._sort_formats(formats)
  127. subtitles = self.extract_subtitles(video_id)
  128. return {
  129. 'id': video_id,
  130. 'title': title,
  131. 'duration': duration,
  132. 'subtitles': subtitles,
  133. 'formats': formats
  134. }
  135. def _fix_subtitles(self, subs):
  136. srt = ''
  137. seq_counter = 0
  138. for pos in range(0, len(subs) - 1):
  139. seq_current = subs[pos]
  140. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  141. if m_current is None:
  142. continue
  143. seq_next = subs[pos + 1]
  144. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  145. if m_next is None:
  146. continue
  147. appear_time = m_current.group('timecode')
  148. disappear_time = m_next.group('timecode')
  149. text = seq_current['Caption'].strip()
  150. if text:
  151. seq_counter += 1
  152. srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
  153. if srt:
  154. return srt
  155. def _get_subtitles(self, video_id):
  156. url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
  157. subs = self._download_json(url, None, False)
  158. if subs:
  159. return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
  160. else:
  161. return {}
  162. class LyndaCourseIE(LyndaBaseIE):
  163. IE_NAME = 'lynda:course'
  164. IE_DESC = 'lynda.com online courses'
  165. # Course link equals to welcome/introduction video link of same course
  166. # We will recognize it as course link
  167. _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
  168. def _real_extract(self, url):
  169. mobj = re.match(self._VALID_URL, url)
  170. course_path = mobj.group('coursepath')
  171. course_id = mobj.group('courseid')
  172. course = self._download_json(
  173. 'http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
  174. course_id, 'Downloading course JSON')
  175. if course.get('Status') == 'NotFound':
  176. raise ExtractorError(
  177. 'Course %s does not exist' % course_id, expected=True)
  178. unaccessible_videos = 0
  179. entries = []
  180. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  181. # by single video API anymore
  182. for chapter in course['Chapters']:
  183. for video in chapter.get('Videos', []):
  184. if video.get('HasAccess') is False:
  185. unaccessible_videos += 1
  186. continue
  187. video_id = video.get('ID')
  188. if video_id:
  189. entries.append({
  190. '_type': 'url_transparent',
  191. 'url': 'http://www.lynda.com/%s/%s-4.html' % (course_path, video_id),
  192. 'ie_key': LyndaIE.ie_key(),
  193. 'chapter': chapter.get('Title'),
  194. 'chapter_number': int_or_none(chapter.get('ChapterIndex')),
  195. 'chapter_id': compat_str(chapter.get('ID')),
  196. })
  197. if unaccessible_videos > 0:
  198. self._downloader.report_warning(
  199. '%s videos are only available for members (or paid members) and will not be downloaded. '
  200. % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
  201. course_title = course.get('Title')
  202. course_description = course.get('Description')
  203. return self.playlist_result(entries, course_id, course_title, course_description)