Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

simplye-391 #29

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Palace/Accounts/Library/Account+profileDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ extension Account {

func getProfileDocument(completion: @escaping (_ profileDocument: UserProfileDocument?) -> Void) {
guard let profileHref = self.details?.userProfileUrl,
let profileUrl = URL(string: profileHref)
let profileUrl = URL(string: profileHref),
let _ = TPPUserAccount.sharedAccount().authToken
else {
// Can be a normal situation, no active user account
completion(nil)
Expand Down
6 changes: 6 additions & 0 deletions Palace/Book/Models/TPPBookRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,13 +228,19 @@ class TPPBookRegistry: NSObject, TPPBookRegistrySyncing {
guard let loansUrl = AccountsManager.shared.currentAccount?.loansUrl else {
return
}
// dont allow empty token to sync
guard let _ = TPPUserAccount.sharedAccount().authToken else {
return
}

if syncUrl == loansUrl {
print("book registry skipped sync")
return
}
state = .syncing
syncUrl = loansUrl
print("book registry syncUrl 1: \(syncUrl)")

TPPOPDSFeed.withURL(loansUrl, shouldResetCache: true) { feed, errorDocument in
print("book registry withURL!")
DispatchQueue.main.async {
Expand Down
6 changes: 3 additions & 3 deletions Palace/Book/UI/TPPBookDetailView.m
Original file line number Diff line number Diff line change
Expand Up @@ -382,11 +382,11 @@ - (void)createFooterLabels
: NSLocalizedString(@"Categories", nil))]
: nil;

NSString *const bookLanguageKeyString = NSLocalizedString(@"Language", "");
NSString *const bookLanguageKeyString = [NSString stringWithFormat:@"%@: ",NSLocalizedString(@"Language", "")];

NSString *const bookFormatKeyString = NSLocalizedString(@"Book format:", nil);
NSString *const bookFormatKeyString = [NSString stringWithFormat:@"%@: ",NSLocalizedString(@"Book format", nil)];

NSString *const isbnKeyString = NSLocalizedString(@"ISBN", nil);
NSString *const isbnKeyString = [NSString stringWithFormat:@"%@: ",NSLocalizedString(@"ISBN", nil)];

NSString *const narratorsKeyString =
self.book.narrators ? [NSString stringWithFormat:@"%@: ", NSLocalizedString(@"Narrators", nil)] : nil;
Expand Down
102 changes: 75 additions & 27 deletions Palace/Network/TPPNetworkExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,51 @@ enum NYPLResult<SuccessInfo> {

extension TPPNetworkExecutor: TPPRequestExecuting {

func handleUnauth( _ req: URLRequest, _ origResult: NYPLResult<Data>, completion: @escaping (_: NYPLResult<Data>) -> Void){
var updatedRequest = req
if let token = TPPUserAccount.sharedAccount().authToken {
self.authenticateWithToken(token) { status in
if status == 401 {
// User needs to login again, remove user's credentials.
TPPUserAccount.sharedAccount().removeAll()

EkirjastoLoginViewController.show {
if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequestWithToken(updatedRequest, completion: completion)
}else{
completion(origResult)
}

}
}else if status == 200 {

if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequestWithToken(updatedRequest, completion: completion)
}else{
completion(origResult)
}
}else {
completion(origResult)
}
}
}else{

EkirjastoLoginViewController.show {
if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequestWithToken(updatedRequest, completion: completion)
}else{
completion(origResult)
}

}

//completion(origResult)
}

}

@discardableResult
func executeRequestWithToken(_ req: URLRequest, completion: @escaping (_: NYPLResult<Data>) -> Void) -> URLSessionDataTask {
Expand All @@ -85,32 +130,7 @@ extension TPPNetworkExecutor: TPPRequestExecuting {
updatedRequest.hasRetried = true
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 401 {
self.authenticateWithToken(TPPUserAccount.sharedAccount().authToken!) { status in
if status == 401 {
// User needs to login again, remove user's credentials.
TPPUserAccount.sharedAccount().removeAll()

EkirjastoLoginViewController.show {
if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequestWithToken(updatedRequest, completion: completion)
}else{
completion(result)
}

}
}else if status == 200 {

if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequestWithToken(updatedRequest, completion: completion)
}else{
completion(result)
}
}else {
completion(result)
}
}
self.handleUnauth(updatedRequest, result, completion: completion)
}else {
completion(result)
}
Expand All @@ -119,7 +139,20 @@ extension TPPNetworkExecutor: TPPRequestExecuting {
}
}

case .success(_, _):
case .success(_, let response):

if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 401 {
if req.hasRetried {
completion(result)
}else{
var updatedRequest = req
updatedRequest.hasRetried = true
self.handleUnauth(updatedRequest, result, completion: completion)
}
}
}

completion(result)
}
}
Expand Down Expand Up @@ -191,12 +224,27 @@ extension TPPNetworkExecutor: TPPRequestExecuting {
}else{
completion(result)
}
}else if case .success(_, let response) = result {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 401 && !req.hasRetried {
var updatedRequest = req
updatedRequest.hasRetried = true
print("successful unauth for: \(req.url?.absoluteString)")
self.handleUnauth(updatedRequest, result, completion: completion)
}else{
completion(result)
}
}else{
completion(result)
}

}else {
completion(result)
}

})
}

} else {
handleTokenRefresh(for: req, completion: completion)
}
Expand Down
13 changes: 12 additions & 1 deletion Palace/OnboardingScreens/TPPOnboardingView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ struct TPPOnboardingView: View {
}
}

