Init commit

This commit is contained in:
世界
2023-07-15 15:03:45 +08:00
commit f441b89efb
122 changed files with 7355 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import Foundation
import GRDB
class Database {
private static var writer: (any DatabaseWriter)?
static func sharedWriter() throws -> any DatabaseWriter {
if let writer {
return writer
}
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")
t.column("name", .text).notNull()
t.column("order", .integer).notNull()
t.column("type", .integer).notNull().defaults(to: ProfileType.local.rawValue)
t.column("path", .text).notNull()
t.column("remoteURL", .text)
t.column("autoUpdate", .boolean).notNull().defaults(to: false)
t.column("lastUpdated", .datetime)
}
try db.create(table: "preferences") { t in
t.primaryKey("name", .text, onConflict: .replace).notNull()
t.column("data", .blob)
}
}
try migrator.migrate(database)
writer = database
return database
}
}
+16
View File
@@ -0,0 +1,16 @@
//
// Profile+Date.swift
// Library
//
// Created by on 2023/6/29.
//
import Foundation
public extension Profile {
var lastUpdatedString: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: lastUpdated!)
}
}
+11
View File
@@ -0,0 +1,11 @@
import Foundation
extension Profile: Hashable {
public static func == (lhs: Profile, rhs: Profile) -> Bool {
lhs.id == rhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
+31
View File
@@ -0,0 +1,31 @@
import Foundation
public extension Profile {
func read() throws -> String {
switch type {
case .local, .remote:
return try String(contentsOfFile: path)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
return try String(contentsOf: saveURL)
}
}
func write(_ content: String) throws {
switch type {
case .local, .remote:
try content.write(toFile: path, atomically: true, encoding: .utf8)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
try content.write(to: saveURL, atomically: true, encoding: .utf8)
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import Foundation
import GRDB
import Libbox
public extension Profile {
func updateRemoteProfile() throws {
if type != .remote {
return
}
let remoteContent = try HTTPClient().getString(remoteURL)
var error: NSError?
LibboxCheckConfig(remoteContent, &error)
if let error {
throw error
}
try write(remoteContent)
lastUpdated = Date()
try ProfileManager.update(self)
}
}
+73
View File
@@ -0,0 +1,73 @@
import Foundation
import GRDB
public class Profile: Record, Identifiable, ObservableObject {
public var id: Int64?
public var mustID: Int64 {
id!
}
@Published public var name: String
public var order: UInt32
public var type: ProfileType
public var path: String
@Published public var remoteURL: String?
@Published public var autoUpdate: Bool
public var lastUpdated: Date?
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil) {
self.id = id
self.name = name
self.order = order
self.type = type
self.path = path
self.remoteURL = remoteURL
autoUpdate = false
lastUpdated = nil
if type == .remote {
lastUpdated = Date()
}
super.init()
}
override public class var databaseTableName: String {
"profiles"
}
enum Columns: String, ColumnExpression {
case id, name, order, type, path, remoteURL, autoUpdate, lastUpdated, userAgent
}
required init(row: Row) throws {
id = row[Columns.id]
name = row[Columns.name] ?? ""
order = row[Columns.order] ?? 0
type = ProfileType(rawValue: row[Columns.type] ?? ProfileType.local.rawValue)!
path = row[Columns.path] ?? ""
remoteURL = row[Columns.remoteURL] ?? ""
autoUpdate = row[Columns.autoUpdate] ?? false
lastUpdated = row[Columns.lastUpdated] ?? Date()
try super.init(row: row)
}
override public func encode(to container: inout PersistenceContainer) throws {
container[Columns.id] = id
container[Columns.name] = name
container[Columns.order] = order
container[Columns.type] = type.rawValue
container[Columns.path] = path
container[Columns.remoteURL] = remoteURL
container[Columns.autoUpdate] = autoUpdate
container[Columns.lastUpdated] = lastUpdated
}
override public func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
public enum ProfileType: Int {
case local = 0, icloud, remote
}
+98
View File
@@ -0,0 +1,98 @@
import Foundation
import GRDB
public enum ProfileManager {
public static func create(_ profile: Profile) throws {
profile.order = try nextOrder()
try 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
try Profile.fetchOne(db, id: profileID)
}
}
public static func get(by profileName: String) throws -> Profile? {
try 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
try profile.delete(db)
}
}
public static func delete(by id: Int64) throws {
_ = try 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
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
try Profile.deleteAll(db, ids: id)
}
}
public static func update(_ profile: Profile) throws {
_ = try Database.sharedWriter().write { db in
try profile.updateChanges(db)
}
}
public static func update(_ profileList: [Profile]) throws {
// TODO: batch update
try 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
try Profile.all().order(Column("order").asc).fetchAll(db)
}
}
public static func listRemote() throws -> [Profile] {
try 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
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
}
}
public static func nextID() throws -> Int64 {
try Database.sharedWriter().read { db in
if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) {
return lastProfile.id! + 1
} else {
return 1
}
}
}
private static func nextOrder() throws -> UInt32 {
try Database.sharedWriter().read { db in
try UInt32(Profile.fetchCount(db))
}
}
}
@@ -0,0 +1,116 @@
import BinaryCodable
import Foundation
import GRDB
extension SharedPreferences {
@propertyWrapper public class Preference<T: Codable> {
private let name: String
private let defaultValue: T
init(_ name: String, defaultValue: T) {
self.name = name
self.defaultValue = defaultValue
}
public var wrappedValue: T {
get {
do {
return try 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)")
}
}
}
}
@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
try Item.fetchOne(db, id: name)
})
else {
return nil
}
return try BinaryDecoder().decode(from: item.data)
}
private static func write(_ name: String, _ value: (some Codable)?) throws {
if value == nil {
_ = try 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 Item(name: name, data: data).insert(db)
}
}
}
}
private class Item: Record, Identifiable {
public var id: String {
name
}
public var name: String
public var data: Data
init(name: String, data: Data) {
self.name = name
self.data = data
super.init()
}
override public class var databaseTableName: String {
"preferences"
}
enum Columns: String, ColumnExpression {
case name, data
}
required init(row: Row) throws {
name = row[Columns.name]
data = row[Columns.data]
try super.init(row: row)
}
override public func encode(to container: inout PersistenceContainer) throws {
container[Columns.name] = name
container[Columns.data] = data
}
}
+19
View File
@@ -0,0 +1,19 @@
import Foundation
public enum SharedPreferences {
@Preference<Int64>("selected_profile_id", defaultValue: -1) public static var selectedProfileID
#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
@Preference<Int>("max_log_lines", defaultValue: 300) public static var maxLogLines
#if os(macOS)
@Preference<Bool>("show_menu_bar_extra", defaultValue: true) public static var showMenuBarExtra
@Preference<Bool>("started_by_user", defaultValue: false) public static var startedByUser
#endif
}