punchnet-macos/punchnet/Views/Network/NetworkModel.swift
2026-03-03 14:46:14 +08:00

122 lines
2.7 KiB
Swift

//
// NetworkState.swift
// punchnet
//
// Created by on 2026/1/16.
//
import Foundation
import Observation
//
struct Resource: Codable {
var id: Int
var name: String
var url: String
var connectionStatus: String
enum CodingKeys: String, CodingKey {
case id
case name
case url
case connectionStatus = "connection_status"
}
}
//
struct Node: Codable {
var id: Int
var name: String
var ip: String
var system: String?
var connectionStatus: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
enum CodingKeys: String, CodingKey {
case id
case name
case ip
case system
case connectionStatus = "connection_status"
}
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
}
//
struct NetworkContext: Codable {
let ip: String
let maskLen: UInt8
let hostname: String
let identityId: UInt32
let resourceList: [Resource]
let nodeList: [Node]
enum CodingKeys: String, CodingKey {
case ip
case maskLen = "mask_len"
case hostname
case identityId = "identity_id"
case resourceList = "resource_list"
case nodeList = "node_list"
}
static func `default`() -> Self {
return .init(ip: "", maskLen: 24, hostname: "", identityId: 0, resourceList: [], nodeList: [])
}
}
//
struct NodeDetail: Codable {
let id: Int
let name: String
let ip: String
let system: String?
let connectionStatus: String
let resourceList: [Resource]
enum CodingKeys: String, CodingKey {
case id
case name
case ip
case system
case connectionStatus = "connection_status"
case resourceList = "resource_list"
}
}
@Observable
class NetworkModel {
//
var selectedNode: Node?
var networkContext: NetworkContext = .default()
init() {
}
func changeSelectedNode(nodeId: Int?) {
if let nodeId {
if let node = self.networkContext.nodeList.first(where: { $0.id == nodeId}) {
self.selectedNode = node
}
}
}
func connect(networkSession: UserContext.NetworkSession) async throws {
let params: [String: Any] = [
"client_id": SystemConfig.getClientId(),
"access_token": networkSession.accessToken
]
self.networkContext = try await SDLAPIClient.doPost(path: "/connect", params: params, as: NetworkContext.self)
}
}