mas/MasKit/Commands/Home.swift

74 lines
2.2 KiB
Swift
Raw Normal View History

2018-12-30 06:57:06 +00:00
//
// Home.swift
// mas-cli
//
// Created by Ben Chatelain on 2018-12-29.
// Copyright © 2016 mas-cli. All rights reserved.
//
import Commandant
/// Opens app page on MAS Preview. Uses the iTunes Lookup API:
/// https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#lookup
public struct HomeCommand: CommandProtocol {
2019-01-03 23:15:53 +00:00
public typealias Options = HomeOptions
2018-12-30 06:57:06 +00:00
public let verb = "home"
public let function = "Opens MAS Preview app page in a browser"
private let storeSearch: StoreSearch
2019-01-03 23:15:53 +00:00
private var openCommand: ExternalCommand
2018-12-30 06:57:06 +00:00
/// Designated initializer.
2021-03-22 05:25:18 +00:00
public init(
storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()
) {
2018-12-30 06:57:06 +00:00
self.storeSearch = storeSearch
2019-01-03 23:15:53 +00:00
self.openCommand = openCommand
2018-12-30 06:57:06 +00:00
}
/// Runs the command.
2021-03-22 05:46:17 +00:00
public func run(_ options: HomeOptions) -> Result<Void, MASError> {
2019-01-02 05:44:33 +00:00
do {
2020-05-15 03:32:51 +00:00
guard let result = try storeSearch.lookup(app: options.appId) else {
2019-01-30 06:15:24 +00:00
print("No results found")
return .failure(.noSearchResultsFound)
2019-01-02 05:44:33 +00:00
}
2019-01-03 23:15:53 +00:00
do {
try openCommand.run(arguments: result.trackViewUrl)
2019-01-03 23:15:53 +00:00
} catch {
printError("Unable to launch open command")
return .failure(.searchFailed)
}
if openCommand.failed {
let reason = openCommand.process.terminationReason
printError("Open failed: (\(reason)) \(openCommand.stderr)")
return .failure(.searchFailed)
}
2019-01-12 01:06:02 +00:00
} catch {
2019-01-05 00:54:00 +00:00
// Bubble up MASErrors
if let error = error as? MASError {
return .failure(error)
}
2019-01-02 05:44:33 +00:00
return .failure(.searchFailed)
2018-12-30 06:57:06 +00:00
}
return .success(())
}
}
public struct HomeOptions: OptionsProtocol {
let appId: Int
2018-12-30 06:57:06 +00:00
static func create(_ appId: Int) -> HomeOptions {
2021-03-22 05:46:17 +00:00
HomeOptions(appId: appId)
2018-12-30 06:57:06 +00:00
}
2019-01-12 01:06:02 +00:00
public static func evaluate(_ mode: CommandMode) -> Result<HomeOptions, CommandantError<MASError>> {
2021-03-22 05:46:17 +00:00
create
2019-01-12 01:06:02 +00:00
<*> mode <| Argument(usage: "ID of app to show on MAS Preview")
2018-12-30 06:57:06 +00:00
}
}