45 lines
1.7 KiB
Swift
45 lines
1.7 KiB
Swift
|
|
import Foundation
|
||
|
|
|
||
|
|
public enum SocketError: Error, CustomStringConvertible {
|
||
|
|
case pathTooLong(String)
|
||
|
|
case syscall(String, Int32)
|
||
|
|
|
||
|
|
public var description: String {
|
||
|
|
switch self {
|
||
|
|
case .pathTooLong(let path): return "socket path is too long for a Unix socket (\(path.utf8.count) bytes): \(path)"
|
||
|
|
case .syscall(let name, let code): return "\(name) failed: \(String(cString: strerror(code)))"
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public enum NotifySocket {
|
||
|
|
public static func defaultPath() -> String {
|
||
|
|
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||
|
|
return base.appendingPathComponent("LuxeNotifier/notify.sock").path
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func makeAddress(_ path: String) throws -> sockaddr_un {
|
||
|
|
var address = sockaddr_un()
|
||
|
|
address.sun_family = sa_family_t(AF_UNIX)
|
||
|
|
let capacity = MemoryLayout.size(ofValue: address.sun_path)
|
||
|
|
guard path.utf8.count < capacity else { throw SocketError.pathTooLong(path) }
|
||
|
|
withUnsafeMutablePointer(to: &address.sun_path) { pointer in
|
||
|
|
pointer.withMemoryRebound(to: CChar.self, capacity: capacity) { _ = strcpy($0, path) }
|
||
|
|
}
|
||
|
|
return address
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One JSON line per event keeps framing trivial and lets `nc -U` act as a test listener.
|
||
|
|
public static func encodeLine(_ event: NotifyEvent) throws -> Data {
|
||
|
|
let encoder = JSONEncoder()
|
||
|
|
encoder.dateEncodingStrategy = .iso8601
|
||
|
|
return try encoder.encode(event) + Data("\n".utf8)
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func decodeLine(_ line: Data) throws -> NotifyEvent {
|
||
|
|
let decoder = JSONDecoder()
|
||
|
|
decoder.dateDecodingStrategy = .iso8601
|
||
|
|
return try decoder.decode(NotifyEvent.self, from: line)
|
||
|
|
}
|
||
|
|
}
|