Kobo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. # It was not possible to enter the entire captcha response on MacOS.
  12. # Importing readline changes the implementation of input() and solves the issue.
  13. # See https://stackoverflow.com/q/65735885 and https://stackoverflow.com/q/7357007.
  14. import readline
  15. class KoboException( Exception ):
  16. pass
  17. # The hook's workflow is based on this:
  18. # https://github.com/requests/toolbelt/blob/master/requests_toolbelt/auth/http_proxy_digest.py
  19. def ReauthenticationHook( r, *args, **kwargs ):
  20. if r.status_code != requests.codes.unauthorized: # 401
  21. return
  22. Globals.Logger.debug( "Refreshing expired authentication token" )
  23. # Consume content and release the original connection to allow our new request to reuse the same one.
  24. r.content
  25. r.close()
  26. prep = r.request.copy()
  27. # Refresh the authentication token and use it.
  28. Globals.Kobo.RefreshAuthentication()
  29. headers = Kobo.GetHeaderWithAccessToken()
  30. prep.headers[ "Authorization" ] = headers[ "Authorization" ]
  31. # Don't retry to reauthenticate this request again.
  32. prep.deregister_hook( "response", ReauthenticationHook )
  33. # Resend the failed request.
  34. _r = r.connection.send( prep, **kwargs )
  35. _r.history.append( r )
  36. _r.request = prep
  37. return _r
  38. class SessionWithTimeOut( requests.Session ):
  39. def request( self, method, url, **kwargs ):
  40. if "timeout" not in kwargs:
  41. kwargs[ "timeout" ] = 30 # 30 seconds
  42. return super().request( method, url, **kwargs )
  43. class Kobo:
  44. Affiliate = "Kobo"
  45. ApplicationVersion = "10.1.2.39807"
  46. DefaultPlatformId = "00000000-0000-0000-0000-000000004000"
  47. DisplayProfile = "Android"
  48. def __init__( self ):
  49. headers = {
  50. # Use the user agent of the Kobo Android app, otherwise the login request hangs forever.
  51. "User-Agent": "Mozilla/5.0 (Linux; Android 13; Pixel Build/TQ2B.230505.005.A1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/101.0.4951.61 Safari/537.36 KoboApp/10.1.2.39807 KoboPlatform Id/00000000-0000-0000-0000-000000004000 KoboAffiliate/Kobo KoboBuildFlavor/global",
  52. # At least one x-kobo-... header must present. Seemingly it does not matter which one, so we add these.
  53. "x-kobo-affiliatename": Kobo.Affiliate,
  54. "x-kobo-appversion": Kobo.ApplicationVersion,
  55. "x-kobo-platformid": Kobo.DefaultPlatformId,
  56. }
  57. self.InitializationSettings = {}
  58. self.Session = SessionWithTimeOut()
  59. self.Session.headers.update( headers )
  60. # This could be added to the session but then we would need to add { "Authorization": None } headers to all other
  61. # functions that doesn't need authorization.
  62. @staticmethod
  63. def GetHeaderWithAccessToken() -> dict:
  64. authorization = "Bearer " + Globals.Settings.AccessToken
  65. headers = { "Authorization": authorization }
  66. return headers
  67. # This could be added to the session too. See the comment at GetHeaderWithAccessToken.
  68. @staticmethod
  69. def __GetReauthenticationHook() -> dict:
  70. return { "response": ReauthenticationHook }
  71. # The initial device authentication request for a non-logged in user doesn't require a user key, and the returned
  72. # user key can't be used for anything.
  73. def AuthenticateDevice( self, userKey: str = "" ) -> None:
  74. Globals.Logger.debug( "Kobo.AuthenticateDevice" )
  75. if len( Globals.Settings.DeviceId ) == 0:
  76. Globals.Settings.DeviceId = str( uuid.uuid4() )
  77. Globals.Settings.AccessToken = ""
  78. Globals.Settings.RefreshToken = ""
  79. postData = {
  80. "AffiliateName": Kobo.Affiliate,
  81. "AppVersion": Kobo.ApplicationVersion,
  82. "ClientKey": base64.b64encode( Kobo.DefaultPlatformId.encode() ).decode(),
  83. "DeviceId": Globals.Settings.DeviceId,
  84. "PlatformId": Kobo.DefaultPlatformId
  85. }
  86. if len( userKey ) > 0:
  87. postData[ "UserKey" ] = userKey
  88. response = self.Session.post( "https://storeapi.kobo.com/v1/auth/device", json = postData )
  89. response.raise_for_status()
  90. jsonResponse = response.json()
  91. if jsonResponse[ "TokenType" ] != "Bearer":
  92. raise KoboException( "Device authentication returned with an unsupported token type: '%s'" % jsonResponse[ "TokenType" ] )
  93. Globals.Settings.AccessToken = jsonResponse[ "AccessToken" ]
  94. Globals.Settings.RefreshToken = jsonResponse[ "RefreshToken" ]
  95. if not Globals.Settings.AreAuthenticationSettingsSet():
  96. raise KoboException( "Authentication settings are not set after device authentication." )
  97. if len( userKey ) > 0:
  98. Globals.Settings.UserKey = jsonResponse[ "UserKey" ]
  99. Globals.Settings.Save()
  100. def RefreshAuthentication( self ) -> None:
  101. Globals.Logger.debug( "Kobo.RefreshAuthentication" )
  102. headers = Kobo.GetHeaderWithAccessToken()
  103. postData = {
  104. "AppVersion": Kobo.ApplicationVersion,
  105. "ClientKey": base64.b64encode( Kobo.DefaultPlatformId.encode() ).decode(),
  106. "PlatformId": Kobo.DefaultPlatformId,
  107. "RefreshToken": Globals.Settings.RefreshToken
  108. }
  109. # The reauthentication hook is intentionally not set.
  110. response = self.Session.post( "https://storeapi.kobo.com/v1/auth/refresh", json = postData, headers = headers )
  111. response.raise_for_status()
  112. jsonResponse = response.json()
  113. if jsonResponse[ "TokenType" ] != "Bearer":
  114. raise KoboException( "Authentication refresh returned with an unsupported token type: '%s'" % jsonResponse[ "TokenType" ] )
  115. Globals.Settings.AccessToken = jsonResponse[ "AccessToken" ]
  116. Globals.Settings.RefreshToken = jsonResponse[ "RefreshToken" ]
  117. if not Globals.Settings.AreAuthenticationSettingsSet():
  118. raise KoboException( "Authentication settings are not set after authentication refresh." )
  119. Globals.Settings.Save()
  120. def LoadInitializationSettings( self ) -> None:
  121. Globals.Logger.debug( "Kobo.LoadInitializationSettings" )
  122. headers = Kobo.GetHeaderWithAccessToken()
  123. hooks = Kobo.__GetReauthenticationHook()
  124. response = self.Session.get( "https://storeapi.kobo.com/v1/initialization", headers = headers, hooks = hooks )
  125. response.raise_for_status()
  126. jsonResponse = response.json()
  127. self.InitializationSettings = jsonResponse[ "Resources" ]
  128. def __GetExtraLoginParameters( self ) -> Tuple[ str, str, str ]:
  129. Globals.Logger.debug( "Kobo.__GetExtraLoginParameters" )
  130. signInUrl = self.InitializationSettings[ "sign_in_page" ]
  131. params = {
  132. "wsa": Kobo.Affiliate,
  133. "pwsav": Kobo.ApplicationVersion,
  134. "pwspid": Kobo.DefaultPlatformId,
  135. "pwsdid": Globals.Settings.DeviceId
  136. }
  137. response = self.Session.get( signInUrl, params = params )
  138. response.raise_for_status()
  139. htmlResponse = response.text
  140. # The link can be found in the response ('<a class="kobo-link partner-option kobo"') but the Android app does not use the entire path.
  141. # (The entire path looks like this: "/ww/en/signin/signin/kobo?workflowId=01234567-0123-0123-0123-0123456789ab".)
  142. parsed = urllib.parse.urlparse( signInUrl )
  143. koboSignInUrl = parsed._replace( query = None, path = "/ww/en/signin/signin" ).geturl()
  144. match = re.search( r"""/signin/kobo\?workflowId=([0-9a-f\-]+)""", htmlResponse )
  145. if match is None:
  146. raise KoboException( "Can't find the workflow ID. The page format might have changed." )
  147. workflowId = html.unescape( match.group( 1 ) )
  148. match = re.search( r"""<input name="__RequestVerificationToken" type="hidden" value="([^"]+)" />""", htmlResponse )
  149. if match is None:
  150. raise KoboException( "Can't find the request verification token in the login form. The page format might have changed." )
  151. requestVerificationToken = html.unescape( match.group( 1 ) )
  152. return koboSignInUrl, workflowId, requestVerificationToken
  153. def Login( self, email: str, password: str, captcha: str ) -> None:
  154. Globals.Logger.debug( "Kobo.Login" )
  155. signInUrl, workflowId, requestVerificationToken = self.__GetExtraLoginParameters()
  156. postData = {
  157. "LogInModel.WorkflowId": workflowId,
  158. "LogInModel.Provider": Kobo.Affiliate,
  159. "ReturnUrl": "",
  160. "__RequestVerificationToken": requestVerificationToken,
  161. "LogInModel.UserName": email,
  162. "LogInModel.Password": password,
  163. "g-recaptcha-response": captcha,
  164. "h-captcha-response": captcha
  165. }
  166. response = self.Session.post( signInUrl, data = postData )
  167. response.raise_for_status()
  168. htmlResponse = response.text
  169. match = re.search( r"'(kobo://UserAuthenticated\?[^']+)';", htmlResponse )
  170. if match is None:
  171. raise KoboException( "Authenticated user URL can't be found. The page format might have changed." )
  172. url = match.group( 1 )
  173. parsed = urllib.parse.urlparse( url )
  174. parsedQueries = urllib.parse.parse_qs( parsed.query )
  175. Globals.Settings.UserId = parsedQueries[ "userId" ][ 0 ] # We don't call Settings.Save here, AuthenticateDevice will do that if it succeeds.
  176. userKey = parsedQueries[ "userKey" ][ 0 ]
  177. self.AuthenticateDevice( userKey )
  178. def GetBookInfo( self, productId: str ) -> dict:
  179. Globals.Logger.debug( "Kobo.GetBookInfo" )
  180. url = self.InitializationSettings[ "book" ].replace( "{ProductId}", productId )
  181. headers = Kobo.GetHeaderWithAccessToken()
  182. hooks = Kobo.__GetReauthenticationHook()
  183. response = self.Session.get( url, headers = headers, hooks = hooks )
  184. response.raise_for_status()
  185. jsonResponse = response.json()
  186. return jsonResponse
  187. def __GetMyBookListPage( self, syncToken: str ) -> Tuple[ list, str ]:
  188. Globals.Logger.debug( "Kobo.__GetMyBookListPage" )
  189. url = self.InitializationSettings[ "library_sync" ]
  190. headers = Kobo.GetHeaderWithAccessToken()
  191. hooks = Kobo.__GetReauthenticationHook()
  192. if len( syncToken ) > 0:
  193. headers[ "x-kobo-synctoken" ] = syncToken
  194. response = Globals.Kobo.Session.get( url, headers = headers, hooks = hooks )
  195. response.raise_for_status()
  196. bookList = response.json()
  197. syncToken = ""
  198. syncResult = response.headers.get( "x-kobo-sync" )
  199. if syncResult == "continue":
  200. syncToken = response.headers.get( "x-kobo-synctoken", "" )
  201. return bookList, syncToken
  202. def GetMyBookList( self ) -> list:
  203. # The "library_sync" name and the synchronization tokens make it somewhat suspicious that we should use
  204. # "library_items" instead to get the My Books list, but "library_items" gives back less info (even with the
  205. # embed=ProductMetadata query parameter set).
  206. fullBookList = []
  207. syncToken = ""
  208. while True:
  209. bookList, syncToken = self.__GetMyBookListPage( syncToken )
  210. fullBookList += bookList
  211. if len( syncToken ) == 0:
  212. break
  213. return fullBookList
  214. def GetMyWishList( self ) -> list:
  215. Globals.Logger.debug( "Kobo.GetMyWishList" )
  216. items = []
  217. currentPageIndex = 0
  218. while True:
  219. url = self.InitializationSettings[ "user_wishlist" ]
  220. headers = Kobo.GetHeaderWithAccessToken()
  221. hooks = Kobo.__GetReauthenticationHook()
  222. params = {
  223. "PageIndex": currentPageIndex,
  224. "PageSize": 100, # 100 is the default if PageSize is not specified.
  225. }
  226. response = Globals.Kobo.Session.get( url, params = params, headers = headers, hooks = hooks )
  227. response.raise_for_status()
  228. wishList = response.json()
  229. items.extend( wishList[ "Items" ] )
  230. currentPageIndex += 1
  231. if currentPageIndex >= wishList[ "TotalPageCount" ]:
  232. break
  233. return items
  234. def __GetContentAccessBook( self, productId: str, displayProfile: str ) -> dict:
  235. Globals.Logger.debug( "Kobo.__GetContentAccessBook" )
  236. url = self.InitializationSettings[ "content_access_book" ].replace( "{ProductId}", productId )
  237. params = { "DisplayProfile": displayProfile }
  238. headers = Kobo.GetHeaderWithAccessToken()
  239. hooks = Kobo.__GetReauthenticationHook()
  240. response = self.Session.get( url, params = params, headers = headers, hooks = hooks )
  241. response.raise_for_status()
  242. jsonResponse = response.json()
  243. return jsonResponse
  244. @staticmethod
  245. def __GetContentKeys( contentAccessBookResponse: dict ) -> Dict[ str, str ]:
  246. jsonContentKeys = contentAccessBookResponse.get( "ContentKeys" )
  247. if jsonContentKeys is None:
  248. return {}
  249. contentKeys = {}
  250. for contentKey in jsonContentKeys:
  251. contentKeys[ contentKey[ "Name" ] ] = contentKey[ "Value" ]
  252. return contentKeys
  253. @staticmethod
  254. def __GetDownloadInfo( productId: str, contentAccessBookResponse: dict ) -> Tuple[ str, bool ]:
  255. jsonContentUrls = contentAccessBookResponse.get( "ContentUrls" )
  256. if jsonContentUrls is None:
  257. raise KoboException( "Download URL can't be found for product '%s'." % productId )
  258. if len( jsonContentUrls ) == 0:
  259. 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 )
  260. for jsonContentUrl in jsonContentUrls:
  261. if ( jsonContentUrl[ "DRMType" ] == "KDRM" or jsonContentUrl[ "DRMType" ] == "SignedNoDrm" ) and \
  262. ( jsonContentUrl[ "UrlFormat" ] == "EPUB3" or jsonContentUrl[ "UrlFormat" ] == "KEPUB" ):
  263. # Remove the mysterious "b" query parameter that causes forbidden downloads.
  264. url = jsonContentUrl[ "DownloadUrl" ]
  265. parsed = urllib.parse.urlparse( url )
  266. parsedQueries = urllib.parse.parse_qs( parsed.query )
  267. parsedQueries.pop( "b", None )
  268. url = parsed._replace( query = urllib.parse.urlencode( parsedQueries, doseq = True ) ).geturl()
  269. hasDrm = jsonContentUrl[ "DRMType" ] == "KDRM"
  270. return url, hasDrm
  271. message = "Download URL for supported formats can't be found for product '%s'.\n" % productId
  272. message += "Available formats:"
  273. for jsonContentUrl in jsonContentUrls:
  274. message += "\nDRMType: '%s', UrlFormat: '%s'" % ( jsonContentUrl[ "DRMType" ], jsonContentUrl[ "UrlFormat" ] )
  275. raise KoboException( message )
  276. def __DownloadToFile( self, url, outputPath: str ) -> None:
  277. Globals.Logger.debug( "Kobo.__DownloadToFile" )
  278. response = self.Session.get( url, stream = True )
  279. response.raise_for_status()
  280. with open( outputPath, "wb" ) as f:
  281. for chunk in response.iter_content( chunk_size = 1024 * 256 ):
  282. f.write( chunk )
  283. # Downloading archived books is not possible, the "content_access_book" API endpoint returns with empty ContentKeys
  284. # and ContentUrls for them.
  285. def Download( self, productId: str, displayProfile: str, outputPath: str ) -> None:
  286. Globals.Logger.debug( "Kobo.Download" )
  287. jsonResponse = self.__GetContentAccessBook( productId, displayProfile )
  288. contentKeys = Kobo.__GetContentKeys( jsonResponse )
  289. downloadUrl, hasDrm = Kobo.__GetDownloadInfo( productId, jsonResponse )
  290. temporaryOutputPath = outputPath + ".downloading"
  291. try:
  292. self.__DownloadToFile( downloadUrl, temporaryOutputPath )
  293. if hasDrm:
  294. drmRemover = KoboDrmRemover( Globals.Settings.DeviceId, Globals.Settings.UserId )
  295. drmRemover.RemoveDrm( temporaryOutputPath, outputPath, contentKeys )
  296. os.remove( temporaryOutputPath )
  297. else:
  298. os.rename( temporaryOutputPath, outputPath )
  299. except:
  300. if os.path.isfile( temporaryOutputPath ):
  301. os.remove( temporaryOutputPath )
  302. if os.path.isfile( outputPath ):
  303. os.remove( outputPath )
  304. raise