2016-04-14 16:14:06 +00:00
|
|
|
//
|
|
|
|
// Search.swift
|
|
|
|
// mas-cli
|
|
|
|
//
|
|
|
|
// Created by Michael Schneider on 4/14/16.
|
|
|
|
// Copyright © 2016 Andrew Naylor. All rights reserved.
|
|
|
|
//
|
|
|
|
|
2016-04-14 19:27:07 +00:00
|
|
|
struct ResultKeys {
|
|
|
|
static let ResultCount = "resultCount"
|
|
|
|
static let Results = "results"
|
|
|
|
static let TrackName = "trackName"
|
|
|
|
static let TrackId = "trackId"
|
|
|
|
}
|
|
|
|
|
2016-09-24 14:53:50 +00:00
|
|
|
struct SearchCommand: CommandProtocol {
|
2016-04-14 16:14:06 +00:00
|
|
|
typealias Options = SearchOptions
|
|
|
|
let verb = "search"
|
|
|
|
let function = "Search for apps from the Mac App Store"
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
func run(_ options: Options) -> Result<(), MASError> {
|
2016-04-14 16:14:06 +00:00
|
|
|
|
2016-04-14 19:27:07 +00:00
|
|
|
guard let searchURLString = searchURLString(options.appName),
|
2016-09-17 12:58:38 +00:00
|
|
|
let searchJson = URLSession.requestSynchronousJSONWithURLString(searchURLString) as? [String: AnyObject] else {
|
2016-09-25 21:13:23 +00:00
|
|
|
return .failure(.searchFailed)
|
2016-04-14 16:14:06 +00:00
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
guard let resultCount = searchJson[ResultKeys.ResultCount] as? Int , resultCount > 0,
|
2016-04-14 19:27:07 +00:00
|
|
|
let results = searchJson[ResultKeys.Results] as? [[String: AnyObject]] else {
|
|
|
|
print("No results found")
|
2016-09-25 21:13:23 +00:00
|
|
|
return .failure(.noSearchResultsFound)
|
2016-04-14 16:14:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for result in results {
|
2016-04-14 19:27:07 +00:00
|
|
|
if let appName = result[ResultKeys.TrackName] as? String,
|
2016-09-17 12:58:38 +00:00
|
|
|
let appId = result[ResultKeys.TrackId] as? Int {
|
2016-04-14 16:14:06 +00:00
|
|
|
print("\(String(appId)) \(appName)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
return .success(())
|
2016-04-14 16:14:06 +00:00
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
func searchURLString(_ appName: String) -> String? {
|
2016-04-14 19:27:07 +00:00
|
|
|
if let urlEncodedAppName = appName.URLEncodedString() {
|
|
|
|
return "https://itunes.apple.com/search?entity=macSoftware&term=\(urlEncodedAppName)&attribute=allTrackTerm"
|
|
|
|
}
|
|
|
|
return nil
|
2016-04-14 16:14:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-24 14:53:50 +00:00
|
|
|
struct SearchOptions: OptionsProtocol {
|
2016-04-14 16:14:06 +00:00
|
|
|
let appName: String
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
static func create(_ appName: String) -> SearchOptions {
|
2016-04-14 16:14:06 +00:00
|
|
|
return SearchOptions(appName: appName)
|
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
static func evaluate(_ m: CommandMode) -> Result<SearchOptions, CommandantError<MASError>> {
|
2016-04-14 16:14:06 +00:00
|
|
|
return create
|
|
|
|
<*> m <| Argument(usage: "the app name to search")
|
|
|
|
}
|
|
|
|
}
|