Kobo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. from Globals import Globals
  2. from KoboDrmRemover import KoboDrmRemover
  3. import requests
  4. from typing import Dict, Tuple
  5. import base64
  6. import html
  7. import os
  8. import re
  9. import urllib
  10. import uuid
  11. class KoboException( Exception ):
  12. pass
  13. # The hook's workflow is based on this:
  14. # https://github.com/requests/toolbelt/blob/master/requests_toolbelt/auth/http_proxy_digest.py
  15. def ReauthenticationHook( r, *args, **kwargs ):
  16. if r.status_code != requests.codes.unauthorized: # 401
  17. return
  18. print( "Refreshing expired authentication token" )
  19. # Consume content and release the original connection to allow our new request to reuse the same one.
  20. r.content
  21. r.close()
  22. prep = r.request.copy()
  23. # Refresh the authentication token and use it.
  24. Globals.Kobo.RefreshAuthentication()
  25. headers = Kobo.GetHeaderWithAccessToken()
  26. prep.headers[ "Authorization" ] = headers[ "Authorization" ]
  27. # Don't retry to reauthenticate this request again.
  28. prep.deregister_hook( "response", ReauthenticationHook )
  29. # Resend the failed request.
  30. _r = r.connection.send( prep, **kwargs )
  31. _r.history.append( r )
  32. _r.request = prep
  33. return _r
  34. class Kobo:
  35. Affiliate = "Kobo"
  36. ApplicationVersion = "8.11.24971"
  37. DefaultPlatformId = "00000000-0000-0000-0000-000000004000"
  38. DisplayProfile = "Android"
  39. def __init__( self ):
  40. self.InitializationSettings = {}
  41. self.Session = requests.session()
  42. # This could be added to the session but then we would need to add { "Authorization": None } headers to all other
  43. # functions that doesn't need authorization.
  44. @staticmethod
  45. def GetHeaderWithAccessToken() -> dict:
  46. authorization = "Bearer " + Globals.Settings.AccessToken
  47. headers = { "Authorization": authorization }
  48. return headers
  49. # This could be added to the session too. See the comment at GetHeaderWithAccessToken.
  50. @staticmethod
  51. def __GetReauthenticationHook() -> dict:
  52. return { "response": ReauthenticationHook }
  53. # The initial device authentication request for a non-logged in user doesn't require a user key, and the returned
  54. # user key can't be used for anything.
  55. def AuthenticateDevice( self, userKey: str = "" ) -> None:
  56. if len( Globals.Settings.DeviceId ) == 0:
  57. Globals.Settings.DeviceId = str( uuid.uuid4() )
  58. Globals.Settings.AccessToken = ""
  59. Globals.Settings.RefreshToken = ""
  60. postData = {
  61. "AffiliateName": Kobo.Affiliate,
  62. "AppVersion": Kobo.ApplicationVersion,
  63. "ClientKey": base64.b64encode( Kobo.DefaultPlatformId.encode() ).decode(),
  64. "DeviceId": Globals.Settings.DeviceId,
  65. "PlatformId": Kobo.DefaultPlatformId
  66. }
  67. if len( userKey ) > 0:
  68. postData[ "UserKey" ] = userKey
  69. response = self.Session.post( "https://storeapi.kobo.com/v1/auth/device", json = postData )
  70. response.raise_for_status()
  71. jsonResponse = response.json()
  72. if jsonResponse[ "TokenType" ] != "Bearer":
  73. raise KoboException( "Device authentication returned with an unsupported token type: '%s'" % jsonResponse[ "TokenType" ] )
  74. Globals.Settings.AccessToken = jsonResponse[ "AccessToken" ]
  75. Globals.Settings.RefreshToken = jsonResponse[ "RefreshToken" ]
  76. if not Globals.Settings.AreAuthenticationSettingsSet():
  77. raise KoboException( "Authentication settings are not set after device authentication." )
  78. if len( userKey ) > 0:
  79. Globals.Settings.UserKey = jsonResponse[ "UserKey" ]
  80. Globals.Settings.Save()
  81. def RefreshAuthentication( self ) -> None:
  82. headers = Kobo.GetHeaderWithAccessToken()
  83. postData = {
  84. "AppVersion": Kobo.ApplicationVersion,
  85. "ClientKey": base64.b64encode( Kobo.DefaultPlatformId.encode() ).decode(),
  86. "PlatformId": Kobo.DefaultPlatformId,
  87. "RefreshToken": Globals.Settings.RefreshToken
  88. }
  89. # The reauthentication hook is intentionally not set.
  90. response = self.Session.post( "https://storeapi.kobo.com/v1/auth/refresh", json = postData, headers = headers )
  91. response.raise_for_status()
  92. jsonResponse = response.json()
  93. if jsonResponse[ "TokenType" ] != "Bearer":
  94. raise KoboException( "Authentication refresh returned with an unsupported token type: '%s'" % jsonResponse[ "TokenType" ] )
  95. Globals.Settings.AccessToken = jsonResponse[ "AccessToken" ]
  96. Globals.Settings.RefreshToken = jsonResponse[ "RefreshToken" ]
  97. if not Globals.Settings.AreAuthenticationSettingsSet():
  98. raise KoboException( "Authentication settings are not set after authentication refresh." )
  99. Globals.Settings.Save()
  100. def LoadInitializationSettings( self ) -> None:
  101. headers = Kobo.GetHeaderWithAccessToken()
  102. hooks = Kobo.__GetReauthenticationHook()
  103. response = self.Session.get( "https://storeapi.kobo.com/v1/initialization", headers = headers, hooks = hooks )
  104. response.raise_for_status()
  105. jsonResponse = response.json()
  106. self.InitializationSettings = jsonResponse[ "Resources" ]
  107. def __GetExtraLoginParameters( self ) -> Tuple[ str, str, str ]:
  108. signInUrl = self.InitializationSettings[ "sign_in_page" ]
  109. params = {
  110. "wsa": Kobo.Affiliate,
  111. "pwsav": Kobo.ApplicationVersion,
  112. "pwspid": Kobo.DefaultPlatformId,
  113. "pwsdid": Globals.Settings.DeviceId
  114. }
  115. response = self.Session.get( signInUrl, params = params )
  116. response.raise_for_status()
  117. htmlResponse = response.text
  118. # The link can be found in the response ('<a class="kobo-link partner-option kobo"') but this will do for now.
  119. parsed = urllib.parse.urlparse( signInUrl )
  120. koboSignInUrl = parsed._replace( query = None, path = "/ww/en/signin/signin/kobo" ).geturl()
  121. match = re.search( r""" name="LogInModel.WorkflowId" type="hidden" value="([^"]+)" />""", htmlResponse )
  122. if match is None:
  123. raise KoboException( "Can't find the workflow ID in the login form. The page format might have changed." )
  124. workflowId = html.unescape( match.group( 1 ) )
  125. match = re.search( r"""<input name="__RequestVerificationToken" type="hidden" value="([^"]+)" />""", htmlResponse )
  126. if match is None:
  127. raise KoboException( "Can't find the request verification token in the login form. The page format might have changed." )
  128. requestVerificationToken = html.unescape( match.group( 1 ) )
  129. return koboSignInUrl, workflowId, requestVerificationToken
  130. def Login( self, email: str, password: str, captcha: str ) -> None:
  131. signInUrl, workflowId, requestVerificationToken = self.__GetExtraLoginParameters()
  132. postData = {
  133. "LogInModel.WorkflowId": workflowId,
  134. "LogInModel.Provider": Kobo.Affiliate,
  135. "ReturnUrl": "",
  136. "__RequestVerificationToken": requestVerificationToken,
  137. "LogInModel.UserName": email,
  138. "LogInModel.Password": password,
  139. "g-recaptcha-response": captcha
  140. }
  141. response = self.Session.post( signInUrl, data = postData )
  142. response.raise_for_status()
  143. htmlResponse = response.text
  144. match = re.search( r"'(kobo://UserAuthenticated\?[^']+)';", htmlResponse )
  145. if match is None:
  146. raise KoboException( "Authenticated user URL can't be found. The page format might have changed." )
  147. url = match.group( 1 )
  148. parsed = urllib.parse.urlparse( url )
  149. parsedQueries = urllib.parse.parse_qs( parsed.query )
  150. Globals.Settings.UserId = parsedQueries[ "userId" ][ 0 ] # We don't call Settings.Save here, AuthenticateDevice will do that if it succeeds.
  151. userKey = parsedQueries[ "userKey" ][ 0 ]
  152. self.AuthenticateDevice( userKey )
  153. def GetBookInfo( self, productId: str ) -> dict:
  154. url = self.InitializationSettings[ "book" ].replace( "{ProductId}", productId )
  155. headers = Kobo.GetHeaderWithAccessToken()
  156. hooks = Kobo.__GetReauthenticationHook()
  157. response = self.Session.get( url, headers = headers, hooks = hooks )
  158. response.raise_for_status()
  159. jsonResponse = response.json()
  160. return jsonResponse
  161. def __GetMyBookListPage( self, syncToken: str ) -> Tuple[ list, str ]:
  162. url = self.InitializationSettings[ "library_sync" ]
  163. headers = Kobo.GetHeaderWithAccessToken()
  164. hooks = Kobo.__GetReauthenticationHook()
  165. if len( syncToken ) > 0:
  166. headers[ "x-kobo-synctoken" ] = syncToken
  167. response = Globals.Kobo.Session.get( url, headers = headers, hooks = hooks )
  168. response.raise_for_status()
  169. bookList = response.json()
  170. syncToken = ""
  171. syncResult = response.headers.get( "x-kobo-sync" )
  172. if syncResult == "continue":
  173. syncToken = response.headers.get( "x-kobo-synctoken", "" )
  174. return bookList, syncToken
  175. def GetMyBookList( self ) -> list:
  176. # The "library_sync" name and the synchronization tokens make it somewhat suspicious that we should use
  177. # "library_items" instead to get the My Books list, but "library_items" gives back less info (even with the
  178. # embed=ProductMetadata query parameter set).
  179. fullBookList = []
  180. syncToken = ""
  181. while True:
  182. bookList, syncToken = self.__GetMyBookListPage( syncToken )
  183. fullBookList += bookList
  184. if len( syncToken ) == 0:
  185. break
  186. return fullBookList
  187. def __GetContentAccessBook( self, productId: str, displayProfile: str ) -> dict:
  188. url = self.InitializationSettings[ "content_access_book" ].replace( "{ProductId}", productId )
  189. params = { "DisplayProfile": displayProfile }
  190. headers = Kobo.GetHeaderWithAccessToken()
  191. hooks = Kobo.__GetReauthenticationHook()
  192. response = self.Session.get( url, params = params, headers = headers, hooks = hooks )
  193. response.raise_for_status()
  194. jsonResponse = response.json()
  195. return jsonResponse
  196. @staticmethod
  197. def __GetContentKeys( contentAccessBookResponse: dict ) -> Dict[ str, str ]:
  198. jsonContentKeys = contentAccessBookResponse.get( "ContentKeys" )
  199. if jsonContentKeys is None:
  200. return {}
  201. contentKeys = {}
  202. for contentKey in jsonContentKeys:
  203. contentKeys[ contentKey[ "Name" ] ] = contentKey[ "Value" ]
  204. return contentKeys
  205. @staticmethod
  206. def __GetDownloadInfo( productId: str, contentAccessBookResponse: dict ) -> Tuple[ str, bool ]:
  207. jsonContentUrls = contentAccessBookResponse.get( "ContentUrls" )
  208. if jsonContentUrls is None:
  209. raise KoboException( "Download URL can't be found for product '%s'." % productId )
  210. if len( jsonContentUrls ) == 0:
  211. raise KoboException( "Download URL list is empty for product '%s'. If this is an archived book then it must be unarchived first on the Kobo website (https://www.kobo.com/help/en-US/article/1799/restoring-deleted-books-or-magazines)." % productId )
  212. for jsonContentUrl in jsonContentUrls:
  213. if ( jsonContentUrl[ "DRMType" ] == "KDRM" or jsonContentUrl[ "DRMType" ] == "SignedNoDrm" ) and \
  214. ( jsonContentUrl[ "UrlFormat" ] == "EPUB3" or jsonContentUrl[ "UrlFormat" ] == "KEPUB" ):
  215. hasDrm = jsonContentUrl[ "DRMType" ] == "KDRM"
  216. return jsonContentUrl[ "DownloadUrl" ], hasDrm
  217. message = "Download URL for supported formats can't be found for product '%s'.\n" % productId
  218. message += "Available formats:"
  219. for jsonContentUrl in jsonContentUrls:
  220. message += "\nDRMType: '%s', UrlFormat: '%s'" % ( jsonContentUrl[ "DRMType" ], jsonContentUrl[ "UrlFormat" ] )
  221. raise KoboException( message )
  222. def __DownloadToFile( self, url, outputPath: str ) -> None:
  223. response = self.Session.get( url, stream = True )
  224. response.raise_for_status()
  225. with open( outputPath, "wb" ) as f:
  226. for chunk in response.iter_content( chunk_size = 1024 * 256 ):
  227. f.write( chunk )
  228. # Downloading archived books is not possible, the "content_access_book" API endpoint returns with empty ContentKeys
  229. # and ContentUrls for them.
  230. def Download( self, productId: str, displayProfile: str, outputPath: str ) -> None:
  231. jsonResponse = self.__GetContentAccessBook( productId, displayProfile )
  232. contentKeys = Kobo.__GetContentKeys( jsonResponse )
  233. downloadUrl, hasDrm = Kobo.__GetDownloadInfo( productId, jsonResponse )
  234. temporaryOutputPath = outputPath + ".downloading"
  235. try:
  236. self.__DownloadToFile( downloadUrl, temporaryOutputPath )
  237. if hasDrm:
  238. drmRemover = KoboDrmRemover( Globals.Settings.DeviceId, Globals.Settings.UserId )
  239. drmRemover.RemoveDrm( temporaryOutputPath, outputPath, contentKeys )
  240. os.remove( temporaryOutputPath )
  241. else:
  242. os.rename( temporaryOutputPath, outputPath )
  243. except:
  244. if os.path.isfile( temporaryOutputPath ):
  245. os.remove( temporaryOutputPath )
  246. if os.path.isfile( outputPath ):
  247. os.remove( outputPath )
  248. raise