Tusker/Tusker/Screens/Preferences/Tip Jar/TipJarView.swift

433 lines
15 KiB
Swift

//
// TipJarView.swift
// Tusker
//
// Created by Shadowfacts on 1/24/23.
// Copyright © 2023 Shadowfacts. All rights reserved.
//
import SwiftUI
import StoreKit
import Combine
struct TipJarView: View {
private static let tipProductIDs = [
"tusker.tip.small",
"tusker.tip.medium",
"tusker.tip.large",
]
private static let supporterProductIDs = [
"tusker.supporter.regular",
]
@State private var isLoaded = false
@State private var tipProducts: [(Product, Bool)] = []
@State private var supporterProducts: [(Product, Bool)] = []
@State private var error: Error?
@State private var showConfetti = false
@State private var updatesObserver: Task<Void, Never>?
@State private var tipButtonWidth: CGFloat?
@State private var supporterButtonWidth: CGFloat?
@State private var supporterStartDate: Date?
@StateObject private var observer = UbiquitousKeyValueStoreObserver()
var body: some View {
ZStack {
Color.appGroupedBackground
.edgesIgnoringSafeArea(.all)
productsView
if showConfetti {
ConfettiView()
.transition(.opacity.animation(.default))
}
}
.navigationTitle("Tip Jar")
.alertWithData("Error", data: $error, actions: { _ in
Button("OK") {}
}, message: { error in
Text(error.localizedDescription)
})
.task {
updatesObserver = Task.detached { @MainActor in
await observeTransactionUpdates()
}
for await verificationResult in Transaction.currentEntitlements {
if case .verified(let transaction) = verificationResult,
Self.supporterProductIDs.contains(transaction.productID),
await transaction.subscriptionStatus?.state == .subscribed {
supporterStartDate = transaction.originalPurchaseDate
break
}
}
do {
let allProducts = try await Product.products(for: Self.tipProductIDs + Self.supporterProductIDs).map { ($0, false) }
tipProducts = allProducts.filter { Self.tipProductIDs.contains($0.0.id) }
tipProducts.sort(by: { $0.0.price < $1.0.price })
supporterProducts = allProducts.filter { Self.supporterProductIDs.contains($0.0.id) }
supporterProducts.sort(by: { $0.0.price < $1.0.price })
isLoaded = true
} catch {
self.error = .fetchingProducts(error)
}
}
.onDisappear {
updatesObserver?.cancel()
}
.onReceive(Just(showConfetti).filter { $0 }.delay(for: .seconds(5), scheduler: DispatchQueue.main)) { _ in
showConfetti = false
}
}
@ViewBuilder
private var productsView: some View {
if isLoaded {
VStack {
if !supporterProducts.isEmpty {
supporterSubscriptions
}
tipPurchases
if let tipStatus {
tipStatus
.multilineTextAlignment(.center)
.padding(.horizontal)
.padding(.top, 16)
Text("Thank you!")
}
}
} else {
ProgressView()
.progressViewStyle(.circular)
}
}
@ViewBuilder
private var supporterSubscriptions: some View {
Text("If you want to contribute Tusker's continued development, you can become a supporter. Supporting Tusker is an auto-renewable monthly subscription.")
.multilineTextAlignment(.center)
.padding(.horizontal)
VStack(alignment: .myAlignment) {
ForEach($supporterProducts, id: \.0.id) { $productAndPurchasing in
TipRow(product: productAndPurchasing.0, buttonWidth: supporterButtonWidth, isPurchasing: $productAndPurchasing.1, showConfetti: $showConfetti)
}
}
.onPreferenceChange(ButtonWidthKey.self) { newValue in
if let supporterButtonWidth {
self.supporterButtonWidth = max(supporterButtonWidth, newValue)
} else {
self.supporterButtonWidth = newValue
}
}
}
@ViewBuilder
private var tipPurchases: some View {
Text("Or, you can choose to make a one-time tip to show your gratitutde or help support the app's development. It is greatly appreciated!")
.multilineTextAlignment(.center)
.padding(.horizontal)
.padding(.top, 16)
VStack(alignment: .myAlignment) {
ForEach($tipProducts, id: \.0.id) { $productAndPurchasing in
TipRow(product: productAndPurchasing.0, buttonWidth: tipButtonWidth, isPurchasing: $productAndPurchasing.1, showConfetti: $showConfetti)
}
}
.onPreferenceChange(ButtonWidthKey.self) { newValue in
if let tipButtonWidth {
self.tipButtonWidth = max(tipButtonWidth, newValue)
} else {
self.tipButtonWidth = newValue
}
}
}
private var tipStatus: Text? {
var text: Text?
if let supporterStartDate {
var months = Calendar.current.dateComponents([.month], from: supporterStartDate, to: Date()).month!
// the user has already paid for n months before the nth month has finished, so reflect that
months += 1
text = Text("You've been a supporter for ^[\(months) months](inflect: true)")
}
if let total = getTotalTips(),
total > 0 {
if let t = text {
text = Text("\(t) and tipped \(total.formatted(tipProducts[0].0.priceFormatStyle))")
} else {
text = Text("You've tipped \(total.formatted(tipProducts[0].0.priceFormatStyle))")
}
}
if let text {
return Text("\(text) 😍")
} else {
return nil
}
}
@MainActor
private func observeTransactionUpdates() async {
for await verificationResult in StoreKit.Transaction.updates {
if let index = tipProducts.firstIndex(where: { $0.0.id == verificationResult.unsafePayloadValue.productID }) {
switch verificationResult {
case .verified(let transaction):
await transaction.finish()
self.tipProducts[index].1 = false
self.showConfetti = true
case .unverified(_, let error):
self.error = .verifyingTransaction(error)
}
} else if let index = supporterProducts.firstIndex(where: { $0.0.id == verificationResult.unsafePayloadValue.productID }) {
switch verificationResult {
case .verified(let transaction):
await transaction.finish()
self.supporterProducts[index].1 = false
self.showConfetti = true
self.supporterStartDate = transaction.originalPurchaseDate
case .unverified(_, let error):
self.error = .verifyingTransaction(error)
}
}
}
}
}
extension TipJarView {
enum Error {
case fetchingProducts(Swift.Error)
case purchasing(Swift.Error)
case verifyingTransaction(VerificationResult<StoreKit.Transaction>.VerificationError)
var localizedDescription: String {
switch self {
case .fetchingProducts(let underlying):
return "Error fetching products: \(String(describing: underlying))"
case .purchasing(let underlying):
return "Error purchasing: \(String(describing: underlying))"
case .verifyingTransaction(let underlying):
return "Error verifying transaction: \(String(describing: underlying))"
}
}
}
}
private struct TipRow: View {
let product: Product
let buttonWidth: CGFloat?
@Binding var isPurchasing: Bool
@Binding var showConfetti: Bool
@State private var error: TipJarView.Error?
#if os(visionOS)
@Environment(\.purchase) private var purchase
#endif
var body: some View {
HStack {
Text(product.displayName)
.alignmentGuide(.myAlignment, computeValue: { context in context[.trailing] })
if let subscription = product.subscription {
SubscriptionButton(product: product, subscriptionInfo: subscription, isPurchasing: $isPurchasing, buttonWidth: buttonWidth, purchase: purchase)
} else {
tipButton
}
}
.alertWithData("Error", data: $error) { _ in
Button("OK") {}
} message: { error in
Text(error.localizedDescription)
}
}
private var tipButton: some View {
Button {
Task {
await self.purchase()
}
} label: {
if isPurchasing {
ProgressView()
.progressViewStyle(.circular)
.frame(width: buttonWidth, alignment: .center)
} else {
Text(product.displayPrice)
.background(GeometryReader { proxy in
Color.clear
.preference(key: ButtonWidthKey.self, value: proxy.size.width)
})
.frame(width: buttonWidth)
}
}
.buttonStyle(.borderedProminent)
}
@MainActor
private func purchase() async {
isPurchasing = true
let result: Product.PurchaseResult
do {
#if os(visionOS)
result = try await purchase(product)
#else
result = try await product.purchase()
#endif
} catch {
self.error = .purchasing(error)
isPurchasing = false
return
}
let transaction: StoreKit.Transaction
switch result {
case .success(let verificationResult):
switch verificationResult {
case .unverified(_, let reason):
isPurchasing = false
error = .verifyingTransaction(reason)
return
case .verified(let t):
transaction = t
}
case .userCancelled:
isPurchasing = false
return
case .pending:
// pending transactions may still be completed, but we won't update UI in response to them
isPurchasing = false
return
@unknown default:
isPurchasing = false
return
}
await transaction.finish()
isPurchasing = false
showConfetti = true
addToTotalTips(amount: product.price)
}
}
private struct SubscriptionButton: View {
let product: Product
let subscriptionInfo: Product.SubscriptionInfo
@Binding var isPurchasing: Bool
let buttonWidth: CGFloat?
let purchase: () async -> Void
@State private var hasPurchased = false
@State private var showManageSheet = false
var body: some View {
Button {
if #available(iOS 17.0, *), hasPurchased {
showManageSheet = true
} else {
Task {
await purchase()
await updateHasPurchased()
}
}
} label: {
if #available(iOS 17.0, *), hasPurchased {
Text("Manage")
} else if isPurchasing {
ProgressView()
.progressViewStyle(.circular)
.frame(width: buttonWidth, alignment: .center)
} else {
let per: String = if subscriptionInfo.subscriptionPeriod.value == 1, subscriptionInfo.subscriptionPeriod.unit == .month {
"mo"
} else {
subscriptionInfo.subscriptionPeriod.formatted(product.subscriptionPeriodFormatStyle)
}
Text("\(product.displayPrice)/\(per)")
.background(GeometryReader { proxy in
Color.clear
.preference(key: ButtonWidthKey.self, value: proxy.size.width)
})
.frame(width: buttonWidth)
}
}
.buttonStyle(.borderedProminent)
.task {
await updateHasPurchased()
}
.onChange(of: showManageSheet) {
if !$0 {
Task {
await updateHasPurchased()
}
}
}
.manageSubscriptionsSheetIfAvailable(isPresented: $showManageSheet, subscriptionGroupID: subscriptionInfo.subscriptionGroupID)
}
private func updateHasPurchased() async {
switch await Transaction.currentEntitlement(for: product.id) {
case .verified(let transaction):
let state = await transaction.subscriptionStatus?.state
hasPurchased = state == .subscribed
default:
break
}
}
}
extension HorizontalAlignment {
private enum MyTrailing: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.bottom]
}
}
fileprivate static let myAlignment = HorizontalAlignment(MyTrailing.self)
}
private struct ButtonWidthKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
private func getTotalTips() -> Decimal? {
if let data = NSUbiquitousKeyValueStore.default.data(forKey: "totalTips"),
let existing = try? PropertyListDecoder().decode(Decimal.self, from: data) {
return existing
} else {
return nil
}
}
private func addToTotalTips(amount: Decimal) {
let newAmount = amount + (getTotalTips() ?? 0)
if let data = try? PropertyListEncoder().encode(newAmount) {
NSUbiquitousKeyValueStore.default.set(data, forKey: "totalTips")
}
}
private class UbiquitousKeyValueStoreObserver: ObservableObject {
private var cancellable: AnyCancellable?
init() {
self.cancellable = NotificationCenter.default.publisher(for: NSUbiquitousKeyValueStore.didChangeExternallyNotification)
.receive(on: DispatchQueue.main)
.sink { [unowned self] _ in
self.objectWillChange.send()
}
}
}
private extension View {
@available(iOS, obsoleted: 17.0)
@ViewBuilder
func manageSubscriptionsSheetIfAvailable(isPresented: Binding<Bool>, subscriptionGroupID: String) -> some View {
if #available(iOS 17.0, *) {
self.manageSubscriptionsSheet(isPresented: isPresented, subscriptionGroupID: subscriptionGroupID)
} else {
self
}
}
}