2017-11-28 12:39:44 +00:00
|
|
|
//
|
|
|
|
// Purchase.swift
|
|
|
|
// mas-cli
|
|
|
|
//
|
|
|
|
// Created by Jakob Rieck on 24/10/2017.
|
|
|
|
// Copyright (c) 2017 Jakob Rieck. All rights reserved.
|
|
|
|
//
|
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
import Commandant
|
|
|
|
import CommerceKit
|
2017-11-28 12:39:44 +00:00
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
public struct PurchaseCommand: CommandProtocol {
|
|
|
|
public typealias Options = PurchaseOptions
|
|
|
|
public let verb = "purchase"
|
2020-03-21 10:44:28 +00:00
|
|
|
public let function = "Purchase and download free apps from the Mac App Store"
|
2020-01-09 11:54:01 +00:00
|
|
|
|
2020-05-15 03:07:07 +00:00
|
|
|
private let appLibrary: AppLibrary
|
|
|
|
|
|
|
|
/// Public initializer.
|
2020-01-09 11:54:01 +00:00
|
|
|
public init() {
|
2020-05-15 03:07:07 +00:00
|
|
|
self.init(appLibrary: MasAppLibrary())
|
2020-01-09 11:54:01 +00:00
|
|
|
}
|
|
|
|
|
2020-05-15 03:07:07 +00:00
|
|
|
/// Internal initializer.
|
|
|
|
/// - Parameter appLibrary: AppLibrary manager.
|
|
|
|
init(appLibrary: AppLibrary = MasAppLibrary()) {
|
|
|
|
self.appLibrary = appLibrary
|
|
|
|
}
|
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
/// Runs the command.
|
|
|
|
public func run(_ options: Options) -> Result<(), MASError> {
|
2017-11-28 12:39:44 +00:00
|
|
|
// Try to download applications with given identifiers and collect results
|
2020-01-09 11:54:01 +00:00
|
|
|
let downloadResults = options.appIds.compactMap { (appId) -> MASError? in
|
2020-05-15 03:07:07 +00:00
|
|
|
if let product = appLibrary.installedApp(forId: appId) {
|
2017-11-28 12:39:44 +00:00
|
|
|
printWarning("\(product.appName) has already been purchased.")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-15 03:24:27 +00:00
|
|
|
return download(appId, purchase: true)
|
2017-11-28 12:39:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
switch downloadResults.count {
|
|
|
|
case 0:
|
2020-01-09 11:54:01 +00:00
|
|
|
return .success(())
|
2017-11-28 12:39:44 +00:00
|
|
|
case 1:
|
|
|
|
return .failure(downloadResults[0])
|
|
|
|
default:
|
|
|
|
return .failure(.downloadFailed(error: nil))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
public struct PurchaseOptions: OptionsProtocol {
|
2017-11-28 12:39:44 +00:00
|
|
|
let appIds: [UInt64]
|
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
public static func create(_ appIds: [Int]) -> PurchaseOptions {
|
|
|
|
return PurchaseOptions(appIds: appIds.map { UInt64($0) })
|
2017-11-28 12:39:44 +00:00
|
|
|
}
|
|
|
|
|
2020-01-09 11:54:01 +00:00
|
|
|
public static func evaluate(_ mode: CommandMode) -> Result<PurchaseOptions, CommandantError<MASError>> {
|
2017-11-28 12:39:44 +00:00
|
|
|
return create
|
2020-01-09 11:54:01 +00:00
|
|
|
<*> mode <| Argument(usage: "app ID(s) to install")
|
2017-11-28 12:39:44 +00:00
|
|
|
}
|
|
|
|
}
|