You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

170 lines
5.9 KiB

  1. from __future__ import unicode_literals
  2. import json
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_HTTPError,
  8. )
  9. from ..utils import (
  10. clean_html,
  11. ExtractorError,
  12. remove_end,
  13. strip_or_none,
  14. unified_timestamp,
  15. urljoin,
  16. )
  17. class PacktPubBaseIE(InfoExtractor):
  18. _PACKT_BASE = 'https://www.packtpub.com'
  19. _MAPT_REST = '%s/mapt-rest' % _PACKT_BASE
  20. class PacktPubIE(PacktPubBaseIE):
  21. _VALID_URL = r'https?://(?:(?:www\.)?packtpub\.com/mapt|subscription\.packtpub\.com)/video/[^/]+/(?P<course_id>\d+)/(?P<chapter_id>\d+)/(?P<id>\d+)'
  22. _TESTS = [{
  23. 'url': 'https://www.packtpub.com/mapt/video/web-development/9781787122215/20528/20530/Project+Intro',
  24. 'md5': '1e74bd6cfd45d7d07666f4684ef58f70',
  25. 'info_dict': {
  26. 'id': '20530',
  27. 'ext': 'mp4',
  28. 'title': 'Project Intro',
  29. 'thumbnail': r're:(?i)^https?://.*\.jpg',
  30. 'timestamp': 1490918400,
  31. 'upload_date': '20170331',
  32. },
  33. }, {
  34. 'url': 'https://subscription.packtpub.com/video/web_development/9781787122215/20528/20530/project-intro',
  35. 'only_matching': True,
  36. }]
  37. _NETRC_MACHINE = 'packtpub'
  38. _TOKEN = None
  39. def _real_initialize(self):
  40. username, password = self._get_login_info()
  41. if username is None:
  42. return
  43. try:
  44. self._TOKEN = self._download_json(
  45. self._MAPT_REST + '/users/tokens', None,
  46. 'Downloading Authorization Token', data=json.dumps({
  47. 'email': username,
  48. 'password': password,
  49. }).encode())['data']['access']
  50. except ExtractorError as e:
  51. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (400, 401, 404):
  52. message = self._parse_json(e.cause.read().decode(), None)['message']
  53. raise ExtractorError(message, expected=True)
  54. raise
  55. def _handle_error(self, response):
  56. if response.get('status') != 'success':
  57. raise ExtractorError(
  58. '% said: %s' % (self.IE_NAME, response['message']),
  59. expected=True)
  60. def _download_json(self, *args, **kwargs):
  61. response = super(PacktPubIE, self)._download_json(*args, **kwargs)
  62. self._handle_error(response)
  63. return response
  64. def _real_extract(self, url):
  65. mobj = re.match(self._VALID_URL, url)
  66. course_id, chapter_id, video_id = mobj.group(
  67. 'course_id', 'chapter_id', 'id')
  68. headers = {}
  69. if self._TOKEN:
  70. headers['Authorization'] = 'Bearer ' + self._TOKEN
  71. video = self._download_json(
  72. '%s/users/me/products/%s/chapters/%s/sections/%s'
  73. % (self._MAPT_REST, course_id, chapter_id, video_id), video_id,
  74. 'Downloading JSON video', headers=headers)['data']
  75. content = video.get('content')
  76. if not content:
  77. self.raise_login_required('This video is locked')
  78. video_url = content['file']
  79. metadata = self._download_json(
  80. '%s/products/%s/chapters/%s/sections/%s/metadata'
  81. % (self._MAPT_REST, course_id, chapter_id, video_id),
  82. video_id)['data']
  83. title = metadata['pageTitle']
  84. course_title = metadata.get('title')
  85. if course_title:
  86. title = remove_end(title, ' - %s' % course_title)
  87. timestamp = unified_timestamp(metadata.get('publicationDate'))
  88. thumbnail = urljoin(self._PACKT_BASE, metadata.get('filepath'))
  89. return {
  90. 'id': video_id,
  91. 'url': video_url,
  92. 'title': title,
  93. 'thumbnail': thumbnail,
  94. 'timestamp': timestamp,
  95. }
  96. class PacktPubCourseIE(PacktPubBaseIE):
  97. _VALID_URL = r'(?P<url>https?://(?:(?:www\.)?packtpub\.com/mapt|subscription\.packtpub\.com)/video/[^/]+/(?P<id>\d+))'
  98. _TESTS = [{
  99. 'url': 'https://www.packtpub.com/mapt/video/web-development/9781787122215',
  100. 'info_dict': {
  101. 'id': '9781787122215',
  102. 'title': 'Learn Nodejs by building 12 projects [Video]',
  103. },
  104. 'playlist_count': 90,
  105. }, {
  106. 'url': 'https://subscription.packtpub.com/video/web_development/9781787122215',
  107. 'only_matching': True,
  108. }]
  109. @classmethod
  110. def suitable(cls, url):
  111. return False if PacktPubIE.suitable(url) else super(
  112. PacktPubCourseIE, cls).suitable(url)
  113. def _real_extract(self, url):
  114. mobj = re.match(self._VALID_URL, url)
  115. url, course_id = mobj.group('url', 'id')
  116. course = self._download_json(
  117. '%s/products/%s/metadata' % (self._MAPT_REST, course_id),
  118. course_id)['data']
  119. entries = []
  120. for chapter_num, chapter in enumerate(course['tableOfContents'], 1):
  121. if chapter.get('type') != 'chapter':
  122. continue
  123. children = chapter.get('children')
  124. if not isinstance(children, list):
  125. continue
  126. chapter_info = {
  127. 'chapter': chapter.get('title'),
  128. 'chapter_number': chapter_num,
  129. 'chapter_id': chapter.get('id'),
  130. }
  131. for section in children:
  132. if section.get('type') != 'section':
  133. continue
  134. section_url = section.get('seoUrl')
  135. if not isinstance(section_url, compat_str):
  136. continue
  137. entry = {
  138. '_type': 'url_transparent',
  139. 'url': urljoin(url + '/', section_url),
  140. 'title': strip_or_none(section.get('title')),
  141. 'description': clean_html(section.get('summary')),
  142. 'ie_key': PacktPubIE.ie_key(),
  143. }
  144. entry.update(chapter_info)
  145. entries.append(entry)
  146. return self.playlist_result(entries, course_id, course.get('title'))