Sources/OrgstarMobile/ProStore.swift
207 lines · 8285 bytes
1#if os(iOS)
2import OrgApp
3import StoreKit
4import SwiftUI
5import UIKit
6
7/// orgstar Pro from the App Store: a monthly or yearly subscription, or a lifetime purchase. It
8/// keeps `ProAccess.shared` current; installs from before Pro keep it without buying.
9@MainActor @Observable
10final class ProStore {
11 static let shared = ProStore()
12
13 static let monthly = "sh.krz.orgstar.pro.monthly"
14 static let yearly = "sh.krz.orgstar.pro.yearly"
15 static let lifetime = "sh.krz.orgstar.pro.lifetime"
16 static let productIDs = [monthly, yearly, lifetime]
17
18 private(set) var products: [Product] = []
19 private(set) var activeProductID: String?
20 private(set) var busy = false
21 var message: String?
22
23 @ObservationIgnored private var updates: Task<Void, Never>?
24
25 private init() {}
26
27 /// Starts listening for transactions and checks what's owned. Call once at launch.
28 func start() {
29 guard updates == nil else { return }
30 updates = Task.detached(priority: .background) {
31 for await result in Transaction.updates {
32 guard case .verified(let transaction) = result else { continue }
33 await transaction.finish()
34 await ProStore.shared.refresh()
35 }
36 }
37 Task { await refresh() }
38 }
39
40 func loadProducts() async {
41 guard products.isEmpty else { return }
42 do {
43 let fetched = try await Product.products(for: Self.productIDs)
44 products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
45 } catch {
46 message = "The App Store can't be reached right now."
47 }
48 }
49
50 /// Sets Pro from the current entitlements, or from the original download predating Pro.
51 func refresh() async {
52 var active: String?
53 for await result in Transaction.currentEntitlements {
54 guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
55 transaction.revocationDate == nil else { continue }
56 if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
57 }
58 activeProductID = active
59 if active != nil {
60 ProAccess.shared.set(.purchase)
61 } else if await Self.predatesPro() {
62 ProAccess.shared.set(.grandfathered)
63 } else if ProAccess.shared.grant != .grandfathered {
64 // A cached grandfathered grant survives the App Store being unreachable.
65 ProAccess.shared.set(nil)
66 }
67 }
68
69 /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
70 /// Store reports real original versions; sandbox and Xcode always say "1.0".
71 private static func predatesPro() async -> Bool {
72 guard case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
73 return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
74 }
75
76 func buy(_ product: Product) async {
77 busy = true
78 defer { busy = false }
79 message = nil
80 do {
81 switch try await product.purchase() {
82 case .success(.verified(let transaction)):
83 await transaction.finish()
84 await refresh()
85 case .success(.unverified):
86 message = "The App Store couldn't verify the purchase."
87 case .pending:
88 message = "The purchase is waiting for approval."
89 case .userCancelled:
90 break
91 @unknown default:
92 break
93 }
94 } catch {
95 message = "The purchase didn't go through. \(error.localizedDescription)"
96 }
97 }
98
99 func restore() async {
100 busy = true
101 defer { busy = false }
102 message = nil
103 do {
104 try await AppStore.sync()
105 await refresh()
106 if !ProAccess.shared.isUnlocked { message = "No orgstar Pro purchase was found for this Apple Account." }
107 } catch {
108 message = "Restore didn't finish. \(error.localizedDescription)"
109 }
110 }
111}
112
113/// What Pro includes, its prices, and buying, restoring or managing it.
114struct ProScreen: View {
115 /// The feature that led here, if any.
116 var feature: ProFeature?
117 @Environment(\.dismiss) private var dismiss
118 @State private var managing = false
119 private var store: ProStore { .shared }
120 private var access: ProAccess { .shared }
121
122 var body: some View {
123 Form {
124 Section {
125 VStack(alignment: .leading, spacing: 6) {
126 if let feature, !access.isUnlocked {
127 Text("\(feature.title) needs orgstar Pro.").font(.headline)
128 }
129 Text(status).foregroundStyle(.secondary)
130 }
131 }
132 Section {
133 ForEach(ProFeature.allCases) { Label($0.title, systemImage: $0.systemImage) }
134 } header: {
135 Text("Included in Pro")
136 } footer: {
137 Text("Editing, the agenda, capture, clocking, tables and search stay free.")
138 }
139 if access.grant != .grandfathered, store.activeProductID != ProStore.lifetime {
140 Section {
141 if store.products.isEmpty {
142 ProgressView().frame(maxWidth: .infinity)
143 }
144 ForEach(store.products) { product in
145 Button { Task { await store.buy(product) } } label: {
146 LabeledContent {
147 Text(product.displayPrice + period(product)).monospacedDigit()
148 } label: {
149 Text(product.displayName)
150 if product.id == store.activeProductID { Text("Current plan") }
151 }
152 }
153 .disabled(store.busy || product.id == store.activeProductID)
154 }
155 } footer: {
156 Text("Subscriptions renew automatically until cancelled in your Apple Account settings, at least 24 hours before the period ends.")
157 }
158 }
159 Section {
160 Button("Restore Purchases") { Task { await store.restore() } }.disabled(store.busy)
161 if store.activeProductID == ProStore.monthly || store.activeProductID == ProStore.yearly {
162 Button("Manage Subscription") { managing = true }
163 }
164 Link("Terms of Use", destination: URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!)
165 Link("Privacy Policy", destination: URL(string: "https://krz.sh/privacy/orgstar/")!)
166 }
167 if let message = store.message {
168 Section { Text(message).foregroundStyle(.secondary) }
169 }
170 }
171 .navigationTitle("orgstar Pro")
172 .navigationBarTitleDisplayMode(.inline)
173 .manageSubscriptionsSheet(isPresented: $managing)
174 .task { await store.loadProducts() }
175 }
176
177 private var status: String {
178 switch access.grant {
179 case .grandfathered: "Pro is included: you downloaded orgstar before Pro. Thank you."
180 case .purchase: store.activeProductID == ProStore.lifetime ? "You own orgstar Pro." : "Your orgstar Pro subscription is active."
181 case .license, nil: "Pro adds power features and Apple integrations."
182 }
183 }
184
185 private func period(_ product: Product) -> String {
186 switch product.subscription?.subscriptionPeriod.unit {
187 case .month: " / month"
188 case .year: " / year"
189 default: ""
190 }
191 }
192}
193
194/// The paywall as a sheet, with a close button.
195struct ProSheet: View {
196 let feature: ProFeature
197 @Environment(\.dismiss) private var dismiss
198
199 var body: some View {
200 NavigationStack {
201 ProScreen(feature: feature)
202 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
203 }
204 .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
205 }
206}
207#endif