Sources/OrgApp/ProStore.swift

23c126fd8a5ee1409aa3e324cfaabd3c02ec2e91
orgstar/Sources/OrgApp/ProStore.swift

122 lines · 4655 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    public private(set) var products: [Product] = []
 28    public private(set) var activeProductID: String?
 29    public private(set) var busy = false
 30    public var message: String?
 31
 32    @ObservationIgnored private var updates: Task<Void, Never>?
 33
 34    private init() {}
 35
 36    /// Starts listening for transactions and checks what's owned. Call once at launch, and only
 37    /// from App Store builds: it sets the grant from StoreKit alone, replacing a license grant.
 38    public func start() {
 39        guard updates == nil else { return }
 40        updates = Task.detached(priority: .background) {
 41            for await result in Transaction.updates {
 42                guard case .verified(let transaction) = result else { continue }
 43                await transaction.finish()
 44                await ProStore.shared.refresh()
 45            }
 46        }
 47        Task { await refresh() }
 48    }
 49
 50    public func loadProducts() async {
 51        guard products.isEmpty else { return }
 52        do {
 53            let fetched = try await Product.products(for: Self.productIDs)
 54            products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
 55        } catch {
 56            message = "The App Store can't be reached right now."
 57        }
 58    }
 59
 60    /// Sets Pro from the current entitlements, or from the original download predating Pro.
 61    public func refresh() async {
 62        var active: String?
 63        for await result in Transaction.currentEntitlements {
 64            guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
 65                  transaction.revocationDate == nil else { continue }
 66            if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
 67        }
 68        activeProductID = active
 69        if active != nil {
 70            ProAccess.shared.set(.purchase)
 71        } else if await Self.predatesPro() {
 72            ProAccess.shared.set(.grandfathered)
 73        } else if ProAccess.shared.grant != .grandfathered {
 74            // A cached grandfathered grant survives the App Store being unreachable.
 75            ProAccess.shared.set(nil)
 76        }
 77    }
 78
 79    /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
 80    /// Store reports real original versions; sandbox and Xcode always say "1.0".
 81    private static func predatesPro() async -> Bool {
 82        guard grandfathers, case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
 83        return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
 84    }
 85
 86    public func buy(_ product: Product) async {
 87        busy = true
 88        defer { busy = false }
 89        message = nil
 90        do {
 91            switch try await product.purchase() {
 92            case .success(.verified(let transaction)):
 93                await transaction.finish()
 94                await refresh()
 95            case .success(.unverified):
 96                message = "The App Store couldn't verify the purchase."
 97            case .pending:
 98                message = "The purchase is waiting for approval."
 99            case .userCancelled:
100                break
101            @unknown default:
102                break
103            }
104        } catch {
105            message = "The purchase didn't go through. \(error.localizedDescription)"
106        }
107    }
108
109    public func restore() async {
110        busy = true
111        defer { busy = false }
112        message = nil
113        do {
114            try await AppStore.sync()
115            await refresh()
116            if !ProAccess.shared.isUnlocked { message = "No orgstar+ purchase was found for this Apple Account." }
117        } catch {
118            message = "Restore didn't finish. \(error.localizedDescription)"
119        }
120    }
121}
122#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