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.

332 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_str,
  6. compat_urlparse,
  7. )
  8. from ..utils import (
  9. ExtractorError,
  10. int_or_none,
  11. urlencode_postdata,
  12. )
  13. class LyndaBaseIE(InfoExtractor):
  14. _SIGNIN_URL = 'https://www.lynda.com/signin/lynda'
  15. _PASSWORD_URL = 'https://www.lynda.com/signin/password'
  16. _USER_URL = 'https://www.lynda.com/signin/user'
  17. _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
  18. _NETRC_MACHINE = 'lynda'
  19. def _real_initialize(self):
  20. self._login()
  21. @staticmethod
  22. def _check_error(json_string, key_or_keys):
  23. keys = [key_or_keys] if isinstance(key_or_keys, compat_str) else key_or_keys
  24. for key in keys:
  25. error = json_string.get(key)
  26. if error:
  27. raise ExtractorError('Unable to login: %s' % error, expected=True)
  28. def _login_step(self, form_html, fallback_action_url, extra_form_data, note, referrer_url):
  29. action_url = self._search_regex(
  30. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', form_html,
  31. 'post url', default=fallback_action_url, group='url')
  32. if not action_url.startswith('http'):
  33. action_url = compat_urlparse.urljoin(self._SIGNIN_URL, action_url)
  34. form_data = self._hidden_inputs(form_html)
  35. form_data.update(extra_form_data)
  36. response = self._download_json(
  37. action_url, None, note,
  38. data=urlencode_postdata(form_data),
  39. headers={
  40. 'Referer': referrer_url,
  41. 'X-Requested-With': 'XMLHttpRequest',
  42. }, expected_status=(418, 500, ))
  43. self._check_error(response, ('email', 'password', 'ErrorMessage'))
  44. return response, action_url
  45. def _login(self):
  46. username, password = self._get_login_info()
  47. if username is None:
  48. return
  49. # Step 1: download signin page
  50. signin_page = self._download_webpage(
  51. self._SIGNIN_URL, None, 'Downloading signin page')
  52. # Already logged in
  53. if any(re.search(p, signin_page) for p in (
  54. r'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
  55. return
  56. # Step 2: submit email
  57. signin_form = self._search_regex(
  58. r'(?s)(<form[^>]+data-form-name=["\']signin["\'][^>]*>.+?</form>)',
  59. signin_page, 'signin form')
  60. signin_page, signin_url = self._login_step(
  61. signin_form, self._PASSWORD_URL, {'email': username},
  62. 'Submitting email', self._SIGNIN_URL)
  63. # Step 3: submit password
  64. password_form = signin_page['body']
  65. self._login_step(
  66. password_form, self._USER_URL, {'email': username, 'password': password},
  67. 'Submitting password', signin_url)
  68. class LyndaIE(LyndaBaseIE):
  69. IE_NAME = 'lynda'
  70. IE_DESC = 'lynda.com videos'
  71. _VALID_URL = r'''(?x)
  72. https?://
  73. (?:www\.)?(?:lynda\.com|educourse\.ga)/
  74. (?:
  75. (?:[^/]+/){2,3}(?P<course_id>\d+)|
  76. player/embed
  77. )/
  78. (?P<id>\d+)
  79. '''
  80. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  81. _TESTS = [{
  82. 'url': 'https://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  83. # md5 is unstable
  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. 'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  95. 'only_matching': True,
  96. }, {
  97. 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Willkommen-Grundlagen-guten-Gestaltung/393570/393572-4.html',
  98. 'only_matching': True,
  99. }]
  100. def _raise_unavailable(self, video_id):
  101. self.raise_login_required(
  102. 'Video %s is only available for members' % video_id)
  103. def _real_extract(self, url):
  104. mobj = re.match(self._VALID_URL, url)
  105. video_id = mobj.group('id')
  106. course_id = mobj.group('course_id')
  107. query = {
  108. 'videoId': video_id,
  109. 'type': 'video',
  110. }
  111. video = self._download_json(
  112. 'https://www.lynda.com/ajax/player', video_id,
  113. 'Downloading video JSON', fatal=False, query=query)
  114. # Fallback scenario
  115. if not video:
  116. query['courseId'] = course_id
  117. play = self._download_json(
  118. 'https://www.lynda.com/ajax/course/%s/%s/play'
  119. % (course_id, video_id), video_id, 'Downloading play JSON')
  120. if not play:
  121. self._raise_unavailable(video_id)
  122. formats = []
  123. for formats_dict in play:
  124. urls = formats_dict.get('urls')
  125. if not isinstance(urls, dict):
  126. continue
  127. cdn = formats_dict.get('name')
  128. for format_id, format_url in urls.items():
  129. if not format_url:
  130. continue
  131. formats.append({
  132. 'url': format_url,
  133. 'format_id': '%s-%s' % (cdn, format_id) if cdn else format_id,
  134. 'height': int_or_none(format_id),
  135. })
  136. self._sort_formats(formats)
  137. conviva = self._download_json(
  138. 'https://www.lynda.com/ajax/player/conviva', video_id,
  139. 'Downloading conviva JSON', query=query)
  140. return {
  141. 'id': video_id,
  142. 'title': conviva['VideoTitle'],
  143. 'description': conviva.get('VideoDescription'),
  144. 'release_year': int_or_none(conviva.get('ReleaseYear')),
  145. 'duration': int_or_none(conviva.get('Duration')),
  146. 'creator': conviva.get('Author'),
  147. 'formats': formats,
  148. }
  149. if 'Status' in video:
  150. raise ExtractorError(
  151. 'lynda returned error: %s' % video['Message'], expected=True)
  152. if video.get('HasAccess') is False:
  153. self._raise_unavailable(video_id)
  154. video_id = compat_str(video.get('ID') or video_id)
  155. duration = int_or_none(video.get('DurationInSeconds'))
  156. title = video['Title']
  157. formats = []
  158. fmts = video.get('Formats')
  159. if fmts:
  160. formats.extend([{
  161. 'url': f['Url'],
  162. 'ext': f.get('Extension'),
  163. 'width': int_or_none(f.get('Width')),
  164. 'height': int_or_none(f.get('Height')),
  165. 'filesize': int_or_none(f.get('FileSize')),
  166. 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
  167. } for f in fmts if f.get('Url')])
  168. prioritized_streams = video.get('PrioritizedStreams')
  169. if prioritized_streams:
  170. for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
  171. formats.extend([{
  172. 'url': video_url,
  173. 'height': int_or_none(format_id),
  174. 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
  175. } for format_id, video_url in prioritized_stream.items()])
  176. self._check_formats(formats, video_id)
  177. self._sort_formats(formats)
  178. subtitles = self.extract_subtitles(video_id)
  179. return {
  180. 'id': video_id,
  181. 'title': title,
  182. 'duration': duration,
  183. 'subtitles': subtitles,
  184. 'formats': formats
  185. }
  186. def _fix_subtitles(self, subs):
  187. srt = ''
  188. seq_counter = 0
  189. for pos in range(0, len(subs) - 1):
  190. seq_current = subs[pos]
  191. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  192. if m_current is None:
  193. continue
  194. seq_next = subs[pos + 1]
  195. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  196. if m_next is None:
  197. continue
  198. appear_time = m_current.group('timecode')
  199. disappear_time = m_next.group('timecode')
  200. text = seq_current['Caption'].strip()
  201. if text:
  202. seq_counter += 1
  203. srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
  204. if srt:
  205. return srt
  206. def _get_subtitles(self, video_id):
  207. url = 'https://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
  208. subs = self._download_json(url, None, False)
  209. fixed_subs = self._fix_subtitles(subs)
  210. if fixed_subs:
  211. return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
  212. else:
  213. return {}
  214. class LyndaCourseIE(LyndaBaseIE):
  215. IE_NAME = 'lynda:course'
  216. IE_DESC = 'lynda.com online courses'
  217. # Course link equals to welcome/introduction video link of same course
  218. # We will recognize it as course link
  219. _VALID_URL = r'https?://(?:www|m)\.(?:lynda\.com|educourse\.ga)/(?P<coursepath>(?:[^/]+/){2,3}(?P<courseid>\d+))-2\.html'
  220. _TESTS = [{
  221. 'url': 'https://www.lynda.com/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
  222. 'only_matching': True,
  223. }, {
  224. 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
  225. 'only_matching': True,
  226. }]
  227. def _real_extract(self, url):
  228. mobj = re.match(self._VALID_URL, url)
  229. course_path = mobj.group('coursepath')
  230. course_id = mobj.group('courseid')
  231. item_template = 'https://www.lynda.com/%s/%%s-4.html' % course_path
  232. course = self._download_json(
  233. 'https://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
  234. course_id, 'Downloading course JSON', fatal=False)
  235. if not course:
  236. webpage = self._download_webpage(url, course_id)
  237. entries = [
  238. self.url_result(
  239. item_template % video_id, ie=LyndaIE.ie_key(),
  240. video_id=video_id)
  241. for video_id in re.findall(
  242. r'data-video-id=["\'](\d+)', webpage)]
  243. return self.playlist_result(
  244. entries, course_id,
  245. self._og_search_title(webpage, fatal=False),
  246. self._og_search_description(webpage))
  247. if course.get('Status') == 'NotFound':
  248. raise ExtractorError(
  249. 'Course %s does not exist' % course_id, expected=True)
  250. unaccessible_videos = 0
  251. entries = []
  252. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  253. # by single video API anymore
  254. for chapter in course['Chapters']:
  255. for video in chapter.get('Videos', []):
  256. if video.get('HasAccess') is False:
  257. unaccessible_videos += 1
  258. continue
  259. video_id = video.get('ID')
  260. if video_id:
  261. entries.append({
  262. '_type': 'url_transparent',
  263. 'url': item_template % video_id,
  264. 'ie_key': LyndaIE.ie_key(),
  265. 'chapter': chapter.get('Title'),
  266. 'chapter_number': int_or_none(chapter.get('ChapterIndex')),
  267. 'chapter_id': compat_str(chapter.get('ID')),
  268. })
  269. if unaccessible_videos > 0:
  270. self._downloader.report_warning(
  271. '%s videos are only available for members (or paid members) and will not be downloaded. '
  272. % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
  273. course_title = course.get('Title')
  274. course_description = course.get('Description')
  275. return self.playlist_result(entries, course_id, course_title, course_description)