// // PurchaseDownloadObserver.swift // mas-cli // // Created by Andrew Naylor on 21/08/2015. // Copyright (c) 2015 Andrew Naylor. All rights reserved. // let csi = "\u{001B}[" @objc class PurchaseDownloadObserver: CKDownloadQueueObserver { let purchase: SSPurchase var completionHandler: (() -> ())? var errorHandler: ((MASError) -> ())? init(purchase: SSPurchase) { self.purchase = purchase } func downloadQueue(queue: CKDownloadQueue, statusChangedForDownload download: SSDownload!) { if download.metadata.itemIdentifier != purchase.itemIdentifier { return } let status = download.status if status.failed || status.cancelled { queue.removeDownloadWithItemIdentifier(download.metadata.itemIdentifier) } else { progress(status.progressState) } } func downloadQueue(queue: CKDownloadQueue, changedWithAddition download: SSDownload!) { println("==> Downloading " + download.metadata.title) } func downloadQueue(queue: CKDownloadQueue, changedWithRemoval download: SSDownload!) { clearLine() let status = download.status if status.failed { println("==> Download Failed") errorHandler?(MASError(code: .DownloadFailed, sourceError: status.error)) } else if status.cancelled { println("==> Download Cancelled") errorHandler?(MASError(code: .Cancelled)) } else { println("==> Installed " + download.metadata.title) completionHandler?() } } } struct ProgressState { let percentComplete: Float let phase: String var percentage: String { return String(format: "%.1f%%", arguments: [floor(percentComplete * 100)]) } } func progress(state: ProgressState) { // Don't display the progress bar if we're not on a terminal if isatty(fileno(stdout)) == 0 { return } let barLength = 60 let completeLength = Int(state.percentComplete * Float(barLength)) var bar = "" for i in 0..