| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- import Foundation
- 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 {
- @Published private(set) var activity: ActivityNotice?
- @Published private(set) var isRefreshing = false
- @Published private(set) var lastRefreshHadErrors = false
- private(set) var lastActivityFailure: String?
- private let configuration: PlatformAPIConfiguration?
- private let api: PlatformRemoteFetching?
- private let tracking: FacebookTracking
- private let localTrackingConfiguration: FacebookTrackingConfiguration?
- private let isApplicationActive: () -> Bool
- private let now: () -> Date
- private var didLoadInitialCredentials = false
- 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?,
- 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.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 {
- tracking.refreshAuthorization()
- guard isApplicationActive(), !isRefreshing else { return }
- if !didLoadInitialCredentials {
- didLoadInitialCredentials = true
- 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, !needsConfigurationRetry, let lastSuccessfulRefresh,
- now().timeIntervalSince(lastSuccessfulRefresh) < 300 { resumeTrackingIfPossible(); return }
- isRefreshing = true
- defer {
- isRefreshing = false
- if requestAuthorization || deferredTrackingAllowed { resumeTrackingIfPossible() }
- }
- lastRefreshHadErrors = false
- lastActivityFailure = nil
- guard isApplicationActive(), !Task.isCancelled else { return }
- needsConfigurationRetry = true
- let context = PlatformRequestContext(channel: configuration.channel,
- language: language == .english ? "en-US" : "zh-CN",
- region: PlatformRequestContext.deviceRegionCode, timezone: TimeZone.current.identifier)
- let result: Result<PlatformConfigurationResponse, Error>
- do { result = .success(try await api.fetchConfiguration(context: context)) }
- catch { result = .failure(error) }
- guard !Task.isCancelled else { return }
- 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() }
- guard !Task.isCancelled else { return }
- }
- 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)
- }
- }
- 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
- resumeTrackingIfPossible()
- }
- func recordActivityOpened(_ 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 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)" }
- return "invalid-response"
- }
- }
|