yattee/Model/Accounts/InstancesModel.swift

71 lines
1.9 KiB
Swift
Raw Normal View History

2021-09-25 10:18:22 +02:00
import Defaults
import Foundation
final class InstancesModel: ObservableObject {
2021-11-09 00:14:28 +01:00
static var all: [Instance] {
2021-10-17 00:48:58 +02:00
Defaults[.instances]
}
2021-12-19 17:56:47 +01:00
static var forPlayer: Instance? {
guard let id = Defaults[.playerInstanceID] else {
return nil
}
return InstancesModel.find(id)
}
static var lastUsed: Instance? {
guard let id = Defaults[.lastInstanceID] else {
return nil
2021-09-27 00:03:33 +02:00
}
2021-09-29 12:14:43 +02:00
return InstancesModel.find(id)
2021-09-25 10:18:22 +02:00
}
static func find(_ id: Instance.ID?) -> Instance? {
2021-09-25 10:18:22 +02:00
guard id != nil else {
return nil
}
return Defaults[.instances].first { $0.id == id }
}
2021-10-21 00:21:50 +02:00
static func accounts(_ id: Instance.ID?) -> [Account] {
Defaults[.accounts].filter { $0.instanceID == id }
2021-09-25 10:18:22 +02:00
}
2021-10-21 00:21:50 +02:00
static func add(app: VideosApp, name: String, url: String) -> Instance {
2021-11-07 22:39:28 +01:00
let instance = Instance(
app: app, id: UUID().uuidString, name: name, apiURL: standardizedURL(url)
)
2021-09-25 10:18:22 +02:00
Defaults[.instances].append(instance)
return instance
}
2021-10-27 23:11:38 +02:00
static func setFrontendURL(_ instance: Instance, _ url: String) {
if let index = Defaults[.instances].firstIndex(where: { $0.id == instance.id }) {
var instance = Defaults[.instances][index]
2021-11-07 22:39:28 +01:00
instance.frontendURL = standardizedURL(url)
2021-10-27 23:11:38 +02:00
Defaults[.instances][index] = instance
}
}
static func remove(_ instance: Instance) {
2022-05-20 21:53:17 +02:00
let accounts = Self.accounts(instance.id)
2021-09-25 10:18:22 +02:00
if let index = Defaults[.instances].firstIndex(where: { $0.id == instance.id }) {
Defaults[.instances].remove(at: index)
accounts.forEach { AccountsModel.remove($0) }
2021-09-25 10:18:22 +02:00
}
}
2021-11-07 22:39:28 +01:00
static func standardizedURL(_ url: String) -> String {
2022-06-26 17:35:31 +02:00
if url.count > 7, url.last == "/" {
2021-11-07 22:39:28 +01:00
return String(url.dropLast())
} else {
return url
}
}
2021-09-25 10:18:22 +02:00
}