lynda.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import re
  2. import urllib.parse
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. ExtractorError,
  6. int_or_none,
  7. urlencode_postdata,
  8. )
  9. class LyndaBaseIE(InfoExtractor):
  10. _SIGNIN_URL = 'https://www.lynda.com/signin/lynda'
  11. _PASSWORD_URL = 'https://www.lynda.com/signin/password'
  12. _USER_URL = 'https://www.lynda.com/signin/user'
  13. _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
  14. _NETRC_MACHINE = 'lynda'
  15. @staticmethod
  16. def _check_error(json_string, key_or_keys):
  17. keys = [key_or_keys] if isinstance(key_or_keys, str) else key_or_keys
  18. for key in keys:
  19. error = json_string.get(key)
  20. if error:
  21. raise ExtractorError(f'Unable to login: {error}', expected=True)
  22. def _perform_login_step(self, form_html, fallback_action_url, extra_form_data, note, referrer_url):
  23. action_url = self._search_regex(
  24. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', form_html,
  25. 'post url', default=fallback_action_url, group='url')
  26. if not action_url.startswith('http'):
  27. action_url = urllib.parse.urljoin(self._SIGNIN_URL, action_url)
  28. form_data = self._hidden_inputs(form_html)
  29. form_data.update(extra_form_data)
  30. response = self._download_json(
  31. action_url, None, note,
  32. data=urlencode_postdata(form_data),
  33. headers={
  34. 'Referer': referrer_url,
  35. 'X-Requested-With': 'XMLHttpRequest',
  36. }, expected_status=(418, 500))
  37. self._check_error(response, ('email', 'password', 'ErrorMessage'))
  38. return response, action_url
  39. def _perform_login(self, username, password):
  40. # Step 1: download signin page
  41. signin_page = self._download_webpage(
  42. self._SIGNIN_URL, None, 'Downloading signin page')
  43. # Already logged in
  44. if any(re.search(p, signin_page) for p in (
  45. r'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
  46. return
  47. # Step 2: submit email
  48. signin_form = self._search_regex(
  49. r'(?s)(<form[^>]+data-form-name=["\']signin["\'][^>]*>.+?</form>)',
  50. signin_page, 'signin form')
  51. signin_page, signin_url = self._login_step(
  52. signin_form, self._PASSWORD_URL, {'email': username},
  53. 'Submitting email', self._SIGNIN_URL)
  54. # Step 3: submit password
  55. password_form = signin_page['body']
  56. self._login_step(
  57. password_form, self._USER_URL, {'email': username, 'password': password},
  58. 'Submitting password', signin_url)
  59. class LyndaIE(LyndaBaseIE):
  60. IE_NAME = 'lynda'
  61. IE_DESC = 'lynda.com videos'
  62. _VALID_URL = r'''(?x)
  63. https?://
  64. (?:www\.)?(?:lynda\.com|educourse\.ga)/
  65. (?:
  66. (?:[^/]+/){2,3}(?P<course_id>\d+)|
  67. player/embed
  68. )/
  69. (?P<id>\d+)
  70. '''
  71. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  72. _TESTS = [{
  73. 'url': 'https://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  74. # md5 is unstable
  75. 'info_dict': {
  76. 'id': '114408',
  77. 'ext': 'mp4',
  78. 'title': 'Using the exercise files',
  79. 'duration': 68,
  80. },
  81. }, {
  82. 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
  83. 'only_matching': True,
  84. }, {
  85. 'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  86. 'only_matching': True,
  87. }, {
  88. 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Willkommen-Grundlagen-guten-Gestaltung/393570/393572-4.html',
  89. 'only_matching': True,
  90. }, {
  91. # Status="NotFound", Message="Transcript not found"
  92. 'url': 'https://www.lynda.com/ASP-NET-tutorials/What-you-should-know/5034180/2811512-4.html',
  93. 'only_matching': True,
  94. }]
  95. def _raise_unavailable(self, video_id):
  96. self.raise_login_required(
  97. f'Video {video_id} is only available for members')
  98. def _real_extract(self, url):
  99. mobj = self._match_valid_url(url)
  100. video_id = mobj.group('id')
  101. course_id = mobj.group('course_id')
  102. query = {
  103. 'videoId': video_id,
  104. 'type': 'video',
  105. }
  106. video = self._download_json(
  107. 'https://www.lynda.com/ajax/player', video_id,
  108. 'Downloading video JSON', fatal=False, query=query)
  109. # Fallback scenario
  110. if not video:
  111. query['courseId'] = course_id
  112. play = self._download_json(
  113. f'https://www.lynda.com/ajax/course/{course_id}/{video_id}/play', video_id, 'Downloading play JSON')
  114. if not play:
  115. self._raise_unavailable(video_id)
  116. formats = []
  117. for formats_dict in play:
  118. urls = formats_dict.get('urls')
  119. if not isinstance(urls, dict):
  120. continue
  121. cdn = formats_dict.get('name')
  122. for format_id, format_url in urls.items():
  123. if not format_url:
  124. continue
  125. formats.append({
  126. 'url': format_url,
  127. 'format_id': f'{cdn}-{format_id}' if cdn else format_id,
  128. 'height': int_or_none(format_id),
  129. })
  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: {}'.format(video['Message']), expected=True)
  145. if video.get('HasAccess') is False:
  146. self._raise_unavailable(video_id)
  147. video_id = 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': 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': f'{prioritized_stream_id}-{format_id}',
  168. } for format_id, video_url in prioritized_stream.items()])
  169. self._check_formats(formats, video_id)
  170. subtitles = self.extract_subtitles(video_id)
  171. return {
  172. 'id': video_id,
  173. 'title': title,
  174. 'duration': duration,
  175. 'subtitles': subtitles,
  176. 'formats': formats,
  177. }
  178. def _fix_subtitles(self, subs):
  179. srt = ''
  180. seq_counter = 0
  181. for seq_current, seq_next in zip(subs, subs[1:]):
  182. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  183. if m_current is None:
  184. continue
  185. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  186. if m_next is None:
  187. continue
  188. appear_time = m_current.group('timecode')
  189. disappear_time = m_next.group('timecode')
  190. text = seq_current['Caption'].strip()
  191. if text:
  192. seq_counter += 1
  193. srt += f'{seq_counter}\r\n{appear_time} --> {disappear_time}\r\n{text}\r\n\r\n'
  194. if srt:
  195. return srt
  196. def _get_subtitles(self, video_id):
  197. url = f'https://www.lynda.com/ajax/player?videoId={video_id}&type=transcript'
  198. subs = self._download_webpage(
  199. url, video_id, 'Downloading subtitles JSON', fatal=False)
  200. if not subs or 'Status="NotFound"' in subs:
  201. return {}
  202. subs = self._parse_json(subs, video_id, fatal=False)
  203. if not subs:
  204. return {}
  205. fixed_subs = self._fix_subtitles(subs)
  206. if fixed_subs:
  207. return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
  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>(?:[^/]+/){2,3}(?P<courseid>\d+))-2\.html'
  215. _TESTS = [{
  216. 'url': 'https://www.lynda.com/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
  217. 'only_matching': True,
  218. }, {
  219. 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
  220. 'only_matching': True,
  221. }]
  222. def _real_extract(self, url):
  223. mobj = self._match_valid_url(url)
  224. course_path = mobj.group('coursepath')
  225. course_id = mobj.group('courseid')
  226. item_template = f'https://www.lynda.com/{course_path}/%s-4.html'
  227. course = self._download_json(
  228. f'https://www.lynda.com/ajax/player?courseId={course_id}&type=course',
  229. course_id, 'Downloading course JSON', fatal=False)
  230. if not course:
  231. webpage = self._download_webpage(url, course_id)
  232. entries = [
  233. self.url_result(
  234. item_template % video_id, ie=LyndaIE.ie_key(),
  235. video_id=video_id)
  236. for video_id in re.findall(
  237. r'data-video-id=["\'](\d+)', webpage)]
  238. return self.playlist_result(
  239. entries, course_id,
  240. self._og_search_title(webpage, fatal=False),
  241. self._og_search_description(webpage))
  242. if course.get('Status') == 'NotFound':
  243. raise ExtractorError(
  244. f'Course {course_id} does not exist', expected=True)
  245. unaccessible_videos = 0
  246. entries = []
  247. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  248. # by single video API anymore
  249. for chapter in course['Chapters']:
  250. for video in chapter.get('Videos', []):
  251. if video.get('HasAccess') is False:
  252. unaccessible_videos += 1
  253. continue
  254. video_id = video.get('ID')
  255. if video_id:
  256. entries.append({
  257. '_type': 'url_transparent',
  258. 'url': item_template % video_id,
  259. 'ie_key': LyndaIE.ie_key(),
  260. 'chapter': chapter.get('Title'),
  261. 'chapter_number': int_or_none(chapter.get('ChapterIndex')),
  262. 'chapter_id': str(chapter.get('ID')),
  263. })
  264. if unaccessible_videos > 0:
  265. self.report_warning(
  266. f'{unaccessible_videos} videos are only available for members (or paid members) '
  267. f'and will not be downloaded. {self._ACCOUNT_CREDENTIALS_HINT}')
  268. course_title = course.get('Title')
  269. course_description = course.get('Description')
  270. return self.playlist_result(entries, course_id, course_title, course_description)