Refactor task usage and profile auto update

This commit is contained in:
世界
2023-09-22 11:32:51 +08:00
parent 390e063f20
commit 3374f8e727
49 changed files with 823 additions and 636 deletions
+6 -3
View File
@@ -1,7 +1,7 @@
import Foundation
import GRDB
class Database {
actor Database {
private static var writer: (any DatabaseWriter)?
static func sharedWriter() throws -> any DatabaseWriter {
@@ -11,8 +11,6 @@ class Database {
try FileManager.default.createDirectory(at: FilePath.sharedDirectory, withIntermediateDirectories: true)
let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath)
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
migrator.eraseDatabaseOnSchemaChange = true
migrator.registerMigration("initialize") { db in
try db.create(table: "profiles") { t in
t.autoIncrementedPrimaryKey("id")
@@ -29,6 +27,11 @@ class Database {
t.column("data", .blob)
}
}
migrator.registerMigration("add_auto_update_interval") { db in
try db.alter(table: "profiles") { t in
t.add(column: "autoUpdateInterval", .integer).notNull().defaults(to: 0)
}
}
try migrator.migrate(database)
writer = database
+4 -3
View File
@@ -14,6 +14,7 @@ public extension Profile {
}
if type == .remote {
content.autoUpdate = autoUpdate
content.autoUpdateInterval = autoUpdateInterval
if let lastUpdated {
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
}
@@ -41,8 +42,8 @@ public extension LibboxProfileContent {
return content!
}
func importProfile() throws {
let nextProfileID = try ProfileManager.nextID()
func importProfile() async throws {
let nextProfileID = try await ProfileManager.nextID()
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
@@ -51,7 +52,7 @@ public extension LibboxProfileContent {
if lastUpdated > 0 {
lastUpdatedAt = Date(timeIntervalSince1970: Double(lastUpdated))
}
try ProfileManager.create(Profile(name: name, type: ProfileType(rawValue: Int(type))!, path: profileConfig.relativePath, remoteURL: remotePath, autoUpdate: autoUpdate, lastUpdated: lastUpdatedAt))
try await ProfileManager.create(Profile(name: name, type: ProfileType(rawValue: Int(type))!, path: profileConfig.relativePath, remoteURL: remotePath, autoUpdate: autoUpdate, autoUpdateInterval: autoUpdateInterval, lastUpdated: lastUpdatedAt))
}
func generateShareFile() throws -> URL {
+2 -2
View File
@@ -3,7 +3,7 @@ import GRDB
import Libbox
public extension Profile {
func updateRemoteProfile() throws {
nonisolated func updateRemoteProfile() async throws {
if type != .remote {
return
}
@@ -15,6 +15,6 @@ public extension Profile {
}
try write(remoteContent)
lastUpdated = Date()
try ProfileManager.update(self)
try await ProfileManager.update(self)
}
}
+6 -2
View File
@@ -14,9 +14,10 @@ public class Profile: Record, Identifiable, ObservableObject {
public var path: String
@Published public var remoteURL: String?
@Published public var autoUpdate: Bool
@Published public var autoUpdateInterval: Int32
public var lastUpdated: Date?
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil, autoUpdate: Bool = false, lastUpdated: Date? = nil) {
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil, autoUpdate: Bool = false, autoUpdateInterval: Int32 = 0, lastUpdated: Date? = nil) {
self.id = id
self.name = name
self.order = order
@@ -24,6 +25,7 @@ public class Profile: Record, Identifiable, ObservableObject {
self.path = path
self.remoteURL = remoteURL
self.autoUpdate = autoUpdate
self.autoUpdateInterval = autoUpdateInterval
self.lastUpdated = lastUpdated
super.init()
}
@@ -33,7 +35,7 @@ public class Profile: Record, Identifiable, ObservableObject {
}
enum Columns: String, ColumnExpression {
case id, name, order, type, path, remoteURL, autoUpdate, lastUpdated, userAgent
case id, name, order, type, path, remoteURL, autoUpdate, autoUpdateInterval, lastUpdated, userAgent
}
required init(row: Row) throws {
@@ -44,6 +46,7 @@ public class Profile: Record, Identifiable, ObservableObject {
path = row[Columns.path] ?? ""
remoteURL = row[Columns.remoteURL] ?? ""
autoUpdate = row[Columns.autoUpdate] ?? false
autoUpdateInterval = row[Columns.autoUpdateInterval] ?? 0
lastUpdated = row[Columns.lastUpdated] ?? Date()
try super.init(row: row)
}
@@ -56,6 +59,7 @@ public class Profile: Record, Identifiable, ObservableObject {
container[Columns.path] = path
container[Columns.remoteURL] = remoteURL
container[Columns.autoUpdate] = autoUpdate
container[Columns.autoUpdateInterval] = autoUpdateInterval
container[Columns.lastUpdated] = lastUpdated
}
+29 -29
View File
@@ -2,86 +2,86 @@ import Foundation
import GRDB
public enum ProfileManager {
public static func create(_ profile: Profile) throws {
profile.order = try nextOrder()
try Database.sharedWriter().write { db in
public nonisolated static func create(_ profile: Profile) async throws {
profile.order = try await nextOrder()
try await Database.sharedWriter().write { db in
try profile.insert(db, onConflict: .fail)
}
}
public static func get(_ profileID: Int64) throws -> Profile? {
try Database.sharedWriter().read { db in
public nonisolated static func get(_ profileID: Int64) async throws -> Profile? {
try await Database.sharedWriter().read { db in
try Profile.fetchOne(db, id: profileID)
}
}
public static func get(by profileName: String) throws -> Profile? {
try Database.sharedWriter().read { db in
public nonisolated static func get(by profileName: String) async throws -> Profile? {
try await Database.sharedWriter().read { db in
try Profile.filter(Column("name") == profileName).fetchOne(db)
}
}
public static func delete(_ profile: Profile) throws {
_ = try Database.sharedWriter().write { db in
public nonisolated static func delete(_ profile: Profile) async throws {
_ = try await Database.sharedWriter().write { db in
try profile.delete(db)
}
}
public static func delete(by id: Int64) throws {
_ = try Database.sharedWriter().write { db in
public nonisolated static func delete(by id: Int64) async throws {
_ = try await Database.sharedWriter().write { db in
try Profile.deleteOne(db, id: id)
}
}
public static func delete(_ profileList: [Profile]) throws -> Int {
try Database.sharedWriter().write { db in
public nonisolated static func delete(_ profileList: [Profile]) async throws -> Int {
try await Database.sharedWriter().write { db in
try Profile.deleteAll(db, keys: profileList.map {
["id": $0.id!]
})
}
}
public static func delete(by id: [Int64]) throws -> Int {
try Database.sharedWriter().write { db in
public nonisolated static func delete(by id: [Int64]) async throws -> Int {
try await Database.sharedWriter().write { db in
try Profile.deleteAll(db, ids: id)
}
}
public static func update(_ profile: Profile) throws {
_ = try Database.sharedWriter().write { db in
public nonisolated static func update(_ profile: Profile) async throws {
_ = try await Database.sharedWriter().write { db in
try profile.updateChanges(db)
}
}
public static func update(_ profileList: [Profile]) throws {
public nonisolated static func update(_ profileList: [Profile]) async throws {
// TODO: batch update
try Database.sharedWriter().write { db in
try await Database.sharedWriter().write { db in
for profile in profileList {
try profile.updateChanges(db)
}
}
}
public static func list() throws -> [Profile] {
try Database.sharedWriter().read { db in
public nonisolated static func list() async throws -> [Profile] {
try await Database.sharedWriter().read { db in
try Profile.all().order(Column("order").asc).fetchAll(db)
}
}
public static func listRemote() throws -> [Profile] {
try Database.sharedWriter().read { db in
public nonisolated static func listRemote() async throws -> [Profile] {
try await Database.sharedWriter().read { db in
try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db)
}
}
public static func listAutoUpdateEnabled() throws -> [Profile] {
try Database.sharedWriter().read { db in
public nonisolated static func listAutoUpdateEnabled() async throws -> [Profile] {
try await Database.sharedWriter().read { db in
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
}
}
public static func nextID() throws -> Int64 {
try Database.sharedWriter().read { db in
public nonisolated static func nextID() async throws -> Int64 {
try await Database.sharedWriter().read { db in
if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) {
return lastProfile.id! + 1
} else {
@@ -90,8 +90,8 @@ public enum ProfileManager {
}
}
private static func nextOrder() throws -> UInt32 {
try Database.sharedWriter().read { db in
private nonisolated static func nextOrder() async throws -> UInt32 {
try await Database.sharedWriter().read { db in
try UInt32(Profile.fetchCount(db))
}
}
@@ -3,7 +3,7 @@ import Foundation
import GRDB
extension SharedPreferences {
@propertyWrapper public class Preference<T: Codable> {
public class Preference<T: Codable> {
private let name: String
private let defaultValue: T
@@ -12,53 +12,32 @@ extension SharedPreferences {
self.defaultValue = defaultValue
}
public var wrappedValue: T {
get {
do {
return try SharedPreferences.read(name) ?? defaultValue
} catch {
NSLog("read preferences error: \(error)")
return defaultValue
}
public nonisolated func get() async -> T {
do {
return try await SharedPreferences.read(name) ?? defaultValue
} catch {
NSLog("read preferences error: \(error)")
return defaultValue
}
set {
do {
try SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
public func getBlocking() -> T {
runBlocking { [self] in
await get()
}
}
public nonisolated func set(_ newValue: T) async {
do {
try await SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
}
@propertyWrapper public class NullablePreference<T: Codable> {
private let name: String
init(_ name: String) {
self.name = name
}
public var wrappedValue: T? {
get {
do {
return try SharedPreferences.read(name)
} catch {
NSLog("read preferences error: \(error)")
return nil
}
}
set {
do {
try SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
}
}
private static func read<T: Codable>(_ name: String) throws -> T? {
guard let item = try (Database.sharedWriter().read { db in
private nonisolated static func read<T: Codable>(_ name: String) async throws -> T? {
guard let item = try await (Database.sharedWriter().read { db in
try Item.fetchOne(db, id: name)
})
else {
@@ -67,14 +46,14 @@ extension SharedPreferences {
return try BinaryDecoder().decode(from: item.data)
}
private static func write(_ name: String, _ value: (some Codable)?) throws {
private nonisolated static func write(_ name: String, _ value: (some Codable)?) async throws {
if value == nil {
_ = try Database.sharedWriter().write { db in
_ = try await Database.sharedWriter().write { db in
try Item.deleteOne(db, id: name)
}
} else {
let data = try BinaryEncoder().encode(value)
try Database.sharedWriter().write { db in
try await Database.sharedWriter().write { db in
try Item(name: name, data: data).insert(db)
}
}
+11 -10
View File
@@ -1,31 +1,32 @@
import Foundation
public enum SharedPreferences {
@Preference<Int64>("selected_profile_id", defaultValue: -1) public static var selectedProfileID
public static let selectedProfileID = Preference<Int64>("selected_profile_id", defaultValue: -1)
#if os(macOS)
private static let disableMemoryLimitByDefault = true
#else
private static let disableMemoryLimitByDefault = false
#endif
@Preference<Bool>("disable_memory_limit", defaultValue: disableMemoryLimitByDefault) public static var disableMemoryLimit
public static let disableMemoryLimit = Preference<Bool>("disable_memory_limit", defaultValue: disableMemoryLimitByDefault)
#if !os(tvOS)
@Preference<Bool>("include_all_networks", defaultValue: false) public static var includeAllNetworks
public static let includeAllNetworks = Preference<Bool>("include_all_networks", defaultValue: false)
#endif
@Preference<Int>("max_log_lines", defaultValue: 300) public static var maxLogLines
@Preference<Bool>("always_on", defaultValue: false) public static var alwaysOn
public static let maxLogLines = Preference<Int>("max_log_lines", defaultValue: 300)
public static let alwaysOn = Preference<Bool>("always_on", defaultValue: false)
#if os(macOS)
@Preference<Bool>("show_menu_bar_extra", defaultValue: true) public static var showMenuBarExtra
@Preference<Bool>("menu_bar_extra_in_background", defaultValue: false) public static var menuBarExtraInBackground
@Preference<Bool>("started_by_user", defaultValue: false) public static var startedByUser
public static let showMenuBarExtra = Preference<Bool>("show_menu_bar_extra", defaultValue: true)
public static let menuBarExtraInBackground = Preference<Bool>("menu_bar_extra_in_background", defaultValue: false)
public static let startedByUser = Preference<Bool>("started_by_user", defaultValue: false)
#endif
#if os(iOS)
@Preference<Bool>("network_permission_requested", defaultValue: false) public static var networkPermissionRequested
public static let networkPermissionRequested = Preference<Bool>("network_permission_requested", defaultValue: false)
#endif
@Preference<Bool>("system_proxy_enabled", defaultValue: true) public static var systemProxyEnabled
public static let systemProxyEnabled = Preference<Bool>("system_proxy_enabled", defaultValue: true)
}