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.

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