static var active = false

// dismiss handler
var dismissView: (() -> Void)

Expand All @@ -53,7 +55,7 @@ struct TPPOnboardingView: View {
var body: some View {
ZStack(alignment: .top) {
if(showLoginView) {
EkirjastoLoginView(dismissView: self.dismissView)
EkirjastoLoginView(dismissView: self.onDismiss)
} else {
onboardingSlides()
pagerDots()
Expand All @@ -62,8 +64,17 @@ struct TPPOnboardingView: View {
}
.edgesIgnoringSafeArea(.all)
.statusBar(hidden: true)
.onAppear{
TPPOnboardingView.active = true
}
}

private func onDismiss(){
TPPOnboardingView.active = false
dismissView()
}


@ViewBuilder
private func onboardingSlides() -> some View {
GeometryReader { geometry in
Expand Down
11 changes: 9 additions & 2 deletions Palace/Views/EkirjastoLoginView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ struct EkirjastoLoginView: View {

var dismissView: (() -> Void)?
var navController: UINavigationController? = nil
static var active = false


@State var authDoc : OPDS2AuthenticationDocument? = nil
Expand Down Expand Up @@ -40,10 +41,11 @@ struct EkirjastoLoginView: View {
}
}.navigationViewStyle(.stack)
.onAppear{
EkirjastoLoginView.active = true
AccountsManager.fetchAuthDoc { doc in
authDoc = doc
}
}
}
}

@ViewBuilder func buttonsSection() -> some View{
Expand All @@ -52,6 +54,7 @@ struct EkirjastoLoginView: View {

NavigationLink(destination: {
SuomiIdentificationWebView(closeWebView: {
EkirjastoLoginView.active = false
self.dismissView?()
}, authenticationDocument: authDoc)
}, label: {
Expand All @@ -72,6 +75,7 @@ struct EkirjastoLoginView: View {
if let token = loginToken, !token.isEmpty{
TPPNetworkExecutor.shared.authenticateWithToken(token) { status in
DispatchQueue.main.async {
EkirjastoLoginView.active = false
self.dismissView?()
}
}
Expand All @@ -89,7 +93,10 @@ struct EkirjastoLoginView: View {
.background(Color("ColorEkirjastoLightestGreen"))


Button(action: {self.dismissView?()}) {
Button(action: {
EkirjastoLoginView.active = false
self.dismissView?()
}) {
Text(DisplayStrings.continueWithoutSigning).foregroundColor(Color("ColorEkirjastoButtonTextWithBackground"))
Image("ArrowRight")
.padding(.leading, 10)
Expand Down
34 changes: 32 additions & 2 deletions Palace/Views/EkirjastoLoginViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import Foundation
class EkirjastoLoginViewController : UIHostingController<EkirjastoLoginView>{

private var navController: UINavigationController?
//put inside a mutex?
private static var savedHandlers: [(() -> Void)] = []
private static var showLock = NSLock()

init(rootView: EkirjastoLoginView, navController: UINavigationController?) {
self.navController = navController
Expand Down Expand Up @@ -54,11 +57,25 @@ class EkirjastoLoginViewController : UIHostingController<EkirjastoLoginView>{
let vc = TPPRootTabBarController.shared()
var loginView : EkirjastoLoginViewController?


if Thread.isMainThread{

if EkirjastoLoginView.active || TPPOnboardingView.active {
if let handler = dismissHandler {
savedHandlers.append(handler)
}
return
}

loginView = makeSwiftUIView(dismissHandler: {
loginView?.dismiss(animated: true)

dismissHandler?()
if savedHandlers.count > 0 {
for var handler in savedHandlers {
handler()
}
savedHandlers.removeAll()
}
})
if let nc = loginView?.getNavController() {
nc.pushViewController(loginView!, animated: true)
Expand All @@ -68,16 +85,29 @@ class EkirjastoLoginViewController : UIHostingController<EkirjastoLoginView>{

}else{
DispatchSerialQueue.main.async {

if EkirjastoLoginView.active || TPPOnboardingView.active {
if let handler = dismissHandler {
savedHandlers.append(handler)
}
return
}

loginView = makeSwiftUIView(dismissHandler: {
loginView?.dismiss(animated: true)
dismissHandler?()
if savedHandlers.count > 0 {
for var handler in savedHandlers {
handler()
}
savedHandlers.removeAll()
}
})
if let nc = loginView?.getNavController() {
nc.pushViewController(loginView!, animated: true)
}else{
vc?.safelyPresentViewController(loginView, animated: true, completion: nil)
}
//vc?.safelyPresentViewController(loginView, animated: true, completion: nil)
}
}

Expand Down
Loading