Refactor task usage and profile auto update
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ public class ProfileServer {
|
||||
if state == .ready {
|
||||
Task.detached {
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_MSEC * 100)
|
||||
ProfileConnection(connection).process()
|
||||
await ProfileConnection(connection).process()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,9 @@ public class ProfileServer {
|
||||
self.connection = NWSocket(connection)
|
||||
}
|
||||
|
||||
func process() {
|
||||
func process() async {
|
||||
do {
|
||||
try writeProfilePreviewList()
|
||||
try await writeProfilePreviewList()
|
||||
} catch {
|
||||
NSLog("profile server: write profile list: \(error.localizedDescription)")
|
||||
writeError(error.localizedDescription)
|
||||
@@ -63,44 +63,51 @@ public class ProfileServer {
|
||||
let messageType = Int64(data[0])
|
||||
switch messageType {
|
||||
case LibboxMessageTypeProfileContentRequest:
|
||||
var error: NSError?
|
||||
let request = LibboxDecodeProfileContentRequest(data, &error)
|
||||
if let error {
|
||||
throw error
|
||||
Task {
|
||||
try await processProfileContentRequest(data)
|
||||
}
|
||||
|
||||
let profile = try ProfileManager.get(request!.profileID)
|
||||
guard let profile else {
|
||||
throw NSError(domain: "profile not found", code: 0)
|
||||
}
|
||||
let content = LibboxProfileContent()
|
||||
content.name = profile.name
|
||||
switch profile.type {
|
||||
case .local:
|
||||
content.type = LibboxProfileTypeLocal
|
||||
case .icloud:
|
||||
content.type = LibboxProfileTypeiCloud
|
||||
case .remote:
|
||||
content.type = LibboxProfileTypeRemote
|
||||
}
|
||||
content.config = try profile.read()
|
||||
if profile.type != .local {
|
||||
content.remotePath = profile.remoteURL!
|
||||
}
|
||||
if profile.type == .remote {
|
||||
content.autoUpdate = profile.autoUpdate
|
||||
if let lastUpdated = profile.lastUpdated {
|
||||
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
try connection.write(content.encode())
|
||||
default:
|
||||
throw NSError(domain: "unexpected message type \(messageType)", code: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private func writeProfilePreviewList() throws {
|
||||
let profiles = try ProfileManager.list()
|
||||
private func processProfileContentRequest(_ data: Data) async throws {
|
||||
var error: NSError?
|
||||
let request = LibboxDecodeProfileContentRequest(data, &error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
|
||||
let profile = try await ProfileManager.get(request!.profileID)
|
||||
guard let profile else {
|
||||
throw NSError(domain: "profile not found", code: 0)
|
||||
}
|
||||
let content = LibboxProfileContent()
|
||||
content.name = profile.name
|
||||
switch profile.type {
|
||||
case .local:
|
||||
content.type = LibboxProfileTypeLocal
|
||||
case .icloud:
|
||||
content.type = LibboxProfileTypeiCloud
|
||||
case .remote:
|
||||
content.type = LibboxProfileTypeRemote
|
||||
}
|
||||
content.config = try profile.read()
|
||||
if profile.type != .local {
|
||||
content.remotePath = profile.remoteURL!
|
||||
}
|
||||
if profile.type == .remote {
|
||||
content.autoUpdate = profile.autoUpdate
|
||||
content.autoUpdateInterval = profile.autoUpdateInterval
|
||||
if let lastUpdated = profile.lastUpdated {
|
||||
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
try connection.write(content.encode())
|
||||
}
|
||||
|
||||
private func writeProfilePreviewList() async throws {
|
||||
let profiles = try await ProfileManager.list()
|
||||
let encoder = LibboxProfileEncoder()
|
||||
for profile in profiles {
|
||||
let preview = LibboxProfilePreview()
|
||||
|
||||
@@ -37,8 +37,8 @@ public class CommandClient: ObservableObject {
|
||||
if let connectTask {
|
||||
connectTask.cancel()
|
||||
}
|
||||
connectTask = Task.detached {
|
||||
await self.connect0()
|
||||
connectTask = Task {
|
||||
await connect0()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ public class CommandClient: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func connect0() async {
|
||||
private nonisolated func connect0() async {
|
||||
let clientOptions = LibboxCommandClientOptions()
|
||||
switch connectionType {
|
||||
case .status:
|
||||
@@ -73,7 +73,9 @@ public class CommandClient: ObservableObject {
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
try client.connect()
|
||||
commandClient = client
|
||||
await MainActor.run {
|
||||
commandClient = client
|
||||
}
|
||||
return
|
||||
} catch {}
|
||||
try Task.checkCancellation()
|
||||
@@ -90,19 +92,19 @@ public class CommandClient: ObservableObject {
|
||||
self.commandClient = commandClient
|
||||
}
|
||||
|
||||
func connected() {
|
||||
DispatchQueue.main.sync {
|
||||
nonisolated func connected() {
|
||||
Task { @MainActor [self] in
|
||||
self.commandClient.isConnected = true
|
||||
}
|
||||
}
|
||||
|
||||
func disconnected(_: String?) {
|
||||
DispatchQueue.main.sync {
|
||||
nonisolated func disconnected(_: String?) {
|
||||
Task { @MainActor [self] in
|
||||
self.commandClient.isConnected = false
|
||||
}
|
||||
}
|
||||
|
||||
func writeLog(_ message: String?) {
|
||||
nonisolated func writeLog(_ message: String?) {
|
||||
guard let message else {
|
||||
return
|
||||
}
|
||||
@@ -111,18 +113,18 @@ public class CommandClient: ObservableObject {
|
||||
logList.removeFirst()
|
||||
}
|
||||
logList.append(message)
|
||||
DispatchQueue.main.sync {
|
||||
Task { @MainActor [self, logList] in
|
||||
self.commandClient.logList = logList
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatus(_ message: LibboxStatusMessage?) {
|
||||
DispatchQueue.main.sync {
|
||||
nonisolated func writeStatus(_ message: LibboxStatusMessage?) {
|
||||
Task { @MainActor [self] in
|
||||
self.commandClient.status = message
|
||||
}
|
||||
}
|
||||
|
||||
func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) {
|
||||
nonisolated func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) {
|
||||
guard let groups else {
|
||||
return
|
||||
}
|
||||
@@ -130,20 +132,20 @@ public class CommandClient: ObservableObject {
|
||||
while groups.hasNext() {
|
||||
newGroups.append(groups.next()!)
|
||||
}
|
||||
DispatchQueue.main.sync {
|
||||
Task { @MainActor [self, newGroups] in
|
||||
self.commandClient.groups = newGroups
|
||||
}
|
||||
}
|
||||
|
||||
func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) {
|
||||
DispatchQueue.main.sync {
|
||||
nonisolated func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) {
|
||||
Task { @MainActor [self] in
|
||||
self.commandClient.clashModeList = modeList!.toArray()
|
||||
self.commandClient.clashMode = currentMode!
|
||||
}
|
||||
}
|
||||
|
||||
func updateClashMode(_ newMode: String?) {
|
||||
DispatchQueue.main.sync {
|
||||
nonisolated func updateClashMode(_ newMode: String?) {
|
||||
Task { @MainActor [self] in
|
||||
self.commandClient.clashMode = newMode!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,24 @@ import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
|
||||
func runBlocking<T>(_ body: @escaping () async throws -> T) throws -> T {
|
||||
func runBlocking<T>(_ block: @escaping () async -> T) -> T {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let box = resultBox<T>()
|
||||
Task {
|
||||
Task.detached {
|
||||
let value = await block()
|
||||
box.result0 = value
|
||||
semaphore.signal()
|
||||
}
|
||||
semaphore.wait()
|
||||
return box.result0
|
||||
}
|
||||
|
||||
func runBlocking<T>(_ tBlock: @escaping () async throws -> T) throws -> T {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let box = resultBox<T>()
|
||||
Task.detached {
|
||||
do {
|
||||
let value = try await body()
|
||||
let value = try await tBlock()
|
||||
box.result = .success(value)
|
||||
} catch {
|
||||
box.result = .failure(error)
|
||||
@@ -20,4 +32,5 @@ func runBlocking<T>(_ body: @escaping () async throws -> T) throws -> T {
|
||||
|
||||
private class resultBox<T> {
|
||||
var result: Result<T, Error>!
|
||||
var result0: T!
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@ public class ExtensionEnvironments: ObservableObject {
|
||||
}
|
||||
|
||||
public func postReload() {
|
||||
Task.detached {
|
||||
await self.reload()
|
||||
Task {
|
||||
await reload()
|
||||
}
|
||||
}
|
||||
|
||||
public func reload() async {
|
||||
public nonisolated func reload() async {
|
||||
if let newProfile = try? await ExtensionProfile.load() {
|
||||
if extensionProfile == nil || extensionProfile?.status == .invalid {
|
||||
newProfile.register()
|
||||
|
||||
@@ -11,6 +11,12 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
|
||||
}
|
||||
|
||||
public func openTun(_ options: LibboxTunOptionsProtocol?, ret0_: UnsafeMutablePointer<Int32>?) throws {
|
||||
try runBlocking {
|
||||
try await self.openTun0(options, ret0_)
|
||||
}
|
||||
}
|
||||
|
||||
private func openTun0(_ options: LibboxTunOptionsProtocol?, _ ret0_: UnsafeMutablePointer<Int32>?) async throws {
|
||||
guard let options else {
|
||||
throw NSError(domain: "nil options", code: 0)
|
||||
}
|
||||
@@ -82,7 +88,7 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
|
||||
let proxyServer = NEProxyServer(address: options.getHTTPProxyServer(), port: Int(options.getHTTPProxyServerPort()))
|
||||
proxySettings.httpServer = proxyServer
|
||||
proxySettings.httpsServer = proxyServer
|
||||
if SharedPreferences.systemProxyEnabled {
|
||||
if try await SharedPreferences.systemProxyEnabled.get() {
|
||||
proxySettings.httpEnabled = true
|
||||
proxySettings.httpsEnabled = true
|
||||
}
|
||||
@@ -169,7 +175,9 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
|
||||
}
|
||||
|
||||
public func serviceReload() throws {
|
||||
tunnel.reloadService()
|
||||
Task {
|
||||
await tunnel.reloadService()
|
||||
}
|
||||
}
|
||||
|
||||
public func getSystemProxyStatus() -> LibboxSystemProxyStatus? {
|
||||
|
||||
@@ -14,10 +14,6 @@ public class ExtensionProfile: ObservableObject {
|
||||
status = manager.connection.status
|
||||
}
|
||||
|
||||
deinit {
|
||||
unregister()
|
||||
}
|
||||
|
||||
public func register() {
|
||||
observer = NotificationCenter.default.addObserver(
|
||||
forName: NSNotification.Name.NEVPNStatusDidChange,
|
||||
@@ -54,13 +50,13 @@ public class ExtensionProfile: ObservableObject {
|
||||
|
||||
public func start() async throws {
|
||||
manager.isEnabled = true
|
||||
if SharedPreferences.alwaysOn {
|
||||
if try await SharedPreferences.alwaysOn.get() {
|
||||
manager.isOnDemandEnabled = true
|
||||
setOnDemandRules()
|
||||
}
|
||||
#if !os(tvOS)
|
||||
if let protocolConfiguration = manager.protocolConfiguration {
|
||||
let includeAllNetworks = SharedPreferences.includeAllNetworks
|
||||
let includeAllNetworks = try await SharedPreferences.includeAllNetworks.get()
|
||||
protocolConfiguration.includeAllNetworks = includeAllNetworks
|
||||
if #available(iOS 16.4, macOS 13.3, *) {
|
||||
protocolConfiguration.excludeCellularServices = !includeAllNetworks
|
||||
|
||||
@@ -13,8 +13,6 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
private var platformInterface: ExtensionPlatformInterface!
|
||||
|
||||
override open func startTunnel(options _: [String: NSObject]?) async throws {
|
||||
NSLog("Here I am")
|
||||
|
||||
try? FileManager.default.removeItem(at: ExtensionProvider.errorFile)
|
||||
|
||||
do {
|
||||
@@ -45,12 +43,12 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
writeError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
LibboxSetMemoryLimit(!SharedPreferences.disableMemoryLimit)
|
||||
try await LibboxSetMemoryLimit(!SharedPreferences.disableMemoryLimit.get())
|
||||
|
||||
if platformInterface == nil {
|
||||
platformInterface = ExtensionPlatformInterface(self)
|
||||
}
|
||||
commandServer = LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines))
|
||||
commandServer = try await LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines.get()))
|
||||
do {
|
||||
try commandServer.start()
|
||||
} catch {
|
||||
@@ -58,8 +56,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
return
|
||||
}
|
||||
writeMessage("(packet-tunnel) log server started")
|
||||
|
||||
startService()
|
||||
await startService()
|
||||
}
|
||||
|
||||
func writeMessage(_ message: String) {
|
||||
@@ -83,10 +80,10 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
cancelTunnelWithError(NSError(domain: message, code: 0))
|
||||
}
|
||||
|
||||
private func startService() {
|
||||
private func startService() async {
|
||||
let profile: Profile?
|
||||
do {
|
||||
profile = try ProfileManager.get(Int64(SharedPreferences.selectedProfileID))
|
||||
profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get()))
|
||||
} catch {
|
||||
writeFatalError("(packet-tunnel) error: missing default profile: \(error.localizedDescription)")
|
||||
return
|
||||
@@ -97,7 +94,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
}
|
||||
let configContent: String
|
||||
do {
|
||||
configContent = try profile.read()
|
||||
configContent = try await profile.read()
|
||||
} catch {
|
||||
writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)")
|
||||
return
|
||||
@@ -120,9 +117,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
boxService = service
|
||||
commandServer.setService(service)
|
||||
#if os(macOS)
|
||||
Task.detached {
|
||||
SharedPreferences.startedByUser = true
|
||||
}
|
||||
await SharedPreferences.startedByUser.set(true)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -138,14 +133,14 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
}
|
||||
}
|
||||
|
||||
func reloadService() {
|
||||
func reloadService() async {
|
||||
writeMessage("(packet-tunnel) reloading service")
|
||||
reasserting = true
|
||||
defer {
|
||||
reasserting = false
|
||||
}
|
||||
stopService()
|
||||
startService()
|
||||
await startService()
|
||||
}
|
||||
|
||||
override open func stopTunnel(with reason: NEProviderStopReason) async {
|
||||
@@ -158,7 +153,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
}
|
||||
#if os(macOS)
|
||||
if reason == .userInitiated {
|
||||
SharedPreferences.startedByUser = reason == .userInitiated
|
||||
await SharedPreferences.startedByUser.set(reason == .userInitiated)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -76,26 +76,30 @@
|
||||
}
|
||||
|
||||
public static func isInstalled() async -> Bool {
|
||||
await (try? Task.detached {
|
||||
for _ in 0 ..< 3 {
|
||||
do {
|
||||
let propList = try SystemExtension().getProperties()
|
||||
if propList.isEmpty {
|
||||
return false
|
||||
}
|
||||
for extensionProp in propList {
|
||||
if !extensionProp.isAwaitingUserApproval, !extensionProp.isUninstalling {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
|
||||
}
|
||||
}
|
||||
return false
|
||||
await (try? Task {
|
||||
try await isInstalledBackground()
|
||||
}.result.get()) == true
|
||||
}
|
||||
|
||||
public nonisolated static func isInstalledBackground() async throws -> Bool {
|
||||
for _ in 0 ..< 3 {
|
||||
do {
|
||||
let propList = try SystemExtension().getProperties()
|
||||
if propList.isEmpty {
|
||||
return false
|
||||
}
|
||||
for extensionProp in propList {
|
||||
if !extensionProp.isAwaitingUserApproval, !extensionProp.isUninstalling {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public static func install(forceUpdate: Bool = false, inBackground _: Bool = false) async throws -> OSSystemExtensionRequest.Result? {
|
||||
try await Task.detached {
|
||||
try SystemExtension(forceUpdate: forceUpdate).submitAndWait()
|
||||
|
||||
Reference in New Issue
Block a user