From 26041a067f5ba2db4f05639f081e005d90c2a2f2 Mon Sep 17 00:00:00 2001 From: Maurice Parker Date: Thu, 7 May 2020 02:33:43 -0500 Subject: [PATCH] Serialize renewing the access token --- .../Reddit/RedditFeedProvider.swift | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/Frameworks/Account/FeedProvider/Reddit/RedditFeedProvider.swift b/Frameworks/Account/FeedProvider/Reddit/RedditFeedProvider.swift index dda9c87b9..b5d8fb3f5 100644 --- a/Frameworks/Account/FeedProvider/Reddit/RedditFeedProvider.swift +++ b/Frameworks/Account/FeedProvider/Reddit/RedditFeedProvider.swift @@ -48,6 +48,7 @@ public final class RedditFeedProvider: FeedProvider { return oauthSwift?.client } + private var renewingAccessToken = false private var rateLimitRemaining: Int? private var rateLimitReset: Date? @@ -324,25 +325,37 @@ private extension RedditFeedProvider { if case .tokenExpired = error { os_log(.debug, log: self.log, "Access token expired, attempting to renew...") + if renewingAccessToken { + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + completion(nil) + } + } + + renewingAccessToken = true + oauthSwift?.renewAccessToken(withRefreshToken: oauthRefreshToken) { [weak self] result in - guard let self = self, let username = self.username else { + guard let strongSelf = self, let username = strongSelf.username else { + self?.renewingAccessToken = false completion(nil) return } switch result { case .success(let tokenSuccess): - self.oauthToken = tokenSuccess.credential.oauthToken - self.oauthRefreshToken = tokenSuccess.credential.oauthRefreshToken + strongSelf.oauthToken = tokenSuccess.credential.oauthToken + strongSelf.oauthRefreshToken = tokenSuccess.credential.oauthRefreshToken do { - try Self.storeCredentials(username: username, oauthToken: self.oauthToken, oauthRefreshToken: self.oauthRefreshToken) - os_log(.debug, log: self.log, "Access token renewed.") + try Self.storeCredentials(username: username, oauthToken: strongSelf.oauthToken, oauthRefreshToken: strongSelf.oauthRefreshToken) + os_log(.debug, log: strongSelf.log, "Access token renewed.") } catch { + strongSelf.renewingAccessToken = false completion(error) return } + strongSelf.renewingAccessToken = false completion(nil) case .failure(let oathError): + strongSelf.renewingAccessToken = false completion(oathError) } }