2020-04-04 22:16:31 +00:00
|
|
|
import Foundation
|
|
|
|
import ServiceManagement
|
2020-11-12 01:00:15 +00:00
|
|
|
import AppKit
|
|
|
|
import OSLog
|
2021-01-19 04:08:52 +00:00
|
|
|
import SecretKit
|
2020-04-04 22:16:31 +00:00
|
|
|
|
|
|
|
struct LaunchAgentController {
|
2021-01-19 04:08:52 +00:00
|
|
|
|
2023-12-11 08:59:30 +00:00
|
|
|
private let logger = Logger(subsystem: "com.maxgoedjen.secretive", category: "LaunchAgentController")
|
|
|
|
|
2024-12-25 23:25:01 +00:00
|
|
|
func install() async {
|
2023-12-11 08:59:30 +00:00
|
|
|
logger.debug("Installing agent")
|
2020-04-04 22:16:31 +00:00
|
|
|
_ = setEnabled(false)
|
2020-11-13 06:55:52 +00:00
|
|
|
// 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?
|
2024-12-25 23:25:01 +00:00
|
|
|
try? await Task.sleep(for: .seconds(1))
|
|
|
|
await MainActor.run {
|
2020-11-13 06:55:52 +00:00
|
|
|
_ = setEnabled(true)
|
|
|
|
}
|
2020-04-04 22:16:31 +00:00
|
|
|
}
|
|
|
|
|
2024-12-25 23:25:01 +00:00
|
|
|
func forceLaunch() async -> Bool {
|
2023-12-11 08:59:30 +00:00
|
|
|
logger.debug("Agent is not running, attempting to force launch")
|
2020-11-12 01:00:15 +00:00
|
|
|
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
|
2024-12-25 23:25:01 +00:00
|
|
|
do {
|
2025-01-04 09:10:57 +00:00
|
|
|
try await NSWorkspace.shared.openApplication(at: url, configuration: config)
|
2024-12-25 23:25:01 +00:00
|
|
|
logger.debug("Agent force launched")
|
|
|
|
return true
|
|
|
|
} catch {
|
|
|
|
logger.error("Error force launching \(error.localizedDescription)")
|
|
|
|
return false
|
2020-11-12 01:00:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-04 22:16:31 +00:00
|
|
|
private func setEnabled(_ enabled: Bool) -> Bool {
|
2025-01-04 09:10:57 +00:00
|
|
|
let service = SMAppService.loginItem(identifier: Bundle.main.agentBundleID)
|
|
|
|
do {
|
|
|
|
if enabled {
|
|
|
|
try service.register()
|
|
|
|
} else {
|
|
|
|
try service.unregister()
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
} catch {
|
|
|
|
return false
|
|
|
|
}
|
2020-04-04 22:16:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|