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.

319 lines
12 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. r'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|educourse\.ga)/(?:[^/]+/[^/]+/(?P<course_id>\d+)|player/embed)/(?P<id>\d+)'
  79. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  80. _TESTS = [{
  81. 'url': 'https://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. 'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  94. 'only_matching': True,
  95. }]
  96. def _raise_unavailable(self, video_id):
  97. self.raise_login_required(
  98. 'Video %s is only available for members' % video_id)
  99. def _real_extract(self, url):
  100. mobj = re.match(self._VALID_URL, url)
  101. video_id = mobj.group('id')
  102. course_id = mobj.group('course_id')
  103. query = {
  104. 'videoId': video_id,
  105. 'type': 'video',
  106. }
  107. video = self._download_json(
  108. 'https://www.lynda.com/ajax/player', video_id,
  109. 'Downloading video JSON', fatal=False, query=query)
  110. # Fallback scenario
  111. if not video:
  112. query['courseId'] = course_id
  113. play = self._download_json(
  114. 'https://www.lynda.com/ajax/course/%s/%s/play'
  115. % (course_id, video_id), video_id, 'Downloading play JSON')
  116. if not play:
  117. self._raise_unavailable(video_id)
  118. formats = []
  119. for formats_dict in play:
  120. urls = formats_dict.get('urls')
  121. if not isinstance(urls, dict):
  122. continue
  123. cdn = formats_dict.get('name')
  124. for format_id, format_url in urls.items():
  125. if not format_url:
  126. continue
  127. formats.append({
  128. 'url': format_url,
  129. 'format_id': '%s-%s' % (cdn, format_id) if cdn else format_id,
  130. 'height': int_or_none(format_id),
  131. })
  132. self._sort_formats(formats)
  133. conviva = self._download_json(
  134. 'https://www.lynda.com/ajax/player/conviva', video_id,
  135. 'Downloading conviva JSON', query=query)
  136. return {
  137. 'id': video_id,
  138. 'title': conviva['VideoTitle'],
  139. 'description': conviva.get('VideoDescription'),
  140. 'release_year': int_or_none(conviva.get('ReleaseYear')),
  141. 'duration': int_or_none(conviva.get('Duration')),
  142. 'creator': conviva.get('Author'),
  143. 'formats': formats,
  144. }
  145. if 'Status' in video:
  146. raise ExtractorError(
  147. 'lynda returned error: %s' % video['Message'], expected=True)
  148. if video.get('HasAccess') is False:
  149. self._raise_unavailable(video_id)
  150. video_id = compat_str(video.get('ID') or video_id)
  151. duration = int_or_none(video.get('DurationInSeconds'))
  152. title = video['Title']
  153. formats = []
  154. fmts = video.get('Formats')
  155. if fmts:
  156. formats.extend([{
  157. 'url': f['Url'],
  158. 'ext': f.get('Extension'),
  159. 'width': int_or_none(f.get('Width')),
  160. 'height': int_or_none(f.get('Height')),
  161. 'filesize': int_or_none(f.get('FileSize')),
  162. 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
  163. } for f in fmts if f.get('Url')])
  164. prioritized_streams = video.get('PrioritizedStreams')
  165. if prioritized_streams:
  166. for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
  167. formats.extend([{
  168. 'url': video_url,
  169. 'height': int_or_none(format_id),
  170. 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
  171. } for format_id, video_url in prioritized_stream.items()])
  172. self._check_formats(formats, video_id)
  173. self._sort_formats(formats)
  174. subtitles = self.extract_subtitles(video_id)
  175. return {
  176. 'id': video_id,
  177. 'title': title,
  178. 'duration': duration,
  179. 'subtitles': subtitles,
  180. 'formats': formats
  181. }
  182. def _fix_subtitles(self, subs):
  183. srt = ''
  184. seq_counter = 0
  185. for pos in range(0, len(subs) - 1):
  186. seq_current = subs[pos]
  187. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  188. if m_current is None:
  189. continue
  190. seq_next = subs[pos + 1]
  191. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  192. if m_next is None:
  193. continue
  194. appear_time = m_current.group('timecode')
  195. disappear_time = m_next.group('timecode')
  196. text = seq_current['Caption'].strip()
  197. if text:
  198. seq_counter += 1
  199. srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
  200. if srt:
  201. return srt
  202. def _get_subtitles(self, video_id):
  203. url = 'https://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
  204. subs = self._download_json(url, None, False)
  205. if subs:
  206. return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
  207. else:
  208. return {}
  209. class LyndaCourseIE(LyndaBaseIE):
  210. IE_NAME = 'lynda:course'
  211. IE_DESC = 'lynda.com online courses'
  212. # Course link equals to welcome/introduction video link of same course
  213. # We will recognize it as course link
  214. _VALID_URL = r'https?://(?:www|m)\.(?:lynda\.com|educourse\.ga)/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
  215. def _real_extract(self, url):
  216. mobj = re.match(self._VALID_URL, url)
  217. course_path = mobj.group('coursepath')
  218. course_id = mobj.group('courseid')
  219. item_template = 'https://www.lynda.com/%s/%%s-4.html' % course_path
  220. course = self._download_json(
  221. 'https://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
  222. course_id, 'Downloading course JSON', fatal=False)
  223. if not course:
  224. webpage = self._download_webpage(url, course_id)
  225. entries = [
  226. self.url_result(
  227. item_template % video_id, ie=LyndaIE.ie_key(),
  228. video_id=video_id)
  229. for video_id in re.findall(
  230. r'data-video-id=["\'](\d+)', webpage)]
  231. return self.playlist_result(
  232. entries, course_id,
  233. self._og_search_title(webpage, fatal=False),
  234. self._og_search_description(webpage))
  235. if course.get('Status') == 'NotFound':
  236. raise ExtractorError(
  237. 'Course %s does not exist' % course_id, expected=True)
  238. unaccessible_videos = 0
  239. entries = []
  240. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  241. # by single video API anymore
  242. for chapter in course['Chapters']:
  243. for video in chapter.get('Videos', []):
  244. if video.get('HasAccess') is False:
  245. unaccessible_videos += 1
  246. continue
  247. video_id = video.get('ID')
  248. if video_id:
  249. entries.append({
  250. '_type': 'url_transparent',
  251. 'url': item_template % video_id,
  252. 'ie_key': LyndaIE.ie_key(),
  253. 'chapter': chapter.get('Title'),
  254. 'chapter_number': int_or_none(chapter.get('ChapterIndex')),
  255. 'chapter_id': compat_str(chapter.get('ID')),
  256. })
  257. if unaccessible_videos > 0:
  258. self._downloader.report_warning(
  259. '%s videos are only available for members (or paid members) and will not be downloaded. '
  260. % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
  261. course_title = course.get('Title')
  262. course_description = course.get('Description')
  263. return self.playlist_result(entries, course_id, course_title, course_description)