|
|
@@ -3,38 +3,43 @@ import Combine
|
|
|
|
|
|
struct ActivityNotice: Identifiable, Equatable {
|
|
|
let url: URL
|
|
|
+ var isSurvey = false
|
|
|
+ var privacyURL: URL? = nil
|
|
|
var id: String { url.absoluteString }
|
|
|
}
|
|
|
|
|
|
@MainActor final class PlatformBootstrap: ObservableObject {
|
|
|
- enum CredentialUpdate: Equatable { case none, unchanged, replaced, unavailable, failed }
|
|
|
@Published private(set) var activity: ActivityNotice?
|
|
|
@Published private(set) var isRefreshing = false
|
|
|
- @Published private(set) var lastCredentialUpdate = CredentialUpdate.none
|
|
|
@Published private(set) var lastRefreshHadErrors = false
|
|
|
- private(set) var lastCredentialFailure: String?
|
|
|
private(set) var lastActivityFailure: String?
|
|
|
private let configuration: PlatformAPIConfiguration?
|
|
|
private let api: PlatformRemoteFetching?
|
|
|
- private let credentialStore: PlatformCredentialStoring
|
|
|
- private let activityStore: PlatformActivityStoring
|
|
|
private let tracking: FacebookTracking
|
|
|
- private let fallback: PlatformCredentials?
|
|
|
+ private let localTrackingConfiguration: FacebookTrackingConfiguration?
|
|
|
private let isApplicationActive: () -> Bool
|
|
|
private let now: () -> Date
|
|
|
private var didLoadInitialCredentials = false
|
|
|
- private var lastRefresh: Date?
|
|
|
- private var presentedURLs = Set<URL>()
|
|
|
- private var pendingCredentialSave: PlatformCredentials?
|
|
|
+ private var lastSuccessfulRefresh: Date?
|
|
|
+ private(set) var needsConfigurationRetry = true
|
|
|
+ @Published private(set) var surveySampling = SurveySampling(nil)
|
|
|
+ @Published private(set) var surveyURL: URL?
|
|
|
+ @Published private(set) var privacyURL = PrivacyPolicyLocation.fromBundle()
|
|
|
+ private let surveyState: SurveyState
|
|
|
+ private let draw: (ClosedRange<Int>) -> Int
|
|
|
private var deferredTrackingAllowed = false
|
|
|
|
|
|
- init(configuration: PlatformAPIConfiguration?, api: PlatformRemoteFetching?, credentialStore: PlatformCredentialStoring,
|
|
|
- activityStore: PlatformActivityStoring, tracking: FacebookTracking, fallback: PlatformCredentials?,
|
|
|
- isApplicationActive: @escaping () -> Bool, now: @escaping () -> Date = Date.init) {
|
|
|
+ init(configuration: PlatformAPIConfiguration?, api: PlatformRemoteFetching?,
|
|
|
+ tracking: FacebookTracking, localTrackingConfiguration: FacebookTrackingConfiguration?,
|
|
|
+ isApplicationActive: @escaping () -> Bool, now: @escaping () -> Date = Date.init,
|
|
|
+ surveyDefaults: UserDefaults = .standard, draw: @escaping (ClosedRange<Int>) -> Int = { Int.random(in: $0) }) {
|
|
|
self.configuration = configuration; self.api = api
|
|
|
- self.credentialStore = credentialStore; self.activityStore = activityStore
|
|
|
- self.tracking = tracking; self.fallback = fallback
|
|
|
+ self.tracking = tracking; self.localTrackingConfiguration = localTrackingConfiguration
|
|
|
self.isApplicationActive = isApplicationActive; self.now = now
|
|
|
+ self.surveyState = SurveyState(defaults: surveyDefaults); self.draw = draw
|
|
|
+ self.surveySampling = surveyState.sampling
|
|
|
+ self.surveyURL = surveyState.surveyURL
|
|
|
+ self.privacyURL = surveyState.privacyURL ?? PrivacyPolicyLocation.fromBundle()
|
|
|
}
|
|
|
|
|
|
func activate(language: AppLanguage, force: Bool = false, requestAuthorization: Bool = true) async {
|
|
|
@@ -42,69 +47,86 @@ struct ActivityNotice: Identifiable, Equatable {
|
|
|
guard isApplicationActive(), !isRefreshing else { return }
|
|
|
if !didLoadInitialCredentials {
|
|
|
didLoadInitialCredentials = true
|
|
|
- let cached = configuration.flatMap { try? credentialStore.load(for: $0.cacheKey) }
|
|
|
- if let selected = cached ?? fallback {
|
|
|
+ if let selected = localTrackingConfiguration {
|
|
|
try? tracking.configure(fbid: selected.fbid, token: selected.token, automaticallyRequestAuthorization: false)
|
|
|
}
|
|
|
}
|
|
|
guard let configuration, let api else { resumeTrackingIfPossible(); return }
|
|
|
- if !force, let lastRefresh, now().timeIntervalSince(lastRefresh) < 300 { resumeTrackingIfPossible(); return }
|
|
|
+ if !force, !needsConfigurationRetry, let lastSuccessfulRefresh,
|
|
|
+ now().timeIntervalSince(lastSuccessfulRefresh) < 300 { resumeTrackingIfPossible(); return }
|
|
|
isRefreshing = true
|
|
|
defer {
|
|
|
isRefreshing = false
|
|
|
if requestAuthorization || deferredTrackingAllowed { resumeTrackingIfPossible() }
|
|
|
}
|
|
|
lastRefreshHadErrors = false
|
|
|
- lastCredentialUpdate = .none
|
|
|
- lastCredentialFailure = nil; lastActivityFailure = nil
|
|
|
+ lastActivityFailure = nil
|
|
|
guard isApplicationActive(), !Task.isCancelled else { return }
|
|
|
- lastRefresh = now()
|
|
|
+ needsConfigurationRetry = true
|
|
|
let context = PlatformRequestContext(channel: configuration.channel,
|
|
|
language: language == .english ? "en-US" : "zh-CN",
|
|
|
region: PlatformRequestContext.deviceRegionCode, timezone: TimeZone.current.identifier)
|
|
|
- async let credentials = Self.attempt { try await api.fetchCredentials(context: context) }
|
|
|
- async let notice = Self.attempt { try await api.fetchActivity(context: context) }
|
|
|
- let credentialResult = await credentials
|
|
|
+ let result: Result<PlatformConfigurationResponse, Error>
|
|
|
+ do { result = .success(try await api.fetchConfiguration(context: context)) }
|
|
|
+ catch { result = .failure(error) }
|
|
|
guard !Task.isCancelled else { return }
|
|
|
- switch credentialResult {
|
|
|
- case .success(.credentials(let received)):
|
|
|
- do {
|
|
|
- if tracking.currentConfiguration?.fbid == received.fbid && tracking.currentConfiguration?.token == received.token {
|
|
|
- lastCredentialUpdate = .unchanged
|
|
|
- } else {
|
|
|
- try tracking.configure(fbid: received.fbid, token: received.token, automaticallyRequestAuthorization: false)
|
|
|
- lastCredentialUpdate = .replaced
|
|
|
- pendingCredentialSave = received
|
|
|
- }
|
|
|
- // Retry persistence if the previous response updated memory but Keychain was unavailable.
|
|
|
- if pendingCredentialSave == received {
|
|
|
- try credentialStore.save(received, for: configuration.cacheKey)
|
|
|
- pendingCredentialSave = nil
|
|
|
- }
|
|
|
- } catch { lastCredentialUpdate = .failed; lastRefreshHadErrors = true; lastCredentialFailure = Self.failureCode(error) }
|
|
|
- case .success(.unavailable): lastCredentialUpdate = .unavailable
|
|
|
- case .failure(let error): lastCredentialUpdate = .failed; lastRefreshHadErrors = true; lastCredentialFailure = Self.failureCode(error)
|
|
|
+ switch result {
|
|
|
+ case .success(let response):
|
|
|
+ lastSuccessfulRefresh = now()
|
|
|
+ needsConfigurationRetry = false
|
|
|
+ surveySampling = response.surveySampling
|
|
|
+ surveyURL = response.surveyURL
|
|
|
+ privacyURL = response.privacyURL ?? PrivacyPolicyLocation.fromBundle()
|
|
|
+ surveyState.saveConfiguration(response)
|
|
|
+ case .failure(let error):
|
|
|
+ let failure = Self.failureCode(error)
|
|
|
+ lastRefreshHadErrors = true
|
|
|
+ lastActivityFailure = failure
|
|
|
}
|
|
|
+
|
|
|
// Initial launch routes first; later foreground refreshes keep the existing ATT flow.
|
|
|
if requestAuthorization && isApplicationActive() { await tracking.requestTrackingAuthorizationIfNeeded() }
|
|
|
- let noticeResult = await notice
|
|
|
guard !Task.isCancelled else { return }
|
|
|
- switch noticeResult {
|
|
|
- case .success(let url?):
|
|
|
- activityStore.save(url, for: configuration.cacheKey)
|
|
|
- presentActivity(url)
|
|
|
- case .success(nil): break
|
|
|
- case .failure(let error):
|
|
|
- lastRefreshHadErrors = true
|
|
|
- lastActivityFailure = Self.failureCode(error)
|
|
|
- if isApplicationActive(), let cached = activityStore.loadOpened(for: configuration.cacheKey) {
|
|
|
- presentActivity(cached)
|
|
|
- }
|
|
|
+ }
|
|
|
+
|
|
|
+ func recoverConfiguration(language: AppLanguage,
|
|
|
+ initialDelayNanoseconds: UInt64 = 1_000_000_000,
|
|
|
+ maximumDelayNanoseconds: UInt64 = 30_000_000_000) async {
|
|
|
+ guard configuration != nil, api != nil else { return }
|
|
|
+ let maximumDelay = max(1, maximumDelayNanoseconds)
|
|
|
+ var delay = min(maximumDelay, max(1, initialDelayNanoseconds))
|
|
|
+ while !Task.isCancelled, isApplicationActive() {
|
|
|
+ await activate(language: language)
|
|
|
+ guard needsConfigurationRetry, !Task.isCancelled, isApplicationActive() else { return }
|
|
|
+ do { try await Task.sleep(nanoseconds: delay) } catch { return }
|
|
|
+ delay = delay > maximumDelay / 2 ? maximumDelay : min(delay * 2, maximumDelay)
|
|
|
}
|
|
|
- // A "0" / invalid result preserves the URL cache, but does not auto-open an old page.
|
|
|
}
|
|
|
|
|
|
- func dismissActivity() { activity = nil; resumeTrackingIfPossible() }
|
|
|
+ func dismissActivity(submission: SurveySubmission? = nil) {
|
|
|
+ if activity?.isSurvey == true { surveyState.finish(submission) }
|
|
|
+ activity = nil
|
|
|
+ resumeTrackingIfPossible()
|
|
|
+ }
|
|
|
+
|
|
|
+ @discardableResult func offerSurveyOnGameStart(language: AppLanguage) -> Bool {
|
|
|
+ guard activity == nil, surveyURL != nil, !surveyState.hasSubmitted,
|
|
|
+ surveySampling.shouldPresent(draw: draw(surveySampling.drawRange)) else { return false }
|
|
|
+ presentSurvey(language: language)
|
|
|
+ return true
|
|
|
+ }
|
|
|
+
|
|
|
+ func presentSurvey(language: AppLanguage) {
|
|
|
+ guard activity == nil, let surveyURL,
|
|
|
+ var parts = URLComponents(url: surveyURL, resolvingAgainstBaseURL: false) else { return }
|
|
|
+ var items = parts.queryItems ?? []
|
|
|
+ items.removeAll { $0.name == "lang" || $0.name == "privacyurl" }
|
|
|
+ items.append(URLQueryItem(name: "lang", value: language.rawValue))
|
|
|
+ items.append(URLQueryItem(name: "privacyurl", value: privacyURL.absoluteString))
|
|
|
+ parts.queryItems = items
|
|
|
+ guard let url = parts.url else { return }
|
|
|
+ activity = ActivityNotice(url: url, isSurvey: true, privacyURL: privacyURL)
|
|
|
+ }
|
|
|
|
|
|
func finishLaunching() {
|
|
|
deferredTrackingAllowed = true
|
|
|
@@ -112,31 +134,25 @@ struct ActivityNotice: Identifiable, Equatable {
|
|
|
}
|
|
|
|
|
|
func recordActivityOpened(_ url: URL) {
|
|
|
- guard let configuration, activity?.url == url, presentedURLs.contains(url) else { return }
|
|
|
- activityStore.markOpened(url, for: configuration.cacheKey)
|
|
|
- }
|
|
|
-
|
|
|
- private func presentActivity(_ url: URL) {
|
|
|
- guard !presentedURLs.contains(url) else { return }
|
|
|
- presentedURLs.insert(url)
|
|
|
- activity = ActivityNotice(url: url)
|
|
|
+ guard activity?.url == url, activity?.isSurvey == true else { return }
|
|
|
+ surveyState.recordOpened()
|
|
|
}
|
|
|
|
|
|
#if DEBUG
|
|
|
func presentPreviewActivity() { activity = ActivityNotice(url: URL(string: "https://example.com")!) }
|
|
|
+ func presentPreviewSurvey() {
|
|
|
+ let url = PrivacyPolicyLocation.defaultURL.deletingLastPathComponent().appendingPathComponent("jokersudoku-survey.html")
|
|
|
+ activity = ActivityNotice(url: url, isSurvey: true, privacyURL: PrivacyPolicyLocation.defaultURL)
|
|
|
+ }
|
|
|
#endif
|
|
|
|
|
|
private func resumeTrackingIfPossible() {
|
|
|
guard !isRefreshing, isApplicationActive() else { return }
|
|
|
tracking.applicationDidBecomeActive()
|
|
|
}
|
|
|
- private nonisolated static func attempt<T: Sendable>(_ operation: @Sendable () async throws -> T) async -> Result<T, Error> {
|
|
|
- do { return .success(try await operation()) } catch { return .failure(error) }
|
|
|
- }
|
|
|
private nonisolated static func failureCode(_ error: Error) -> String {
|
|
|
if let error = error as? URLError { return "URLSession:\(error.code.rawValue)" }
|
|
|
if case NetworkClient.HTTPError.status(let status) = error { return "HTTP:\(status)" }
|
|
|
- if let error = error as? KeychainPlatformCredentialStore.StorageError { return "Keychain:\(error.status)" }
|
|
|
- return "invalid-response-or-storage"
|
|
|
+ return "invalid-response"
|
|
|
}
|
|
|
}
|