Skip to content

Commit

Permalink
[PP-612] Resolves library switch error (#373)
Browse files Browse the repository at this point in the history
* in progress

* Clean up annotation deletion, switch management and resolve infinite refresh call issue

* Update project.pbxproj

* Make sure closure is called after token refresh and opt out of token calls when request does not need authentication

* Clean up

* Remove unused logic

* Further clean up

* Update TPPBookDetailView.m

* Only attempt to update the token once per account switch
  • Loading branch information
mauricecarrier7 authored Dec 19, 2023
1 parent 821b169 commit 6a6117c
Show file tree
Hide file tree
Showing 7 changed files with 19 additions and 9 deletions.
1 change: 1 addition & 0 deletions Palace/Accounts/Library/Account.swift
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ protocol AccountLogoDelegate: AnyObject {
var homePageUrl: String?
lazy var hasSupportOption = { supportEmail != nil || supportURL != nil }()
weak var logoDelegate: AccountLogoDelegate?
var hasUpdatedToken: Bool = false

let authenticationDocumentUrl:String?
var authenticationDocument:OPDS2AuthenticationDocument? {
Expand Down
1 change: 1 addition & 0 deletions Palace/Accounts/Library/AccountsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ let currentAccountIdentifierKey = "TPPCurrentAccountIdentifier"
}
set {
Log.debug(#file, "Setting currentAccount to <\(newValue?.name ?? "[name N/A]") LibUUID=\(newValue?.uuid ?? "[UUID N/A]")>")
self.currentAccount?.hasUpdatedToken = false;
currentAccountId = newValue?.uuid
TPPErrorLogger.setUserID(TPPUserAccount.sharedAccount().barcode)
NotificationCenter.default.post(name: NSNotification.Name.TPPCurrentAccountDidChange,
Expand Down
2 changes: 1 addition & 1 deletion Palace/Book/UI/TPPBookDetailView.m
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ - (void)setupAutolayoutConstraints
if ([self.book showAudiobookToolbar] && self.isShowingSample) {
[self.audiobookSampleToolbar autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[self.audiobookSampleToolbar autoPinEdgeToSuperviewEdge:ALEdgeRight];
[self.audiobookSampleToolbar autoPinEdgeToSuperviewEdge:ALEdgeBottom];
[self.audiobookSampleToolbar autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset: TabBarHeight];
[self.audiobookSampleToolbar autoSetDimension:ALDimensionHeight toSize:SampleToolbarHeight relation:NSLayoutRelationLessThanOrEqual];
[self.audiobookSampleToolbar autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self];
self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, SampleToolbarHeight, 0);
Expand Down
12 changes: 7 additions & 5 deletions Palace/Network/TPPNetworkExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ extension TPPNetworkExecutor: TPPRequestExecuting {
return URLSessionDataTask()
}

if req.hasRetried {
if req.hasRetried && userAccount.isTokenRefreshRequired() {
let error = createErrorForRetryFailure()
completion(NYPLResult.failure(error, nil))
return URLSessionDataTask()
Expand Down Expand Up @@ -224,8 +224,9 @@ extension TPPNetworkExecutor {
/// the network or from the cache.
@objc func GET(_ reqURL: URL,
cachePolicy: NSURLRequest.CachePolicy = .useProtocolCachePolicy,
useTokenIfAvailable: Bool = true,
completion: @escaping (_ result: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> URLSessionDataTask? {
GET(request: request(for: reqURL), cachePolicy: cachePolicy, completion: completion)
GET(request: request(for: reqURL), cachePolicy: cachePolicy, useTokenIfAvailable: useTokenIfAvailable, completion: completion)
}

/// Performs a GET request using the specified URLRequest
Expand All @@ -235,11 +236,12 @@ extension TPPNetworkExecutor {
/// the network or from the cache.
@objc func GET(request: URLRequest,
cachePolicy: NSURLRequest.CachePolicy = .useProtocolCachePolicy,
useTokenIfAvailable: Bool,
completion: @escaping (_ result: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> URLSessionDataTask? {
if (request.httpMethod != "GET") {
var newRequest = request
newRequest.httpMethod = "GET"
return GET(request: newRequest, cachePolicy: cachePolicy, completion: completion)
return GET(request: newRequest, cachePolicy: cachePolicy, useTokenIfAvailable: useTokenIfAvailable, completion: completion)
}

var updatedReq = request
Expand Down Expand Up @@ -362,7 +364,7 @@ extension TPPNetworkExecutor {
defer { self.isRefreshing = false }

switch result {
case .success:
case .success(let token):
var newTasks = [URLSessionTask]()

self.retryQueue.forEach { oldTask in
Expand All @@ -383,7 +385,7 @@ extension TPPNetworkExecutor {
newTasks.forEach { $0.resume() }
self.retryQueue.removeAll()

completion?(nil)
completion?(token.accessToken)

case .failure(let error):
Log.info(#file, "Failed to refresh token with error: \(error)")
Expand Down
2 changes: 1 addition & 1 deletion Palace/Network/TPPSession.m
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ - (NSURLRequest*)withURL:(NSURL *const)URL
if ([lpe isEqualToString:@"borrow"])
req = [[TPPNetworkExecutor.shared PUT:URL completion:completionWrapper] originalRequest];
else
req = [[TPPNetworkExecutor.shared GET:URL cachePolicy:NSURLRequestUseProtocolCachePolicy completion:completionWrapper] originalRequest];
req = [[TPPNetworkExecutor.shared GET:URL cachePolicy:NSURLRequestUseProtocolCachePolicy useTokenIfAvailable:true completion:completionWrapper] originalRequest];

return req;
}
Expand Down
5 changes: 5 additions & 0 deletions Palace/Notifications/NotificationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ class NotificationService: NSObject, UNUserNotificationCenterDelegate, Messaging
///
/// Update token when user account changes
func updateToken() {
guard !(AccountsManager.shared.currentAccount?.hasUpdatedToken ?? false) else {
return
}

AccountsManager.shared.currentAccount?.hasUpdatedToken = true
AccountsManager.shared.currentAccount?.getProfileDocument { profileDocument in
guard let endpointHref = profileDocument?.linksWith(.deviceRegistration).first?.href,
let endpointUrl = URL(string: endpointHref)
Expand Down
5 changes: 3 additions & 2 deletions Palace/OPDS/TPPOPDSFeed.m
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ + (void)withURL:(NSURL *)URL
}

request = [[[TPPNetworkExecutor shared] GET:URL
cachePolicy:cachePolicy
completion:^(NSData *data, NSURLResponse *response, NSError *error) {
cachePolicy:cachePolicy
useTokenIfAvailable: NO
completion:^(NSData *data, NSURLResponse *response, NSError *error) {

if (error != nil) {
// Note: NYPLNetworkExecutor already logged this error
Expand Down

0 comments on commit 6a6117c

Please sign in to comment.