import AppKit import CommanderCore import CryptoKit import Security /// Aggiornamenti: all'avvio (se attivo nelle Impostazioni) e con "Controlla adesso". /// Il file `latest.json` sul sito dice l'ultima versione; lo zip si scarica, si controlla /// (impronta SHA-256 e firma dello stesso sviluppatore) e prende il posto dell'app. enum Updater { struct Release: Decodable { let version: String let build: Int let url: URL let sha256: String let notes: String? let minimumSystem: String? } static var feedURL: URL? { (Bundle.main.object(forInfoDictionaryKey: "MCUpdateFeed") as? String).flatMap(URL.init(string:)) } static var currentVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?" } static var currentBuild: Int { Int(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "") ?? 0 } private static var busy = false private static var progressWindow: NSWindow? /// All'avvio, qualche secondo dopo, senza disturbare se non c'è niente. static func checkAtLaunch() { guard Settings.shared.checkUpdates else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 4) { check(userInitiated: false) } } static func check(userInitiated: Bool) { guard !busy, let feed = feedURL else { if userInitiated && feedURL == nil { Dialogs.message("Questa copia dell'app non ha l'indirizzo degli aggiornamenti") } return } busy = true var req = URLRequest(url: feed) req.cachePolicy = .reloadIgnoringLocalCacheData req.timeoutInterval = 20 URLSession.shared.dataTask(with: req) { data, _, error in let release = data.flatMap { try? JSONDecoder().decode(Release.self, from: $0) } DispatchQueue.main.async { busy = false guard let release else { if userInitiated { Dialogs.message("Non riesco a controllare gli aggiornamenti", info: error?.localizedDescription ?? "Il sito degli aggiornamenti non risponde come dovrebbe.", style: .warning) } return } handle(release, userInitiated: userInitiated) } }.resume() } private static func handle(_ r: Release, userInitiated: Bool) { guard r.build > currentBuild else { if userInitiated { Dialogs.message("Hai già l'ultima versione", info: "Mac Commander \(currentVersion)") } return } if let min = r.minimumSystem, ProcessInfo.processInfo.operatingSystemVersion < min { if userInitiated { Dialogs.message("La versione \(r.version) richiede macOS \(min) o successivo", style: .warning) } return } // All'avvio una versione saltata non si ripropone; con "Controlla adesso" sì. if !userInitiated && Settings.shared.skippedUpdate == r.build { return } if !userInitiated && Settings.shared.autoInstallUpdates { install(r) return } let a = NSAlert() a.messageText = "C'è una nuova versione di Mac Commander: \(r.version)" a.informativeText = "Hai la \(currentVersion).\n\n" + (r.notes ?? "") a.addButton(withTitle: "Aggiorna") a.addButton(withTitle: "Più tardi") a.addButton(withTitle: "Salta questa versione") switch a.runCentered() { case .alertFirstButtonReturn: install(r) case .alertThirdButtonReturn: Settings.shared.skippedUpdate = r.build default: break } } // MARK: - Scarica e installa private static func install(_ r: Release) { let app = Bundle.main.bundleURL // Lo zip deve arrivare in https dallo stesso sito di latest.json. guard r.url.scheme == "https", r.url.host == feedURL?.host else { Dialogs.message("Aggiornamento rifiutato", info: "L'indirizzo dello zip non è quello del sito di Mac Commander.", style: .warning) return } if app.path.contains("/AppTranslocation/") { Dialogs.message("Sposta Mac Commander nella cartella Applicazioni", info: "Così può aggiornarsi da solo. Poi riaprilo da lì.", style: .warning) return } guard FileManager.default.isWritableFile(atPath: app.deletingLastPathComponent().path) else { Dialogs.message("Non ho il permesso di aggiornare l'app", info: "Scarica la versione \(r.version) dal sito e sostituiscila a mano: \(r.url.absoluteString)", style: .warning) return } busy = true showProgress("Scarico Mac Commander \(r.version)…") URLSession.shared.downloadTask(with: r.url) { tmp, _, error in let result = Result { guard let tmp else { throw TransferError(error?.localizedDescription ?? "Download non riuscito") } return try prepare(zip: tmp, expectedSHA: r.sha256, replacing: app) } DispatchQueue.main.async { busy = false hideProgress() switch result { case .success: Settings.shared.skippedUpdate = 0 let a = NSAlert() a.messageText = "Mac Commander è aggiornato alla versione \(r.version)" a.informativeText = "La nuova versione parte al prossimo avvio. Vuoi riavviarlo adesso?" a.addButton(withTitle: "Riavvia") a.addButton(withTitle: "Più tardi") if a.runCentered() == .alertFirstButtonReturn { relaunch(app) } case .failure(let e): Dialogs.message("Aggiornamento non riuscito", info: e.localizedDescription, style: .warning) } } }.resume() } /// Controlla lo zip, lo estrae accanto all'app e la sostituisce. Sul thread di lavoro. private static func prepare(zip: URL, expectedSHA: String, replacing app: URL) throws -> URL { let fm = FileManager.default let data = try Data(contentsOf: zip, options: .alwaysMapped) let sha = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() guard sha == expectedSHA.lowercased() else { throw TransferError("Il file scaricato non è quello giusto (impronta diversa).") } // Cartella temporanea sullo stesso disco dell'app: così la sostituzione è immediata. let work = try fm.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: app, create: true) defer { try? fm.removeItem(at: work) } let unzip = Process() unzip.executableURL = URL(fileURLWithPath: "/usr/bin/ditto") unzip.arguments = ["-x", "-k", zip.path, work.path] try unzip.run() unzip.waitUntilExit() guard unzip.terminationStatus == 0, let newApp = try fm.contentsOfDirectory(at: work, includingPropertiesForKeys: nil).first(where: { $0.pathExtension == "app" }) else { throw TransferError("Lo zip non contiene l'app.") } try checkSignature(newApp) _ = try fm.replaceItemAt(app, withItemAt: newApp) return app } /// La nuova app deve avere una firma valida dello stesso sviluppatore di quella che gira. /// Si rifiuta tutto se l'app che gira non ha una firma con team (copia di prova). private static func checkSignature(_ newApp: URL) throws { guard let team = teamID(Bundle.main.bundleURL), let bundleID = Bundle.main.bundleIdentifier, team.allSatisfy({ $0.isLetter || $0.isNumber }) else { throw TransferError("Questa copia di Mac Commander non è firmata: non può aggiornarsi da sola.") } var code: SecStaticCode? var requirement: SecRequirement? let text = "anchor apple generic and identifier \"\(bundleID)\" and certificate leaf[subject.OU] = \"\(team)\"" guard SecStaticCodeCreateWithPath(newApp as CFURL, [], &code) == errSecSuccess, let code, SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess, SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate), requirement) == errSecSuccess else { throw TransferError("La nuova versione non è firmata dallo stesso sviluppatore.") } } private static func teamID(_ url: URL) -> String? { var code: SecStaticCode? var info: CFDictionary? guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code, SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess else { return nil } return (info as? [String: Any])?[kSecCodeInfoTeamIdentifier as String] as? String } /// Chiude l'app e la riapre appena è uscita (lo fa una piccola shell che resta in vita). private static func relaunch(_ app: URL) { let p = Process() p.executableURL = URL(fileURLWithPath: "/bin/sh") // Se l'uscita viene annullata (c'è una copia in corso), dopo un minuto la shell rinuncia. let pid = ProcessInfo.processInfo.processIdentifier p.arguments = ["-c", "i=0; while kill -0 \(pid) 2>/dev/null && [ $i -lt 300 ]; do sleep 0.2; i=$((i+1)); done; kill -0 \(pid) 2>/dev/null || /usr/bin/open \"$0\"", app.path] try? p.run() NSApp.terminate(nil) } private static func showProgress(_ text: String) { let w = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 360, height: 80), styleMask: [.titled], backing: .buffered, defer: false) w.title = "Aggiornamento" w.isReleasedWhenClosed = false let label = NSTextField(labelWithString: text) let bar = NSProgressIndicator() bar.isIndeterminate = true bar.startAnimation(nil) let stack = NSStackView(views: [label, bar]) stack.orientation = .vertical stack.alignment = .leading stack.edgeInsets = NSEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) bar.widthAnchor.constraint(equalToConstant: 320).isActive = true w.contentView = stack w.centerInApp() w.orderFront(nil) progressWindow = w } private static func hideProgress() { progressWindow?.orderOut(nil) progressWindow = nil } } private func < (a: OperatingSystemVersion, b: String) -> Bool { let p = b.split(separator: ".").compactMap { Int($0) } let v = [a.majorVersion, a.minorVersion, a.patchVersion] for i in 0..<3 { let x = i < p.count ? p[i] : 0 if v[i] != x { return v[i] < x } } return false }