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.

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