2023-12-12 17:33:42 +01:00
|
|
|
import Foundation
|
|
|
|
import SwiftUI
|
|
|
|
import SwiftData
|
|
|
|
|
|
|
|
final class RequestCoordinator: ObservableObject {
|
|
|
|
|
|
|
|
@Published
|
|
|
|
var state: MessageResult = .noKeyAvailable
|
|
|
|
|
|
|
|
@Published
|
|
|
|
var pendingRequests: [PendingOperation] = []
|
|
|
|
|
|
|
|
@Published
|
|
|
|
var activeRequest: PendingOperation?
|
|
|
|
|
|
|
|
@Published
|
|
|
|
var keyManager = KeyManagement()
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
@Published
|
|
|
|
var isPerformingRequest: Bool = false
|
|
|
|
|
2023-12-12 17:33:42 +01:00
|
|
|
@AppStorage("server")
|
|
|
|
var serverPath: String = "https://christophhagen.de/sesame/"
|
|
|
|
|
|
|
|
@AppStorage("localIP")
|
|
|
|
var localAddress: String = "192.168.178.104/"
|
|
|
|
|
|
|
|
@AppStorage("connectionType")
|
|
|
|
var connectionType: ConnectionStrategy = .remoteFirst
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private let modelContext: ModelContext
|
|
|
|
|
|
|
|
private let client = Client()
|
|
|
|
|
|
|
|
private var timer: Timer?
|
2023-12-12 17:33:42 +01:00
|
|
|
|
|
|
|
init(modelContext: ModelContext) {
|
|
|
|
self.modelContext = modelContext
|
|
|
|
if keyManager.hasAllKeys {
|
|
|
|
self.state = .notChecked
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 21:57:32 +01:00
|
|
|
func checkConnection(using route: TransmissionType? = nil) {
|
|
|
|
guard !isPerformingRequest else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
isPerformingRequest = true
|
|
|
|
Task {
|
|
|
|
let route = route ?? connectionType.transmissionTypes.first!
|
|
|
|
let (finalResult, _) = await performChallenge(route: route)
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.state = finalResult.result
|
|
|
|
self.isPerformingRequest = false
|
|
|
|
}
|
|
|
|
print("Finished connection test: \(finalResult)")
|
|
|
|
scheduleReturnToReadyState()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-29 22:18:41 +01:00
|
|
|
func startUnlock(quitAfterSuccess: Bool = false) {
|
2023-12-12 23:46:51 +01:00
|
|
|
guard !isPerformingRequest else {
|
2023-12-12 17:33:42 +01:00
|
|
|
return
|
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
isPerformingRequest = true
|
2023-12-12 17:33:42 +01:00
|
|
|
Task {
|
2023-12-12 23:46:51 +01:00
|
|
|
let finalResult = await performFullChallengeResponse()
|
2023-12-31 15:24:20 +01:00
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.state = finalResult
|
|
|
|
self.isPerformingRequest = false
|
|
|
|
}
|
2023-12-31 15:24:20 +01:00
|
|
|
if finalResult == .unlocked, quitAfterSuccess {
|
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
|
|
|
|
exit(EXIT_SUCCESS)
|
|
|
|
}
|
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
scheduleReturnToReadyState()
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private func performFullChallengeResponse() async -> MessageResult {
|
|
|
|
let transmissionTypes = connectionType.transmissionTypes
|
|
|
|
for route in transmissionTypes.dropLast() {
|
|
|
|
if await performUnlockAndSaveItem(route: route) == .unlocked {
|
|
|
|
return .unlocked
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
guard let route = transmissionTypes.last else {
|
|
|
|
// No transmission types at all
|
|
|
|
return keyManager.hasAllKeys ? .notChecked : .noKeyAvailable
|
|
|
|
}
|
|
|
|
return await performUnlockAndSaveItem(route: route)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private func performUnlockAndSaveItem(route: TransmissionType) async -> MessageResult {
|
|
|
|
let startTime = Date.now
|
|
|
|
let result = await performFullChallengeResponse(route: route)
|
|
|
|
let endTime = Date.now
|
|
|
|
let roundTripTime = endTime.timeIntervalSince(startTime)
|
|
|
|
print("Unlock took \(Int(roundTripTime * 1000)) ms (\(result.result))")
|
|
|
|
let item = HistoryItem(message: result, startDate: startTime, route: route, finishDate: endTime)
|
|
|
|
modelContext.insert(item)
|
|
|
|
return result.result
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private func performFullChallengeResponse(route: TransmissionType) async -> Message {
|
|
|
|
let (challengeResponse, challenge) = await performChallenge(route: route)
|
|
|
|
guard let challenge else {
|
|
|
|
return challengeResponse
|
|
|
|
}
|
|
|
|
|
|
|
|
let (unlockResponse, secondaryChallenge) = await performUnlock(with: challenge.message, route: route)
|
|
|
|
guard let secondaryChallenge else {
|
|
|
|
return unlockResponse
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
let (secondUnlockResponse, _) = await performUnlock(with: secondaryChallenge.message, route: route)
|
|
|
|
return secondUnlockResponse
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private func performChallenge(route: TransmissionType) async -> ServerResponse {
|
2023-12-12 17:33:42 +01:00
|
|
|
let initialMessage = Message.initial()
|
|
|
|
let (result, challenge) = await send(initialMessage, route: route)
|
|
|
|
guard let message = challenge?.message else {
|
2023-12-12 23:46:51 +01:00
|
|
|
return (result, nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
// Can't get here without the message being accepted
|
|
|
|
guard message.messageType == .challenge else {
|
|
|
|
print("Invalid message type for challenge: \(message)")
|
2023-12-12 23:46:51 +01:00
|
|
|
return (result.with(result: .invalidMessageTypeFromDevice), nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
return (result.with(result: .deviceAvailable), challenge)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
|
2023-12-12 23:46:51 +01:00
|
|
|
private func performUnlock(with challenge: Message, route: TransmissionType) async -> ServerResponse {
|
2023-12-12 17:33:42 +01:00
|
|
|
let request = challenge.requestMessage()
|
|
|
|
let (unlockState, responseData) = await send(request, route: route)
|
|
|
|
|
|
|
|
guard let response = responseData?.message else {
|
2023-12-12 23:46:51 +01:00
|
|
|
return (unlockState, nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
switch response.messageType {
|
|
|
|
case .initial, .request:
|
|
|
|
print("Invalid message type for response: \(response)")
|
2023-12-12 23:46:51 +01:00
|
|
|
return (response.with(result: .invalidMessageTypeFromDevice), nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
case .challenge:
|
|
|
|
// New challenge received, challenge was expired
|
2023-12-12 23:46:51 +01:00
|
|
|
return (unlockState, responseData)
|
2023-12-12 17:33:42 +01:00
|
|
|
case .response:
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
guard response.serverChallenge == request.serverChallenge else {
|
|
|
|
print("Invalid server challenge for unlock: \(response)")
|
2023-12-12 23:46:51 +01:00
|
|
|
return (response.with(result: .invalidServerChallengeFromDevice), nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
return (response.with(result: .unlocked), nil)
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private func url(for route: TransmissionType) -> String {
|
|
|
|
switch route {
|
|
|
|
case .throughServer:
|
|
|
|
return serverPath
|
|
|
|
case .overLocalWifi:
|
|
|
|
return localAddress
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func send(_ message: Message, route: TransmissionType) async -> ServerResponse {
|
|
|
|
guard let keys = keyManager.getAllKeys() else {
|
|
|
|
return (message.with(result: .noKeyAvailable), nil)
|
|
|
|
}
|
|
|
|
let url = url(for: route)
|
|
|
|
return await client.send(message, to: url, through: route, using: keys)
|
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
|
|
|
|
func resetState() {
|
|
|
|
let hasKeys = keyManager.hasAllKeys
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.state = hasKeys ? .notChecked : .noKeyAvailable
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func scheduleReturnToReadyState() {
|
|
|
|
timer?.invalidate()
|
|
|
|
|
2023-12-12 17:33:42 +01:00
|
|
|
DispatchQueue.main.async {
|
2023-12-12 23:46:51 +01:00
|
|
|
self.timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { [weak self] timer in
|
|
|
|
defer { timer.invalidate() }
|
2023-12-12 17:33:42 +01:00
|
|
|
guard let self else {
|
|
|
|
return
|
|
|
|
}
|
2023-12-12 23:46:51 +01:00
|
|
|
self.resetState()
|
|
|
|
self.timer = nil
|
2023-12-12 17:33:42 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|