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.

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