passepartout-apple/Passepartout/App/Managers/ProductManager.swift

318 lines
9.6 KiB
Swift
Raw Normal View History

//
// ProductManager.swift
// Passepartout
//
// Created by Davide De Rosa on 4/6/19.
2023-03-17 15:56:19 +00:00
// Copyright (c) 2023 Davide De Rosa. All rights reserved.
//
// https://github.com/passepartoutvpn
//
// This file is part of Passepartout.
//
// Passepartout is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Passepartout is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Passepartout. If not, see <http://www.gnu.org/licenses/>.
//
import Combine
import Foundation
import Kvitto
2022-06-23 21:31:01 +00:00
import PassepartoutLibrary
import StoreKit
2023-05-24 16:19:47 +00:00
final class ProductManager: NSObject, ObservableObject {
2022-04-12 13:09:14 +00:00
enum AppType: Int {
case freemium = 0
case beta = 1
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
case fullVersion = 2
}
2023-03-17 20:55:47 +00:00
let appType: AppType
2023-03-17 20:55:47 +00:00
let buildProducts: BuildProducts
2023-03-17 20:55:47 +00:00
let didRefundProducts = PassthroughSubject<Void, Never>()
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
@Published private(set) var isRefreshingProducts = false
2022-04-12 13:09:14 +00:00
@Published private(set) var products: [SKProduct]
//
2023-03-17 20:55:47 +00:00
private let inApp: InApp<LocalProduct>
2023-03-17 20:55:47 +00:00
private var purchasedAppBuild: Int?
2023-03-17 20:55:47 +00:00
private var purchasedFeatures: Set<LocalProduct>
2023-03-17 20:55:47 +00:00
private var purchaseDates: [LocalProduct: Date]
2023-03-17 20:55:47 +00:00
private var cancelledPurchases: Set<LocalProduct>? {
willSet {
guard cancelledPurchases != nil else {
return
}
guard let newCancelledPurchases = newValue, newCancelledPurchases != cancelledPurchases else {
pp_log.debug("No purchase was refunded")
return
}
detectRefunds(newCancelledPurchases)
}
}
2023-03-17 20:55:47 +00:00
private var refreshRequest: SKReceiptRefreshRequest?
2023-03-17 20:55:47 +00:00
init(appType: AppType, buildProducts: BuildProducts) {
self.appType = appType
self.buildProducts = buildProducts
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
products = []
inApp = InApp()
purchasedAppBuild = nil
purchasedFeatures = []
purchaseDates = [:]
cancelledPurchases = nil
2023-03-17 20:55:47 +00:00
super.init()
reloadReceipt()
SKPaymentQueue.default().add(self)
2022-04-12 13:09:14 +00:00
refreshProducts()
}
2023-03-17 20:55:47 +00:00
deinit {
SKPaymentQueue.default().remove(self)
}
2023-03-17 20:55:47 +00:00
func canMakePayments() -> Bool {
SKPaymentQueue.canMakePayments()
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func refreshProducts() {
let ids = LocalProduct.all
guard !ids.isEmpty else {
return
}
guard products.isEmpty else {
pp_log.debug("In-app products already available, not refreshing")
return
}
2022-04-12 13:09:14 +00:00
isRefreshingProducts = true
inApp.requestProducts(withIdentifiers: ids, completionHandler: { _ in
pp_log.debug("In-app products: \(self.inApp.products.map { $0.productIdentifier })")
2022-04-12 13:09:14 +00:00
self.products = self.inApp.products
self.isRefreshingProducts = false
}, failureHandler: {
2022-04-12 13:09:14 +00:00
pp_log.warning("Unable to list products: \($0)")
self.isRefreshingProducts = false
})
}
2022-04-12 13:09:14 +00:00
func product(withIdentifier identifier: LocalProduct) -> SKProduct? {
2022-09-04 18:09:31 +00:00
inApp.product(withIdentifier: identifier)
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func featureProducts(including: [LocalProduct]) -> [SKProduct] {
2022-09-04 18:09:31 +00:00
inApp.products.filter {
guard let p = LocalProduct(rawValue: $0.productIdentifier) else {
return false
}
guard including.contains(p) else {
return false
}
guard p.isFeature else {
return false
}
return true
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func featureProducts(excluding: [LocalProduct]) -> [SKProduct] {
2022-09-04 18:09:31 +00:00
inApp.products.filter {
guard let p = LocalProduct(rawValue: $0.productIdentifier) else {
return false
}
guard !excluding.contains(p) else {
return false
}
guard p.isFeature else {
return false
}
return true
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func purchase(_ product: SKProduct, completionHandler: @escaping (Result<InAppPurchaseResult, Error>) -> Void) {
inApp.purchase(product: product) { result in
if case .success = result {
self.reloadReceipt()
}
DispatchQueue.main.async {
completionHandler(result)
}
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func restorePurchases(completionHandler: @escaping (Error?) -> Void) {
inApp.restorePurchases { (finished, _, error) in
guard finished else {
return
}
DispatchQueue.main.async {
completionHandler(error)
}
}
}
// MARK: In-app eligibility
2023-03-17 20:55:47 +00:00
2021-02-07 09:43:54 +00:00
private func isCurrentPlatformVersion() -> Bool {
2022-05-16 09:18:49 +00:00
purchasedFeatures.contains(isMac ? .fullVersion_macOS : .fullVersion_iOS)
2021-02-07 09:43:54 +00:00
}
private func isFullVersion() -> Bool {
if appType == .fullVersion {
return true
}
2021-02-07 09:43:54 +00:00
if isCurrentPlatformVersion() {
return true
}
return purchasedFeatures.contains(.fullVersion)
}
2022-04-12 13:09:14 +00:00
func isEligible(forFeature feature: LocalProduct) -> Bool {
if let purchasedAppBuild = purchasedAppBuild {
if feature == .networkSettings && buildProducts.hasProduct(.networkSettings, atBuild: purchasedAppBuild) {
return true
}
}
return isFullVersion() || purchasedFeatures.contains(feature)
}
2022-04-12 13:09:14 +00:00
func isEligible(forProvider providerName: ProviderName) -> Bool {
2022-10-04 20:24:06 +00:00
guard providerName != .oeck else {
return true
}
return isEligible(forFeature: providerName.product)
}
2022-04-12 13:09:14 +00:00
func isEligibleForFeedback() -> Bool {
2022-09-04 18:09:31 +00:00
appType == .beta || !purchasedFeatures.isEmpty
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
func hasPurchased(_ product: LocalProduct) -> Bool {
2022-09-04 18:09:31 +00:00
purchasedFeatures.contains(product)
}
2022-04-12 13:09:14 +00:00
func purchaseDate(forProduct product: LocalProduct) -> Date? {
2022-09-04 18:09:31 +00:00
purchaseDates[product]
}
2022-04-12 13:09:14 +00:00
func reloadReceipt(andNotify: Bool = true) {
guard let url = Bundle.main.appStoreReceiptURL else {
2022-04-12 13:09:14 +00:00
pp_log.warning("No App Store receipt found!")
return
}
guard let receipt = Receipt(contentsOfURL: url) else {
2022-04-12 13:09:14 +00:00
pp_log.error("Could not parse App Store receipt!")
return
}
if let originalAppVersion = receipt.originalAppVersion, let buildNumber = Int(originalAppVersion) {
purchasedAppBuild = buildNumber
}
purchasedFeatures.removeAll()
var newCancelledPurchases: Set<LocalProduct> = []
if let buildNumber = purchasedAppBuild {
2022-04-12 13:09:14 +00:00
pp_log.debug("Original purchased build: \(buildNumber)")
// assume some purchases by build number
buildProducts.products(atBuild: buildNumber).forEach {
purchasedFeatures.insert($0)
}
}
if let iapReceipts = receipt.inAppPurchaseReceipts {
purchaseDates.removeAll()
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
pp_log.debug("In-app receipts:")
iapReceipts.forEach {
guard let pid = $0.productIdentifier, let product = LocalProduct(rawValue: pid) else {
return
}
if let cancellationDate = $0.cancellationDate {
2022-04-12 13:09:14 +00:00
pp_log.debug("\t\(pid) [cancelled on: \(cancellationDate)]")
newCancelledPurchases.insert(product)
return
}
if let purchaseDate = $0.originalPurchaseDate {
2022-04-12 13:09:14 +00:00
pp_log.debug("\t\(pid) [purchased on: \(purchaseDate)]")
purchaseDates[product] = purchaseDate
}
purchasedFeatures.insert(product)
}
}
2022-04-12 13:09:14 +00:00
pp_log.info("Purchased features: \(purchasedFeatures)")
if andNotify {
objectWillChange.send()
}
cancelledPurchases = newCancelledPurchases
}
}
extension ProductManager: SKPaymentTransactionObserver {
2022-04-12 13:09:14 +00:00
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
DispatchQueue.main.async { [weak self] in
self?.reloadReceipt()
}
}
}
extension ProductManager {
private func detectRefunds(_ refunds: Set<LocalProduct>) {
let isEligibleForFullVersion = isFullVersion()
let hasCancelledFullVersion: Bool
let hasCancelledTrustedNetworks: Bool
2023-03-17 20:55:47 +00:00
2022-05-16 09:18:49 +00:00
if isMac {
hasCancelledFullVersion = !isEligibleForFullVersion && (
refunds.contains(.fullVersion) || refunds.contains(.fullVersion_macOS)
)
2022-05-16 09:18:49 +00:00
hasCancelledTrustedNetworks = false
} else {
hasCancelledFullVersion = !isEligibleForFullVersion && (
refunds.contains(.fullVersion) || refunds.contains(.fullVersion_iOS)
)
hasCancelledTrustedNetworks = !isEligibleForFullVersion && refunds.contains(.trustedNetworks)
2022-05-16 09:18:49 +00:00
}
2023-03-17 20:55:47 +00:00
// review features and potentially revert them if they were used (Siri is handled in AppDelegate)
if hasCancelledFullVersion || hasCancelledTrustedNetworks {
didRefundProducts.send()
}
}
}
2022-05-16 09:18:49 +00:00
extension ProductManager {
private var isMac: Bool {
#if targetEnvironment(macCatalyst)
true
#else
false
#endif
}
}