2
0

UTMDonateView.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //
  2. // Copyright © 2024 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import SwiftUI
  17. import StoreKit
  18. struct UTMDonateView: View {
  19. @Environment(\.presentationMode) var presentationMode
  20. private var appIcon: String? {
  21. guard let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any],
  22. let primaryIcon = icons["CFBundlePrimaryIcon"] as? [String: Any],
  23. let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String],
  24. let iconFileName = iconFiles.last else {
  25. return nil
  26. }
  27. return iconFileName
  28. }
  29. var body: some View {
  30. NavigationView {
  31. VStack {
  32. if let appIcon = appIcon, let image = UIImage(named: appIcon) {
  33. Image(uiImage: image)
  34. .resizable()
  35. .aspectRatio(contentMode: .fit)
  36. .clipShape(RoundedRectangle(cornerRadius: 12.632, style: .continuous))
  37. .frame(width: 72, height: 72)
  38. }
  39. Text("Your support is the driving force that helps UTM stay independent. Your contribution, no matter the size, makes a significant difference. It enables us to develop new features and maintain existing ones. Thank you for considering a donation to support us.")
  40. .padding()
  41. if #available(iOS 15, *) {
  42. StoreView()
  43. } else {
  44. List {
  45. Link("GitHub Sponsors", destination: URL(string: "https://github.com/sponsors/utmapp")!)
  46. }
  47. }
  48. }.navigationTitle("Support UTM")
  49. .navigationBarTitleDisplayMode(.inline)
  50. .toolbar {
  51. ToolbarItem(placement: .topBarTrailing) {
  52. Button("Close") {
  53. presentationMode.wrappedValue.dismiss()
  54. }
  55. }
  56. }
  57. }.navigationViewStyle(.stack)
  58. }
  59. }
  60. @available(iOS 15, *)
  61. private struct StoreView: View {
  62. @StateObject private var store = UTMDonateStore()
  63. var body: some View {
  64. if !store.isLoaded {
  65. ProgressView()
  66. Spacer()
  67. } else {
  68. List {
  69. if !store.consumables.isEmpty {
  70. Section("One Time Donation") {
  71. ForEach(store.consumables) { item in
  72. ListCellView(store: store, product: item)
  73. }
  74. }
  75. .listStyle(.grouped)
  76. }
  77. if !store.subscriptions.isEmpty {
  78. Section("Recurring Donation") {
  79. ForEach(store.subscriptions) { item in
  80. ListCellView(store: store, product: item)
  81. }
  82. Link("Manage Subscriptions…", destination: URL(string: "itms-apps://apps.apple.com/account/subscriptions")!)
  83. }
  84. .listStyle(.grouped)
  85. }
  86. if store.consumables.isEmpty && store.subscriptions.isEmpty {
  87. Link("GitHub Sponsors", destination: URL(string: "https://github.com/sponsors/utmapp")!)
  88. } else if !store.subscriptions.isEmpty {
  89. Button("Restore Purchases") {
  90. Task {
  91. try? await AppStore.sync()
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }
  98. }
  99. @available(iOS 15, *)
  100. private struct ListCellView: View {
  101. @ObservedObject var store: UTMDonateStore
  102. @State var isPurchased: Bool = false
  103. @State var errorTitle = ""
  104. @State var isShowingError: Bool = false
  105. @State var isLoaded: Bool = false
  106. #if os(visionOS)
  107. @Environment(\.purchase) var purchase
  108. #endif
  109. let product: Product
  110. let purchasingEnabled: Bool
  111. var systemImage: String? {
  112. store.productImages[product.id]
  113. }
  114. init(store: UTMDonateStore, product: Product, purchasingEnabled: Bool = true) {
  115. self.store = store
  116. self.product = product
  117. self.purchasingEnabled = purchasingEnabled
  118. }
  119. var body: some View {
  120. HStack {
  121. Image(systemName: systemImage ?? "heart.fill")
  122. .font(.system(size: 36))
  123. .frame(width: 48, height: 48)
  124. .padding(.trailing, 20)
  125. if purchasingEnabled {
  126. productDetail
  127. Spacer()
  128. buyButton
  129. .buttonStyle(BuyButtonStyle(isPurchased: isPurchased))
  130. .disabled(isPurchased)
  131. } else {
  132. productDetail
  133. }
  134. }
  135. .alert(isPresented: $isShowingError, content: {
  136. Alert(title: Text(errorTitle), message: nil, dismissButton: .default(Text("OK")))
  137. })
  138. }
  139. @ViewBuilder
  140. var productDetail: some View {
  141. VStack(alignment: .leading) {
  142. Text(product.displayName)
  143. .bold()
  144. Text(product.description)
  145. }
  146. }
  147. func subscribeButton(_ subscription: Product.SubscriptionInfo) -> some View {
  148. let unit: String
  149. let plural = 1 < subscription.subscriptionPeriod.value
  150. switch subscription.subscriptionPeriod.unit {
  151. case .day:
  152. unit = plural ? String.localizedStringWithFormat(NSLocalizedString("%d days", comment: "UTMDonateView"), subscription.subscriptionPeriod.value) : NSLocalizedString("day", comment: "UTMDonateView")
  153. case .week:
  154. unit = plural ? String.localizedStringWithFormat(NSLocalizedString("%d weeks", comment: "UTMDonateView"), subscription.subscriptionPeriod.value) : NSLocalizedString("week", comment: "UTMDonateView")
  155. case .month:
  156. unit = plural ? String.localizedStringWithFormat(NSLocalizedString("%d months", comment: "UTMDonateView"), subscription.subscriptionPeriod.value) : NSLocalizedString("month", comment: "UTMDonateView")
  157. case .year:
  158. unit = plural ? String.localizedStringWithFormat(NSLocalizedString("%d years", comment: "UTMDonateView"), subscription.subscriptionPeriod.value) : NSLocalizedString("year", comment: "UTMDonateView")
  159. @unknown default:
  160. unit = NSLocalizedString("period", comment: "UTMDonateView")
  161. }
  162. return VStack {
  163. Text(product.displayPrice)
  164. .foregroundColor(.white)
  165. .bold()
  166. .padding(EdgeInsets(top: -4.0, leading: 0.0, bottom: -8.0, trailing: 0.0))
  167. Divider()
  168. .background(Color.white)
  169. Text(unit)
  170. .foregroundColor(.white)
  171. .font(.system(size: 12))
  172. .padding(EdgeInsets(top: -8.0, leading: 0.0, bottom: -4.0, trailing: 0.0))
  173. }
  174. }
  175. var buyButton: some View {
  176. Button(action: {
  177. Task {
  178. await buy()
  179. }
  180. }) {
  181. if !isLoaded {
  182. ProgressView()
  183. .tint(.white)
  184. } else if isPurchased {
  185. Text(Image(systemName: "checkmark"))
  186. .bold()
  187. .foregroundColor(.white)
  188. } else {
  189. if let subscription = product.subscription {
  190. subscribeButton(subscription)
  191. } else {
  192. Text(product.displayPrice)
  193. .foregroundColor(.white)
  194. .bold()
  195. }
  196. }
  197. }
  198. .onAppear {
  199. Task {
  200. isPurchased = (try? await store.isPurchased(product)) ?? false
  201. isLoaded = true
  202. }
  203. }
  204. .onChange(of: store.purchasedSubscriptions) { _ in
  205. Task {
  206. isPurchased = (try? await store.isPurchased(product)) ?? false
  207. }
  208. }
  209. }
  210. func buy() async {
  211. do {
  212. if try await store.purchase(with: {
  213. #if os(visionOS)
  214. try await purchase(product)
  215. #else
  216. try await product.purchase()
  217. #endif
  218. }) != nil {
  219. withAnimation {
  220. isPurchased = true
  221. }
  222. }
  223. } catch UTMDonateStore.StoreError.failedVerification {
  224. errorTitle = NSLocalizedString("Your purchase could not be verified by the App Store.", comment: "UTMDonateView")
  225. isShowingError = true
  226. } catch {
  227. logger.error("Failed purchase for \(product.id): \(error)")
  228. }
  229. }
  230. }
  231. private struct BuyButtonStyle: ButtonStyle {
  232. let isPurchased: Bool
  233. init(isPurchased: Bool = false) {
  234. self.isPurchased = isPurchased
  235. }
  236. func makeBody(configuration: Self.Configuration) -> some View {
  237. var bgColor: Color = isPurchased ? Color.green : Color.blue
  238. bgColor = configuration.isPressed ? bgColor.opacity(0.7) : bgColor.opacity(1)
  239. return configuration.label
  240. .frame(width: 50)
  241. .padding(10)
  242. .background(bgColor)
  243. .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
  244. .scaleEffect(configuration.isPressed ? 0.9 : 1.0)
  245. }
  246. }
  247. #Preview {
  248. UTMDonateView()
  249. }