PageRenderTime 66ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/yt_dlp/extractor/lynda.py

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