lynda.py 12 KB

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