Sources/OrgApp/ProStore.swift
160 lines · 6362 bytes
9 symbols in this file
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 private(set) var isLoading = false
40 public var message: String?
41
42 @ObservationIgnored private var updates: Task<Void, Never>?
43 @ObservationIgnored private var expiry: Task<Void, Never>?
44
45 private init() {}
46
47 /// Starts listening for transactions and checks what's owned. Call once at launch, and only
48 /// from App Store builds: it sets the grant from StoreKit alone, replacing a license grant.
49 public func start() {
50 guard updates == nil else { return }
51 updates = Task.detached(priority: .background) {
52 for await result in Transaction.updates {
53 guard case .verified(let transaction) = result else { continue }
54 await transaction.finish()
55 await ProStore.shared.refresh()
56 }
57 }
58 Task { await refresh() }
59 }
60
61 public func loadProducts() async {
62 guard products.count < Self.productIDs.count, !isLoading else { return }
63 isLoading = true
64 message = nil
65 defer { isLoading = false }
66 do {
67 let fetched = try await Product.products(for: Self.productIDs)
68 products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
69 if products.count < Self.productIDs.count {
70 message = String(localized: "Some plans aren't available from the App Store right now.")
71 }
72 } catch {
73 message = String(localized: "The App Store can't be reached right now.")
74 }
75 }
76
77 /// Sets Pro from the current entitlements, or from the original download predating Pro.
78 public func refresh() async {
79 var active: String?
80 var expires: Date?
81 for await result in Transaction.currentEntitlements {
82 guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
83 transaction.revocationDate == nil else { continue }
84 if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
85 if let date = transaction.expirationDate { expires = max(expires ?? date, date) }
86 }
87 activeProductID = active
88 #if os(macOS)
89 refresh(at: active == Self.lifetime ? nil : expires)
90 #endif
91 if active != nil {
92 ProAccess.shared.set(.purchase)
93 } else if await Self.predatesPro() {
94 ProAccess.shared.set(.grandfathered)
95 } else if ProAccess.shared.grant != .grandfathered {
96 // A cached grandfathered grant survives the App Store being unreachable.
97 ProAccess.shared.set(nil)
98 }
99 }
100
101 #if os(macOS)
102 /// Checks again when a subscription runs out, since StoreKit sends no update for a lapse and
103 /// the Mac app can stay open for weeks.
104 private func refresh(at date: Date?) {
105 expiry?.cancel()
106 expiry = nil
107 guard let date, date > .now else { return }
108 expiry = Task {
109 try? await Task.sleep(for: .seconds(date.timeIntervalSinceNow + 1))
110 guard !Task.isCancelled else { return }
111 // A new task, so cancelling this one can't cut the entitlement check short.
112 Task { await ProStore.shared.refresh() }
113 }
114 }
115 #endif
116
117 /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
118 /// Store reports real original versions; sandbox and Xcode always say "1.0".
119 private static func predatesPro() async -> Bool {
120 guard grandfathers, case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
121 return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
122 }
123
124 public func buy(_ product: Product) async {
125 busy = true
126 defer { busy = false }
127 message = nil
128 do {
129 switch try await product.purchase() {
130 case .success(.verified(let transaction)):
131 await transaction.finish()
132 await refresh()
133 case .success(.unverified):
134 message = "The App Store couldn't verify the purchase."
135 case .pending:
136 message = "The purchase is waiting for approval."
137 case .userCancelled:
138 break
139 @unknown default:
140 break
141 }
142 } catch {
143 message = "The purchase didn't go through. \(error.localizedDescription)"
144 }
145 }
146
147 public func restore() async {
148 busy = true
149 defer { busy = false }
150 message = nil
151 do {
152 try await AppStore.sync()
153 await refresh()
154 if !ProAccess.shared.isUnlocked { message = "No orgstar+ purchase was found for this Apple Account." }
155 } catch {
156 message = "Restore didn't finish. \(error.localizedDescription)"
157 }
158 }
159}
160#endif