frontendmasters.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import re
  2. from .common import InfoExtractor
  3. from ..compat import (
  4. compat_str,
  5. compat_urlparse,
  6. )
  7. from ..utils import (
  8. ExtractorError,
  9. parse_duration,
  10. url_or_none,
  11. urlencode_postdata,
  12. )
  13. class FrontendMastersBaseIE(InfoExtractor):
  14. _API_BASE = 'https://api.frontendmasters.com/v1/kabuki'
  15. _LOGIN_URL = 'https://frontendmasters.com/login/'
  16. _NETRC_MACHINE = 'frontendmasters'
  17. _QUALITIES = {
  18. 'low': {'width': 480, 'height': 360},
  19. 'mid': {'width': 1280, 'height': 720},
  20. 'high': {'width': 1920, 'height': 1080}
  21. }
  22. def _perform_login(self, username, password):
  23. login_page = self._download_webpage(
  24. self._LOGIN_URL, None, 'Downloading login page')
  25. login_form = self._hidden_inputs(login_page)
  26. login_form.update({
  27. 'username': username,
  28. 'password': password
  29. })
  30. post_url = self._search_regex(
  31. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  32. 'post_url', default=self._LOGIN_URL, group='url')
  33. if not post_url.startswith('http'):
  34. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  35. response = self._download_webpage(
  36. post_url, None, 'Logging in', data=urlencode_postdata(login_form),
  37. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  38. # Successful login
  39. if any(p in response for p in (
  40. 'wp-login.php?action=logout', '>Logout')):
  41. return
  42. error = self._html_search_regex(
  43. r'class=(["\'])(?:(?!\1).)*\bMessageAlert\b(?:(?!\1).)*\1[^>]*>(?P<error>[^<]+)<',
  44. response, 'error message', default=None, group='error')
  45. if error:
  46. raise ExtractorError('Unable to login: %s' % error, expected=True)
  47. raise ExtractorError('Unable to log in')
  48. class FrontendMastersPageBaseIE(FrontendMastersBaseIE):
  49. def _download_course(self, course_name, url):
  50. return self._download_json(
  51. '%s/courses/%s' % (self._API_BASE, course_name), course_name,
  52. 'Downloading course JSON', headers={'Referer': url})
  53. @staticmethod
  54. def _extract_chapters(course):
  55. chapters = []
  56. lesson_elements = course.get('lessonElements')
  57. if isinstance(lesson_elements, list):
  58. chapters = [url_or_none(e) for e in lesson_elements if url_or_none(e)]
  59. return chapters
  60. @staticmethod
  61. def _extract_lesson(chapters, lesson_id, lesson):
  62. title = lesson.get('title') or lesson_id
  63. display_id = lesson.get('slug')
  64. description = lesson.get('description')
  65. thumbnail = lesson.get('thumbnail')
  66. chapter_number = None
  67. index = lesson.get('index')
  68. element_index = lesson.get('elementIndex')
  69. if (isinstance(index, int) and isinstance(element_index, int)
  70. and index < element_index):
  71. chapter_number = element_index - index
  72. chapter = (chapters[chapter_number - 1]
  73. if chapter_number - 1 < len(chapters) else None)
  74. duration = None
  75. timestamp = lesson.get('timestamp')
  76. if isinstance(timestamp, compat_str):
  77. mobj = re.search(
  78. r'(?P<start>\d{1,2}:\d{1,2}:\d{1,2})\s*-(?P<end>\s*\d{1,2}:\d{1,2}:\d{1,2})',
  79. timestamp)
  80. if mobj:
  81. duration = parse_duration(mobj.group('end')) - parse_duration(
  82. mobj.group('start'))
  83. return {
  84. '_type': 'url_transparent',
  85. 'url': 'frontendmasters:%s' % lesson_id,
  86. 'ie_key': FrontendMastersIE.ie_key(),
  87. 'id': lesson_id,
  88. 'display_id': display_id,
  89. 'title': title,
  90. 'description': description,
  91. 'thumbnail': thumbnail,
  92. 'duration': duration,
  93. 'chapter': chapter,
  94. 'chapter_number': chapter_number,
  95. }
  96. class FrontendMastersIE(FrontendMastersBaseIE):
  97. _VALID_URL = r'(?:frontendmasters:|https?://api\.frontendmasters\.com/v\d+/kabuki/video/)(?P<id>[^/]+)'
  98. _TESTS = [{
  99. 'url': 'https://api.frontendmasters.com/v1/kabuki/video/a2qogef6ba',
  100. 'md5': '7f161159710d6b7016a4f4af6fcb05e2',
  101. 'info_dict': {
  102. 'id': 'a2qogef6ba',
  103. 'ext': 'mp4',
  104. 'title': 'a2qogef6ba',
  105. },
  106. 'skip': 'Requires FrontendMasters account credentials',
  107. }, {
  108. 'url': 'frontendmasters:a2qogef6ba',
  109. 'only_matching': True,
  110. }]
  111. def _real_extract(self, url):
  112. lesson_id = self._match_id(url)
  113. source_url = '%s/video/%s/source' % (self._API_BASE, lesson_id)
  114. formats = []
  115. for ext in ('webm', 'mp4'):
  116. for quality in ('low', 'mid', 'high'):
  117. resolution = self._QUALITIES[quality].copy()
  118. format_id = '%s-%s' % (ext, quality)
  119. format_url = self._download_json(
  120. source_url, lesson_id,
  121. 'Downloading %s source JSON' % format_id, query={
  122. 'f': ext,
  123. 'r': resolution['height'],
  124. }, headers={
  125. 'Referer': url,
  126. }, fatal=False)['url']
  127. if not format_url:
  128. continue
  129. f = resolution.copy()
  130. f.update({
  131. 'url': format_url,
  132. 'ext': ext,
  133. 'format_id': format_id,
  134. })
  135. formats.append(f)
  136. subtitles = {
  137. 'en': [{
  138. 'url': '%s/transcripts/%s.vtt' % (self._API_BASE, lesson_id),
  139. }]
  140. }
  141. return {
  142. 'id': lesson_id,
  143. 'title': lesson_id,
  144. 'formats': formats,
  145. 'subtitles': subtitles
  146. }
  147. class FrontendMastersLessonIE(FrontendMastersPageBaseIE):
  148. _VALID_URL = r'https?://(?:www\.)?frontendmasters\.com/courses/(?P<course_name>[^/]+)/(?P<lesson_name>[^/]+)'
  149. _TEST = {
  150. 'url': 'https://frontendmasters.com/courses/web-development/tools',
  151. 'info_dict': {
  152. 'id': 'a2qogef6ba',
  153. 'display_id': 'tools',
  154. 'ext': 'mp4',
  155. 'title': 'Tools',
  156. 'description': 'md5:82c1ea6472e88ed5acd1829fe992e4f7',
  157. 'thumbnail': r're:^https?://.*\.jpg$',
  158. 'chapter': 'Introduction',
  159. 'chapter_number': 1,
  160. },
  161. 'params': {
  162. 'skip_download': True,
  163. },
  164. 'skip': 'Requires FrontendMasters account credentials',
  165. }
  166. def _real_extract(self, url):
  167. mobj = self._match_valid_url(url)
  168. course_name, lesson_name = mobj.group('course_name', 'lesson_name')
  169. course = self._download_course(course_name, url)
  170. lesson_id, lesson = next(
  171. (video_id, data)
  172. for video_id, data in course['lessonData'].items()
  173. if data.get('slug') == lesson_name)
  174. chapters = self._extract_chapters(course)
  175. return self._extract_lesson(chapters, lesson_id, lesson)
  176. class FrontendMastersCourseIE(FrontendMastersPageBaseIE):
  177. _VALID_URL = r'https?://(?:www\.)?frontendmasters\.com/courses/(?P<id>[^/]+)'
  178. _TEST = {
  179. 'url': 'https://frontendmasters.com/courses/web-development/',
  180. 'info_dict': {
  181. 'id': 'web-development',
  182. 'title': 'Introduction to Web Development',
  183. 'description': 'md5:9317e6e842098bf725d62360e52d49a6',
  184. },
  185. 'playlist_count': 81,
  186. 'skip': 'Requires FrontendMasters account credentials',
  187. }
  188. @classmethod
  189. def suitable(cls, url):
  190. return False if FrontendMastersLessonIE.suitable(url) else super(
  191. FrontendMastersBaseIE, cls).suitable(url)
  192. def _real_extract(self, url):
  193. course_name = self._match_id(url)
  194. course = self._download_course(course_name, url)
  195. chapters = self._extract_chapters(course)
  196. lessons = sorted(
  197. course['lessonData'].values(), key=lambda data: data['index'])
  198. entries = []
  199. for lesson in lessons:
  200. lesson_name = lesson.get('slug')
  201. lesson_id = lesson.get('hash') or lesson.get('statsId')
  202. if not lesson_id or not lesson_name:
  203. continue
  204. entries.append(self._extract_lesson(chapters, lesson_id, lesson))
  205. title = course.get('title')
  206. description = course.get('description')
  207. return self.playlist_result(entries, course_name, title, description)