safari.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import json
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. update_url_query,
  8. )
  9. class SafariBaseIE(InfoExtractor):
  10. _LOGIN_URL = 'https://learning.oreilly.com/accounts/login/'
  11. _NETRC_MACHINE = 'safari'
  12. _API_BASE = 'https://learning.oreilly.com/api/v1'
  13. _API_FORMAT = 'json'
  14. LOGGED_IN = False
  15. def _perform_login(self, username, password):
  16. _, urlh = self._download_webpage_handle(
  17. 'https://learning.oreilly.com/accounts/login-check/', None,
  18. 'Downloading login page')
  19. def is_logged(urlh):
  20. return 'learning.oreilly.com/home/' in urlh.url
  21. if is_logged(urlh):
  22. self.LOGGED_IN = True
  23. return
  24. redirect_url = urlh.url
  25. parsed_url = urllib.parse.urlparse(redirect_url)
  26. qs = urllib.parse.parse_qs(parsed_url.query)
  27. next_uri = urllib.parse.urljoin(
  28. 'https://api.oreilly.com', qs['next'][0])
  29. auth, urlh = self._download_json_handle(
  30. 'https://www.oreilly.com/member/auth/login/', None, 'Logging in',
  31. data=json.dumps({
  32. 'email': username,
  33. 'password': password,
  34. 'redirect_uri': next_uri,
  35. }).encode(), headers={
  36. 'Content-Type': 'application/json',
  37. 'Referer': redirect_url,
  38. }, expected_status=400)
  39. credentials = auth.get('credentials')
  40. if (not auth.get('logged_in') and not auth.get('redirect_uri')
  41. and credentials):
  42. raise ExtractorError(
  43. f'Unable to login: {credentials}', expected=True)
  44. # oreilly serves two same instances of the following cookies
  45. # in Set-Cookie header and expects first one to be actually set
  46. for cookie in ('groot_sessionid', 'orm-jwt', 'orm-rt'):
  47. self._apply_first_set_cookie_header(urlh, cookie)
  48. _, urlh = self._download_webpage_handle(
  49. auth.get('redirect_uri') or next_uri, None, 'Completing login')
  50. if is_logged(urlh):
  51. self.LOGGED_IN = True
  52. return
  53. raise ExtractorError('Unable to log in')
  54. class SafariIE(SafariBaseIE):
  55. IE_NAME = 'safari'
  56. IE_DESC = 'safaribooksonline.com online video'
  57. _VALID_URL = r'''(?x)
  58. https?://
  59. (?:www\.)?(?:safaribooksonline|(?:learning\.)?oreilly)\.com/
  60. (?:
  61. library/view/[^/]+/(?P<course_id>[^/]+)/(?P<part>[^/?\#&]+)\.html|
  62. videos/[^/]+/[^/]+/(?P<reference_id>[^-]+-[^/?\#&]+)
  63. )
  64. '''
  65. _TESTS = [{
  66. 'url': 'https://www.safaribooksonline.com/library/view/hadoop-fundamentals-livelessons/9780133392838/part00.html',
  67. 'md5': 'dcc5a425e79f2564148652616af1f2a3',
  68. 'info_dict': {
  69. 'id': '0_qbqx90ic',
  70. 'ext': 'mp4',
  71. 'title': 'Introduction to Hadoop Fundamentals LiveLessons',
  72. 'timestamp': 1437758058,
  73. 'upload_date': '20150724',
  74. 'uploader_id': 'stork',
  75. },
  76. }, {
  77. # non-digits in course id
  78. 'url': 'https://www.safaribooksonline.com/library/view/create-a-nodejs/100000006A0210/part00.html',
  79. 'only_matching': True,
  80. }, {
  81. 'url': 'https://www.safaribooksonline.com/library/view/learning-path-red/9780134664057/RHCE_Introduction.html',
  82. 'only_matching': True,
  83. }, {
  84. 'url': 'https://www.safaribooksonline.com/videos/python-programming-language/9780134217314/9780134217314-PYMC_13_00',
  85. 'only_matching': True,
  86. }, {
  87. 'url': 'https://learning.oreilly.com/videos/hadoop-fundamentals-livelessons/9780133392838/9780133392838-00_SeriesIntro',
  88. 'only_matching': True,
  89. }, {
  90. 'url': 'https://www.oreilly.com/library/view/hadoop-fundamentals-livelessons/9780133392838/00_SeriesIntro.html',
  91. 'only_matching': True,
  92. }]
  93. _PARTNER_ID = '1926081'
  94. _UICONF_ID = '29375172'
  95. def _real_extract(self, url):
  96. mobj = self._match_valid_url(url)
  97. reference_id = mobj.group('reference_id')
  98. if reference_id:
  99. video_id = reference_id
  100. partner_id = self._PARTNER_ID
  101. ui_id = self._UICONF_ID
  102. else:
  103. video_id = '{}-{}'.format(mobj.group('course_id'), mobj.group('part'))
  104. webpage, urlh = self._download_webpage_handle(url, video_id)
  105. mobj = re.match(self._VALID_URL, urlh.url)
  106. reference_id = mobj.group('reference_id')
  107. if not reference_id:
  108. reference_id = self._search_regex(
  109. r'data-reference-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  110. webpage, 'kaltura reference id', group='id')
  111. partner_id = self._search_regex(
  112. r'data-partner-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  113. webpage, 'kaltura widget id', default=self._PARTNER_ID,
  114. group='id')
  115. ui_id = self._search_regex(
  116. r'data-ui-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  117. webpage, 'kaltura uiconf id', default=self._UICONF_ID,
  118. group='id')
  119. query = {
  120. 'wid': f'_{partner_id}',
  121. 'uiconf_id': ui_id,
  122. 'flashvars[referenceId]': reference_id,
  123. }
  124. if self.LOGGED_IN:
  125. kaltura_session = self._download_json(
  126. f'{self._API_BASE}/player/kaltura_session/?reference_id={reference_id}',
  127. video_id, 'Downloading kaltura session JSON',
  128. 'Unable to download kaltura session JSON', fatal=False,
  129. headers={'Accept': 'application/json'})
  130. if kaltura_session:
  131. session = kaltura_session.get('session')
  132. if session:
  133. query['flashvars[ks]'] = session
  134. return self.url_result(update_url_query(
  135. 'https://cdnapisec.kaltura.com/html5/html5lib/v2.37.1/mwEmbedFrame.php', query),
  136. 'Kaltura')
  137. class SafariApiIE(SafariBaseIE):
  138. IE_NAME = 'safari:api'
  139. _VALID_URL = r'https?://(?:www\.)?(?:safaribooksonline|(?:learning\.)?oreilly)\.com/api/v1/book/(?P<course_id>[^/]+)/chapter(?:-content)?/(?P<part>[^/?#&]+)\.html'
  140. _TESTS = [{
  141. 'url': 'https://www.safaribooksonline.com/api/v1/book/9780133392838/chapter/part00.html',
  142. 'only_matching': True,
  143. }, {
  144. 'url': 'https://www.safaribooksonline.com/api/v1/book/9780134664057/chapter/RHCE_Introduction.html',
  145. 'only_matching': True,
  146. }]
  147. def _real_extract(self, url):
  148. mobj = self._match_valid_url(url)
  149. part = self._download_json(
  150. url, '{}/{}'.format(mobj.group('course_id'), mobj.group('part')),
  151. 'Downloading part JSON')
  152. web_url = part['web_url']
  153. if 'library/view' in web_url:
  154. web_url = web_url.replace('library/view', 'videos')
  155. natural_keys = part['natural_key']
  156. web_url = f'{web_url.rsplit("/", 1)[0]}/{natural_keys[0]}-{natural_keys[1][:-5]}'
  157. return self.url_result(web_url, SafariIE.ie_key())
  158. class SafariCourseIE(SafariBaseIE):
  159. IE_NAME = 'safari:course'
  160. IE_DESC = 'safaribooksonline.com online courses'
  161. _VALID_URL = r'''(?x)
  162. https?://
  163. (?:
  164. (?:www\.)?(?:safaribooksonline|(?:learning\.)?oreilly)\.com/
  165. (?:
  166. library/view/[^/]+|
  167. api/v1/book|
  168. videos/[^/]+
  169. )|
  170. techbus\.safaribooksonline\.com
  171. )
  172. /(?P<id>[^/]+)
  173. '''
  174. _TESTS = [{
  175. 'url': 'https://www.safaribooksonline.com/library/view/hadoop-fundamentals-livelessons/9780133392838/',
  176. 'info_dict': {
  177. 'id': '9780133392838',
  178. 'title': 'Hadoop Fundamentals LiveLessons',
  179. },
  180. 'playlist_count': 22,
  181. 'skip': 'Requires safaribooksonline account credentials',
  182. }, {
  183. 'url': 'https://www.safaribooksonline.com/api/v1/book/9781449396459/?override_format=json',
  184. 'only_matching': True,
  185. }, {
  186. 'url': 'http://techbus.safaribooksonline.com/9780134426365',
  187. 'only_matching': True,
  188. }, {
  189. 'url': 'https://www.safaribooksonline.com/videos/python-programming-language/9780134217314',
  190. 'only_matching': True,
  191. }, {
  192. 'url': 'https://learning.oreilly.com/videos/hadoop-fundamentals-livelessons/9780133392838',
  193. 'only_matching': True,
  194. }, {
  195. 'url': 'https://www.oreilly.com/library/view/hadoop-fundamentals-livelessons/9780133392838/',
  196. 'only_matching': True,
  197. }]
  198. @classmethod
  199. def suitable(cls, url):
  200. return (False if SafariIE.suitable(url) or SafariApiIE.suitable(url)
  201. else super().suitable(url))
  202. def _real_extract(self, url):
  203. course_id = self._match_id(url)
  204. course_json = self._download_json(
  205. f'{self._API_BASE}/book/{course_id}/?override_format={self._API_FORMAT}',
  206. course_id, 'Downloading course JSON')
  207. if 'chapters' not in course_json:
  208. raise ExtractorError(
  209. f'No chapters found for course {course_id}', expected=True)
  210. entries = [
  211. self.url_result(chapter, SafariApiIE.ie_key())
  212. for chapter in course_json['chapters']]
  213. course_title = course_json['title']
  214. return self.playlist_result(entries, course_id, course_title)