Sources/OrgApp/ProStore.swift

213799f3f0792831bdbd707d1f85cb19b614f39f
orgstar/Sources/OrgApp/ProStore.swift

131 lines · 5095 bytes

  1#if canImport(StoreKit)
  2import Foundation
  3import Observation
  4import StoreKit
  5
  6/// orgstar+ from the App Store: a monthly or yearly subscription, or a lifetime purchase. It
  7/// keeps `ProAccess.shared` current; iOS installs from before Pro keep it without buying.
  8@MainActor @Observable
  9public final class ProStore {
 10    public static let shared = ProStore()
 11
 12    public static let monthly = "sh.krz.orgstar.pro.monthly"
 13    public static let yearly = "sh.krz.orgstar.pro.yearly"
 14    public static let lifetime = "sh.krz.orgstar.pro.lifetime"
 15    public static let productIDs = [monthly, yearly, lifetime]
 16
 17    /// Whether downloads from before Pro keep it free. Only on iOS; the Mac App Store app never
 18    /// grandfathers.
 19    public static let grandfathers: Bool = {
 20        #if os(iOS)
 21        true
 22        #else
 23        false
 24        #endif
 25    }()
 26
 27    /// How much a yearly price saves against twelve monthly ones, in whole percent, or nil when
 28    /// it saves nothing.
 29    public nonisolated static func yearlySavings(yearly: Decimal, monthly: Decimal) -> Int? {
 30        guard monthly > 0 else { return nil }
 31        let ratio = NSDecimalNumber(decimal: yearly / (monthly * 12)).doubleValue
 32        let percent = Int((1 - ratio) * 100)
 33        return percent > 0 ? percent : nil
 34    }
 35
 36    public private(set) var products: [Product] = []
 37    public private(set) var activeProductID: String?
 38    public private(set) var busy = false
 39    public var message: String?
 40
 41    @ObservationIgnored private var updates: Task<Void, Never>?
 42
 43    private init() {}
 44
 45    /// Starts listening for transactions and checks what's owned. Call once at launch, and only
 46    /// from App Store builds: it sets the grant from StoreKit alone, replacing a license grant.
 47    public func start() {
 48        guard updates == nil else { return }
 49        updates = Task.detached(priority: .background) {
 50            for await result in Transaction.updates {
 51                guard case .verified(let transaction) = result else { continue }
 52                await transaction.finish()
 53                await ProStore.shared.refresh()
 54            }
 55        }
 56        Task { await refresh() }
 57    }
 58
 59    public func loadProducts() async {
 60        guard products.isEmpty else { return }
 61        do {
 62            let fetched = try await Product.products(for: Self.productIDs)
 63            products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
 64        } catch {
 65            message = "The App Store can't be reached right now."
 66        }
 67    }
 68
 69    /// Sets Pro from the current entitlements, or from the original download predating Pro.
 70    public func refresh() async {
 71        var active: String?
 72        for await result in Transaction.currentEntitlements {
 73            guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
 74                  transaction.revocationDate == nil else { continue }
 75            if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
 76        }
 77        activeProductID = active
 78        if active != nil {
 79            ProAccess.shared.set(.purchase)
 80        } else if await Self.predatesPro() {
 81            ProAccess.shared.set(.grandfathered)
 82        } else if ProAccess.shared.grant != .grandfathered {
 83            // A cached grandfathered grant survives the App Store being unreachable.
 84            ProAccess.shared.set(nil)
 85        }
 86    }
 87
 88    /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
 89    /// Store reports real original versions; sandbox and Xcode always say "1.0".
 90    private static func predatesPro() async -> Bool {
 91        guard grandfathers, case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
 92        return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
 93    }
 94
 95    public func buy(_ product: Product) async {
 96        busy = true
 97        defer { busy = false }
 98        message = nil
 99        do {
100            switch try await product.purchase() {
101            case .success(.verified(let transaction)):
102                await transaction.finish()
103                await refresh()
104            case .success(.unverified):
105                message = "The App Store couldn't verify the purchase."
106            case .pending:
107                message = "The purchase is waiting for approval."
108            case .userCancelled:
109                break
110            @unknown default:
111                break
112            }
113        } catch {
114            message = "The purchase didn't go through. \(error.localizedDescription)"
115        }
116    }
117
118    public func restore() async {
119        busy = true
120        defer { busy = false }
121        message = nil
122        do {
123            try await AppStore.sync()
124            await refresh()
125            if !ProAccess.shared.isUnlocked { message = "No orgstar+ purchase was found for this Apple Account." }
126        } catch {
127            message = "Restore didn't finish. \(error.localizedDescription)"
128        }
129    }
130}
131#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form