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.

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