secretive/Sources/Secretive/Controllers/AgentLaunchController.swift

54 lines
1.8 KiB
Swift
Raw Permalink Normal View History

2020-04-04 22:16:31 +00:00
import Foundation
import ServiceManagement
import AppKit
import OSLog
import SecretKit
2020-04-04 22:16:31 +00:00
2022-01-03 06:15:18 +00:00
struct AgentLaunchController {
2022-01-03 06:52:53 +00:00
func install(uninstallFirst: Bool = true, completion: (() -> Void)? = nil) {
Logger().debug("Installing agent")
2022-01-03 06:52:53 +00:00
if uninstallFirst {
_ = setEnabled(false)
}
// This is definitely a bit of a "seems to work better" thing but:
// Seems to more reliably hit if these are on separate runloops, otherwise it seems like it sometimes doesn't kill old
// and start new?
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
_ = setEnabled(true)
2022-01-03 06:52:53 +00:00
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
completion?()
2022-01-03 06:52:53 +00:00
}
}
2020-04-04 22:16:31 +00:00
}
func forceLaunch(completion: ((Bool) -> Void)?) {
2022-01-03 06:15:18 +00:00
Logger().debug("Agent is still not running, attempting to force launch")
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LoginItems/SecretAgent.app")
2021-08-08 22:57:01 +00:00
let config = NSWorkspace.OpenConfiguration()
config.activates = false
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
2021-05-10 03:05:45 +00:00
DispatchQueue.main.async {
completion?(error == nil)
}
if let error = error {
Logger().error("Error force launching \(error.localizedDescription)")
} else {
Logger().debug("Agent force launched")
}
}
}
2022-01-03 06:52:53 +00:00
func killNonInstanceAgents(agents: [NSRunningApplication]) {
for agent in agents {
agent.terminate()
}
}
2020-04-04 22:16:31 +00:00
private func setEnabled(_ enabled: Bool) -> Bool {
SMLoginItemSetEnabled(Bundle.main.agentBundleID as CFString, enabled)
2020-04-04 22:16:31 +00:00
}
}