lynda.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. from __future__ import unicode_literals
  2. import re
  3. import json
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_urllib_parse,
  8. compat_urllib_request,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. clean_html,
  13. int_or_none,
  14. )
  15. class LyndaBaseIE(InfoExtractor):
  16. _LOGIN_URL = 'https://www.lynda.com/login/login.aspx'
  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. def _login(self):
  22. (username, password) = self._get_login_info()
  23. if username is None:
  24. return
  25. login_form = {
  26. 'username': username.encode('utf-8'),
  27. 'password': password.encode('utf-8'),
  28. 'remember': 'false',
  29. 'stayPut': 'false'
  30. }
  31. request = compat_urllib_request.Request(
  32. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  33. login_page = self._download_webpage(
  34. request, None, 'Logging in as %s' % username)
  35. # Not (yet) logged in
  36. m = re.search(r'loginResultJson\s*=\s*\'(?P<json>[^\']+)\';', login_page)
  37. if m is not None:
  38. response = m.group('json')
  39. response_json = json.loads(response)
  40. state = response_json['state']
  41. if state == 'notlogged':
  42. raise ExtractorError(
  43. 'Unable to login, incorrect username and/or password',
  44. expected=True)
  45. # This is when we get popup:
  46. # > You're already logged in to lynda.com on two devices.
  47. # > If you log in here, we'll log you out of another device.
  48. # So, we need to confirm this.
  49. if state == 'conflicted':
  50. confirm_form = {
  51. 'username': '',
  52. 'password': '',
  53. 'resolve': 'true',
  54. 'remember': 'false',
  55. 'stayPut': 'false',
  56. }
  57. request = compat_urllib_request.Request(
  58. self._LOGIN_URL, compat_urllib_parse.urlencode(confirm_form).encode('utf-8'))
  59. login_page = self._download_webpage(
  60. request, None,
  61. 'Confirming log in and log out from another device')
  62. if all(not re.search(p, login_page) for p in ('isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
  63. if 'login error' in login_page:
  64. mobj = re.search(
  65. r'(?s)<h1[^>]+class="topmost">(?P<title>[^<]+)</h1>\s*<div>(?P<description>.+?)</div>',
  66. login_page)
  67. if mobj:
  68. raise ExtractorError(
  69. 'lynda returned error: %s - %s'
  70. % (mobj.group('title'), clean_html(mobj.group('description'))),
  71. expected=True)
  72. raise ExtractorError('Unable to log in')
  73. def _logout(self):
  74. self._download_webpage(
  75. 'http://www.lynda.com/ajax/logout.aspx', None,
  76. 'Logging out', 'Unable to log out', fatal=False)
  77. class LyndaIE(LyndaBaseIE):
  78. IE_NAME = 'lynda'
  79. IE_DESC = 'lynda.com videos'
  80. _VALID_URL = r'https?://www\.lynda\.com/(?:[^/]+/[^/]+/\d+|player/embed)/(?P<id>\d+)'
  81. _NETRC_MACHINE = 'lynda'
  82. _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
  83. _TESTS = [{
  84. 'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
  85. 'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
  86. 'info_dict': {
  87. 'id': '114408',
  88. 'ext': 'mp4',
  89. 'title': 'Using the exercise files',
  90. 'duration': 68
  91. }
  92. }, {
  93. 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
  94. 'only_matching': True,
  95. }]
  96. def _real_extract(self, url):
  97. video_id = self._match_id(url)
  98. page = self._download_webpage(
  99. 'http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
  100. video_id, 'Downloading video JSON')
  101. video_json = json.loads(page)
  102. if 'Status' in video_json:
  103. raise ExtractorError(
  104. 'lynda returned error: %s' % video_json['Message'], expected=True)
  105. if video_json['HasAccess'] is False:
  106. self.raise_login_required('Video %s is only available for members' % video_id)
  107. video_id = compat_str(video_json['ID'])
  108. duration = video_json['DurationInSeconds']
  109. title = video_json['Title']
  110. formats = []
  111. fmts = video_json.get('Formats')
  112. if fmts:
  113. formats.extend([
  114. {
  115. 'url': fmt['Url'],
  116. 'ext': fmt['Extension'],
  117. 'width': fmt['Width'],
  118. 'height': fmt['Height'],
  119. 'filesize': fmt['FileSize'],
  120. 'format_id': str(fmt['Resolution'])
  121. } for fmt in fmts])
  122. prioritized_streams = video_json.get('PrioritizedStreams')
  123. if prioritized_streams:
  124. for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
  125. formats.extend([
  126. {
  127. 'url': video_url,
  128. 'width': int_or_none(format_id),
  129. 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
  130. } for format_id, video_url in prioritized_stream.items()
  131. ])
  132. self._check_formats(formats, video_id)
  133. self._sort_formats(formats)
  134. subtitles = self.extract_subtitles(video_id, page)
  135. return {
  136. 'id': video_id,
  137. 'title': title,
  138. 'duration': duration,
  139. 'subtitles': subtitles,
  140. 'formats': formats
  141. }
  142. def _fix_subtitles(self, subs):
  143. srt = ''
  144. seq_counter = 0
  145. for pos in range(0, len(subs) - 1):
  146. seq_current = subs[pos]
  147. m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
  148. if m_current is None:
  149. continue
  150. seq_next = subs[pos + 1]
  151. m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
  152. if m_next is None:
  153. continue
  154. appear_time = m_current.group('timecode')
  155. disappear_time = m_next.group('timecode')
  156. text = seq_current['Caption'].strip()
  157. if text:
  158. seq_counter += 1
  159. srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
  160. if srt:
  161. return srt
  162. def _get_subtitles(self, video_id, webpage):
  163. url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
  164. subs = self._download_json(url, None, False)
  165. if subs:
  166. return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
  167. else:
  168. return {}
  169. class LyndaCourseIE(LyndaBaseIE):
  170. IE_NAME = 'lynda:course'
  171. IE_DESC = 'lynda.com online courses'
  172. # Course link equals to welcome/introduction video link of same course
  173. # We will recognize it as course link
  174. _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
  175. def _real_extract(self, url):
  176. mobj = re.match(self._VALID_URL, url)
  177. course_path = mobj.group('coursepath')
  178. course_id = mobj.group('courseid')
  179. course = self._download_json(
  180. 'http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
  181. course_id, 'Downloading course JSON')
  182. self._logout()
  183. if course.get('Status') == 'NotFound':
  184. raise ExtractorError(
  185. 'Course %s does not exist' % course_id, expected=True)
  186. unaccessible_videos = 0
  187. videos = []
  188. # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
  189. # by single video API anymore
  190. for chapter in course['Chapters']:
  191. for video in chapter.get('Videos', []):
  192. if video.get('HasAccess') is False:
  193. unaccessible_videos += 1
  194. continue
  195. video_id = video.get('ID')
  196. if video_id:
  197. videos.append(video_id)
  198. if unaccessible_videos > 0:
  199. self._downloader.report_warning(
  200. '%s videos are only available for members (or paid members) and will not be downloaded. '
  201. % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
  202. entries = [
  203. self.url_result(
  204. 'http://www.lynda.com/%s/%s-4.html' % (course_path, video_id),
  205. 'Lynda')
  206. for video_id in videos]
  207. course_title = course.get('Title')
  208. return self.playlist_result(entries, course_id, course_title)