mas/Sources/MasKit/Commands/Purchase.swift

70 lines
2 KiB
Swift
Raw Normal View History

//
// Purchase.swift
// mas-cli
//
// Created by Jakob Rieck on 24/10/2017.
// Copyright (c) 2017 Jakob Rieck. All rights reserved.
//
import Commandant
import CommerceKit
public struct PurchaseCommand: CommandProtocol {
2020-05-15 03:32:51 +00:00
public typealias Options = PurchaseOptions
public let verb = "purchase"
public let function = "Purchase and download free apps from the Mac App Store"
private let appLibrary: AppLibrary
/// Public initializer.
2020-05-15 03:32:51 +00:00
public init() {
self.init(appLibrary: MasAppLibrary())
2020-05-15 03:32:51 +00:00
}
/// Internal initializer.
/// - Parameter appLibrary: AppLibrary manager.
init(appLibrary: AppLibrary = MasAppLibrary()) {
self.appLibrary = appLibrary
}
2020-05-15 03:32:51 +00:00
/// Runs the command.
2021-03-22 05:46:17 +00:00
public func run(_ options: Options) -> Result<Void, MASError> {
if #available(macOS 10.15, *) {
// Purchases are no longer possible as of Catalina.
// https://github.com/mas-cli/mas/issues/289
return .failure(.notSupported)
}
2020-05-15 03:32:51 +00:00
// Try to download applications with given identifiers and collect results
let appIds = options.appIds.filter { appId in
if let product = appLibrary.installedApp(forId: appId) {
2020-05-15 03:32:51 +00:00
printWarning("\(product.appName) has already been purchased.")
return false
2020-05-15 03:32:51 +00:00
}
return true
2020-05-15 03:32:51 +00:00
}
do {
try downloadAll(appIds, purchase: true).wait()
} catch {
return .failure(error as? MASError ?? .downloadFailed(error: error as NSError))
2020-05-15 03:32:51 +00:00
}
return .success(())
2020-05-15 03:32:51 +00:00
}
}
public struct PurchaseOptions: OptionsProtocol {
2020-05-15 03:32:51 +00:00
let appIds: [UInt64]
2020-05-15 03:32:51 +00:00
public static func create(_ appIds: [Int]) -> PurchaseOptions {
2021-03-22 05:46:17 +00:00
PurchaseOptions(appIds: appIds.map { UInt64($0) })
2020-05-15 03:32:51 +00:00
}
2020-05-15 03:32:51 +00:00
public static func evaluate(_ mode: CommandMode) -> Result<PurchaseOptions, CommandantError<MASError>> {
2021-03-22 05:46:17 +00:00
create
2020-05-15 03:32:51 +00:00
<*> mode <| Argument(usage: "app ID(s) to install")
}
}