passepartout-apple/PassepartoutLibrary/Sources/PassepartoutFrontend/Managers/ProductManager.swift

315 lines
9.8 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 PassepartoutCore
import PassepartoutProviders
public protocol LocalInApp: InAppProtocol where ProductIdentifier == LocalProduct {
}
2023-03-17 20:55:47 +00:00
extension StoreKitInApp: LocalInApp where ProductIdentifier == LocalProduct {
}
@MainActor
public final class ProductManager: NSObject, ObservableObject {
private let inApp: any LocalInApp
private let receiptReader: ReceiptReader
2023-03-17 20:55:47 +00:00
private let overriddenAppType: AppType?
public let buildProducts: BuildProducts
2023-03-17 20:55:47 +00:00
public let didRefundProducts = PassthroughSubject<Void, Never>()
2023-03-17 20:55:47 +00:00
@Published public private(set) var appType: AppType
@Published public private(set) var isRefreshingProducts = false
@Published public private(set) var products: [InAppProduct]
2022-04-12 13:09:14 +00:00
//
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
public init(inApp: any LocalInApp,
receiptReader: ReceiptReader,
overriddenAppType: AppType? = nil,
buildProducts: BuildProducts) {
self.overriddenAppType = overriddenAppType
self.receiptReader = receiptReader
self.buildProducts = buildProducts
appType = .undefined
2022-04-12 13:09:14 +00:00
products = []
self.inApp = inApp
purchasedAppBuild = nil
purchasedFeatures = []
purchaseDates = [:]
cancelledPurchases = nil
2023-03-17 20:55:47 +00:00
super.init()
inApp.setTransactionsObserver { [weak self] in
self?.reloadReceipt()
}
reloadReceipt()
Task {
await refreshProducts()
let isBeta = await SandboxChecker().isBeta
appType = overriddenAppType ?? (isBeta ? .beta : .freemium)
pp_log.info("App type: \(appType)")
reloadReceipt()
}
}
2023-03-17 20:55:47 +00:00
public func canMakePayments() -> Bool {
inApp.canMakePurchases()
}
2023-03-17 20:55:47 +00:00
public func refreshProducts() async {
2022-04-12 13:09:14 +00:00
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
do {
let productsMap = try await inApp.requestProducts(withIdentifiers: ids)
pp_log.debug("In-app products: \(productsMap.keys.map(\.rawValue))")
products = Array(productsMap.values)
isRefreshingProducts = false
} catch {
pp_log.warning("Unable to list products: \(error)")
isRefreshingProducts = false
}
}
public func product(withIdentifier identifier: LocalProduct) -> InAppProduct? {
2022-09-04 18:09:31 +00:00
inApp.product(withIdentifier: identifier)
}
2023-03-17 20:55:47 +00:00
public func featureProducts(including: [LocalProduct]) -> [InAppProduct] {
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
public func featureProducts(excluding: [LocalProduct]) -> [InAppProduct] {
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
public func purchase(_ product: InAppProduct) async throws -> InAppPurchaseResult {
guard let pid = LocalProduct(rawValue: product.productIdentifier) else {
assertionFailure("Unrecognized product: \(product)")
pp_log.warning("Unrecognized product: \(product)")
return .cancelled
}
let result = try await inApp.purchase(productWithIdentifier: pid)
reloadReceipt()
return result
}
2023-03-17 20:55:47 +00:00
public func restorePurchases() async throws {
try await inApp.restorePurchases()
}
}
// MARK: In-app eligibility
2023-03-17 20:55:47 +00:00
extension ProductManager {
public 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
}
public func isFullVersion() -> Bool {
if appType == .fullVersion {
return true
}
2021-02-07 09:43:54 +00:00
if isCurrentPlatformVersion() {
return true
}
return purchasedFeatures.contains(.fullVersion)
}
public func isEligible(forFeature feature: LocalProduct) -> Bool {
if let purchasedAppBuild = purchasedAppBuild {
if feature == .networkSettings && buildProducts.hasProduct(.networkSettings, atBuild: purchasedAppBuild) {
return true
}
}
if feature.isPlatformVersion {
return purchasedFeatures.contains(feature)
}
return isFullVersion() || purchasedFeatures.contains(feature)
}
public 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)
}
public func isEligibleForFeedback() -> Bool {
2022-09-04 18:09:31 +00:00
appType == .beta || !purchasedFeatures.isEmpty
}
2023-03-17 20:55:47 +00:00
public func hasPurchased(_ product: LocalProduct) -> Bool {
2022-09-04 18:09:31 +00:00
purchasedFeatures.contains(product)
}
public func purchaseDate(forProduct product: LocalProduct) -> Date? {
2022-09-04 18:09:31 +00:00
purchaseDates[product]
}
}
extension ProductManager {
public func reloadReceipt(andNotify: Bool = true) {
guard let receipt = receiptReader.receipt(for: appType) else {
2022-04-12 13:09:14 +00:00
pp_log.error("Could not parse App Store receipt!")
return
}
if let originalBuildNumber = receipt.originalBuildNumber {
purchasedAppBuild = originalBuildNumber
}
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.purchaseReceipts {
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
}
}
private extension ProductManager {
var isMac: Bool {
#if targetEnvironment(macCatalyst)
true
#else
false
#endif
}
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()
}
}
}