safari.py 9.6 KB

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