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
@@ -2,44 +2,59 @@ import Foundation
import Library import Library
public enum ProfileUpdateTask { public enum ProfileUpdateTask {
static let minUpdateInterval: TimeInterval = 15 * 60
static let defaultUpdateInterval: TimeInterval = 60 * 60
private static var timer: Timer? private static var timer: Timer?
public static func setup() throws { public static func configure() async throws {
var earliestBeginDate: Date? timer?.invalidate()
if let updatedAt = try oldestUpdated() { timer = nil
if updatedAt > Date(timeIntervalSinceNow: -taskInterval) { let profiles = try await ProfileManager.listAutoUpdateEnabled()
earliestBeginDate = updatedAt.addingTimeInterval(taskInterval) if profiles.isEmpty {
return
} }
var updateInterval = profiles.map { it in
it.autoUpdateIntervalOrDefault
}.min()!
if updateInterval < minUpdateInterval {
updateInterval = minUpdateInterval
} }
timer = Timer(fire: earliestBeginDate ?? Date.now, interval: taskInterval, repeats: true, block: { _ in timer = Timer(fire: calculateEarliestBeginDate(profiles), interval: updateInterval, repeats: true, block: { _ in
do { Task {
_ = try updateProfiles() await getAndupdateProfiles()
NSLog("profile update task succeed")
} catch {
NSLog("profile update task failed: \(error.localizedDescription)")
} }
}) })
} }
static let taskInterval: TimeInterval = 15 * 60 static func calculateEarliestBeginDate(_ profiles: [Profile]) -> Date {
let nowTime = Date.now
static func oldestUpdated() throws -> Date? { var earliestBeginDate = profiles.map { it in
let profiles = try ProfileManager.listAutoUpdateEnabled() it.lastUpdated!.addingTimeInterval(it.autoUpdateIntervalOrDefault)
return profiles.map { profile in }.min()!
profile.lastUpdated! if earliestBeginDate <= nowTime {
earliestBeginDate = nowTime
} }
.min() return earliestBeginDate
} }
static func updateProfiles() throws -> Bool { private nonisolated static func getAndupdateProfiles() async {
let profiles = try ProfileManager.listAutoUpdateEnabled() do {
_ = try await updateProfiles(ProfileManager.listAutoUpdateEnabled())
NSLog("profile update task succeed")
} catch {
NSLog("profile update task failed: \(error.localizedDescription)")
}
}
static func updateProfiles(_ profiles: [Profile]) async throws -> Bool {
var success = true var success = true
for profile in profiles { for profile in profiles {
if profile.lastUpdated! > Date(timeIntervalSinceNow: -taskInterval) { if profile.lastUpdated! > Date(timeIntervalSinceNow: -profile.autoUpdateIntervalOrDefault) {
continue continue
} }
do { do {
try profile.updateRemoteProfile() try await profile.updateRemoteProfile()
} catch { } catch {
NSLog("Update profile \(profile.name) failed: \(error.localizedDescription)") NSLog("Update profile \(profile.name) failed: \(error.localizedDescription)")
success = false success = false
@@ -48,3 +63,13 @@ public enum ProfileUpdateTask {
return success return success
} }
} }
extension Profile {
var autoUpdateIntervalOrDefault: TimeInterval {
if autoUpdateInterval > 0 {
return TimeInterval(autoUpdateInterval * 60)
} else {
return ProfileUpdateTask.defaultUpdateInterval
}
}
}
@@ -4,14 +4,39 @@ import Library
#if os(iOS) || os(tvOS) #if os(iOS) || os(tvOS)
public class UIProfileUpdateTask: BGAppRefreshTask { public class UIProfileUpdateTask: BGAppRefreshTask {
public static let taskSchedulerPermittedIdentifier = "\(FilePath.packageName).update_profiles" private static let taskSchedulerPermittedIdentifier = "\(FilePath.packageName).update_profiles"
public static func setup() async throws { public static func configure() async throws {
let success = BGTaskScheduler.shared.register(forTaskWithIdentifier: taskSchedulerPermittedIdentifier, using: nil) { task in let success = BGTaskScheduler.shared.register(forTaskWithIdentifier: taskSchedulerPermittedIdentifier, using: nil) { task in
NSLog("profile update task started") NSLog("profile update task started")
Task {
await getAndupdateProfiles(task)
}
}
if !success {
throw NSError(domain: "register failed", code: 0)
}
BGTaskScheduler.shared.cancelAllTaskRequests()
let profiles = try await ProfileManager.listAutoUpdateEnabled()
if profiles.isEmpty {
return
}
try scheduleUpdate(ProfileUpdateTask.calculateEarliestBeginDate(profiles))
}
private nonisolated static func getAndupdateProfiles(_ task: BGTask) async {
let profiles: [Profile]
do { do {
let success = try ProfileUpdateTask.updateProfiles() profiles = try await ProfileManager.listAutoUpdateEnabled()
try? scheduleUpdate(Date(timeIntervalSinceNow: ProfileUpdateTask.taskInterval)) } catch {
return
}
if profiles.isEmpty {
return
}
do {
let success = try await ProfileUpdateTask.updateProfiles(profiles)
try? scheduleUpdate(ProfileUpdateTask.calculateEarliestBeginDate(profiles))
task.setTaskCompleted(success: success) task.setTaskCompleted(success: success)
NSLog("profile update task succeed") NSLog("profile update task succeed")
} catch { } catch {
@@ -24,19 +49,6 @@ import Library
NSLog("profile update task expired") NSLog("profile update task expired")
} }
} }
if !success {
throw NSError(domain: "register failed", code: 0)
}
if await BGTaskScheduler.shared.pendingTaskRequests().isEmpty {
var earliestBeginDate: Date? = nil
if let updatedAt = try ProfileUpdateTask.oldestUpdated() {
if updatedAt > Date(timeIntervalSinceNow: -ProfileUpdateTask.taskInterval) {
earliestBeginDate = updatedAt.addingTimeInterval(ProfileUpdateTask.taskInterval)
}
}
try scheduleUpdate(earliestBeginDate)
}
}
private static func scheduleUpdate(_ earliestBeginDate: Date?) throws { private static func scheduleUpdate(_ earliestBeginDate: Date?) throws {
let request = BGAppRefreshTaskRequest(identifier: taskSchedulerPermittedIdentifier) let request = BGAppRefreshTaskRequest(identifier: taskSchedulerPermittedIdentifier)
@@ -9,3 +9,21 @@ public extension Binding {
}) })
} }
} }
public extension Binding where Value == Int32 {
func stringBinding(defaultValue: Int32) -> Binding<String> {
return Binding<String> {
var intValue = wrappedValue
if intValue == 0 {
intValue = defaultValue
}
return String(intValue)
} set: { newValue in
var newIntValue = Int32(newValue) ?? defaultValue
if newIntValue == 0 {
newIntValue = defaultValue
}
wrappedValue = newIntValue
}
}
}
@@ -27,6 +27,8 @@ public func FormItem(_ title: String, @ViewBuilder content: () -> some View) ->
#if os(iOS) || os(tvOS) #if os(iOS) || os(tvOS)
HStack { HStack {
Text(title) Text(title)
.lineLimit(1)
.layoutPriority(1)
Spacer() Spacer()
Spacer() Spacer()
content() content()
@@ -7,6 +7,7 @@ import SwiftUI
import AppKit import AppKit
#endif #endif
@MainActor
public struct ProfileShareButton<Label>: View where Label: View { public struct ProfileShareButton<Label>: View where Label: View {
private let alert: Binding<Alert?> private let alert: Binding<Alert?>
private let profile: Profile private let profile: Profile
@@ -62,8 +63,8 @@ public struct ShareButtonCompat<Label>: View where Label: View {
private func shareItem() { private func shareItem() {
#if os(iOS) #if os(iOS)
Task.detached { Task {
shareItem0() await shareItem0()
} }
#elseif os(macOS) #elseif os(macOS)
sharePresented = true sharePresented = true
@@ -71,14 +72,14 @@ public struct ShareButtonCompat<Label>: View where Label: View {
} }
#if os(iOS) #if os(iOS)
private func shareItem0() { private nonisolated func shareItem0() async {
do { do {
let shareItem = try itemURL() let shareItem = try itemURL()
DispatchQueue.main.async { await MainActor.run {
shareItem1(shareItem) shareItem1(shareItem)
} }
} catch { } catch {
DispatchQueue.main.async { await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
@@ -3,6 +3,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct ActiveDashboardView: View { public struct ActiveDashboardView: View {
@Environment(\.scenePhase) var scenePhase @Environment(\.scenePhase) var scenePhase
@Environment(\.selection) private var parentSelection @Environment(\.selection) private var parentSelection
@@ -19,7 +20,7 @@ public struct ActiveDashboardView: View {
public var body: some View { public var body: some View {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
await doReload() await doReload()
} }
} }
@@ -28,9 +29,14 @@ public struct ActiveDashboardView: View {
body1 body1
} else { } else {
body1 body1
.onAppear {
Task {
await doReloadSystemProxy()
}
}
.onChangeCompat(of: profile.status) { newStatus in .onChangeCompat(of: profile.status) { newStatus in
if newStatus == .connected { if newStatus == .connected {
Task.detached { Task {
await doReloadSystemProxy() await doReloadSystemProxy()
} }
} }
@@ -70,14 +76,14 @@ public struct ActiveDashboardView: View {
#if os(iOS) || os(tvOS) #if os(iOS) || os(tvOS)
.onChangeCompat(of: scenePhase) { newValue in .onChangeCompat(of: scenePhase) { newValue in
if newValue == .active { if newValue == .active {
Task.detached { Task {
await doReload() await doReload()
} }
} }
} }
.onChangeCompat(of: parentSelection.wrappedValue) { newValue in .onChangeCompat(of: parentSelection.wrappedValue) { newValue in
if newValue == .dashboard { if newValue == .dashboard {
Task.detached { Task {
await doReload() await doReload()
} }
} }
@@ -86,7 +92,7 @@ public struct ActiveDashboardView: View {
.alertBinding($alert) .alertBinding($alert)
} }
private func doReload() { private func doReload() async {
defer { defer {
isLoading = false isLoading = false
} }
@@ -98,35 +104,39 @@ public struct ActiveDashboardView: View {
systemProxyAvailable = true systemProxyAvailable = true
systemProxyEnabled = true systemProxyEnabled = true
selectedProfileID = 0 selectedProfileID = 0
} else { } else {
do { do {
profileList = try ProfileManager.list() profileList = try await ProfileManager.list()
} catch {
alert = Alert(error)
return
}
if profileList.isEmpty { if profileList.isEmpty {
return return
} }
selectedProfileID = await SharedPreferences.selectedProfileID.get()
selectedProfileID = SharedPreferences.selectedProfileID
if profileList.filter({ profile in if profileList.filter({ profile in
profile.id == selectedProfileID profile.id == selectedProfileID
}) })
.isEmpty { .isEmpty {
selectedProfileID = profileList[0].id! selectedProfileID = profileList[0].id!
SharedPreferences.selectedProfileID = selectedProfileID await SharedPreferences.selectedProfileID.set(selectedProfileID)
}
}
} }
private func doReloadSystemProxy() {
do {
let status = try LibboxNewStandaloneCommandClient()!.getSystemProxyStatus()
systemProxyAvailable = status.available
systemProxyEnabled = status.enabled
} catch { } catch {
alert = Alert(error) alert = Alert(error)
} }
} }
} }
private nonisolated func doReloadSystemProxy() async {
do {
let status = try LibboxNewStandaloneCommandClient()!.getSystemProxyStatus()
await MainActor.run {
systemProxyAvailable = status.available
systemProxyEnabled = status.enabled
}
} catch {
await MainActor.run {
alert = Alert(error)
}
}
}
}
@@ -2,6 +2,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct ClashModeView: View { public struct ClashModeView: View {
@Environment(\.scenePhase) private var scenePhase @Environment(\.scenePhase) private var scenePhase
@StateObject private var commandClient = CommandClient(.clashMode) @StateObject private var commandClient = CommandClient(.clashMode)
@@ -16,8 +17,8 @@ public struct ClashModeView: View {
clashMode clashMode
}, set: { newMode in }, set: { newMode in
clashMode = newMode clashMode = newMode
Task.detached { Task {
await setMode(newMode) await setClashMode(newMode)
} }
}), content: { }), content: {
ForEach(commandClient.clashModeList, id: \.self) { it in ForEach(commandClient.clashModeList, id: \.self) { it in
@@ -48,11 +49,13 @@ public struct ClashModeView: View {
.alertBinding($alert) .alertBinding($alert)
} }
private func setMode(_ newMode: String) { private nonisolated func setClashMode(_ newMode: String) async {
do { do {
try LibboxNewStandaloneCommandClient()!.setClashMode(newMode) try LibboxNewStandaloneCommandClient()!.setClashMode(newMode)
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
} }
}
@@ -30,6 +30,7 @@ public extension DashboardPage {
} }
} }
@MainActor
func contentView(_ profileList: Binding<[Profile]>, _ selectedProfileID: Binding<Int64?>, _ systemProxyAvailable: Binding<Bool>, _ systemProxyEnabled: Binding<Bool>) -> some View { func contentView(_ profileList: Binding<[Profile]>, _ selectedProfileID: Binding<Int64?>, _ systemProxyAvailable: Binding<Bool>, _ systemProxyEnabled: Binding<Bool>) -> some View {
viewBuilder { viewBuilder {
switch self { switch self {
@@ -1,6 +1,7 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct DashboardView: View { public struct DashboardView: View {
#if os(macOS) #if os(macOS)
@Environment(\.controlActiveState) private var controlActiveState @Environment(\.controlActiveState) private var controlActiveState
@@ -16,12 +17,18 @@ public struct DashboardView: View {
viewBuilder { viewBuilder {
if !systemExtensionInstalled { if !systemExtensionInstalled {
FormView { FormView {
InstallSystemExtensionButton(reload) InstallSystemExtensionButton {
await reload()
}
} }
} else { } else {
DashboardView0() DashboardView0()
} }
}.onAppear(perform: reload) }.onAppear {
Task {
await reload()
}
}
} else { } else {
DashboardView0() DashboardView0()
} }
@@ -34,7 +41,9 @@ public struct DashboardView: View {
if newValue != .inactive { if newValue != .inactive {
if Variant.useSystemExtension { if Variant.useSystemExtension {
if !isLoading { if !isLoading {
reload() Task {
await reload()
}
} }
} }
} }
@@ -43,9 +52,10 @@ public struct DashboardView: View {
} }
#if os(macOS) #if os(macOS)
private func reload() { private nonisolated func reload() async {
Task { let systemExtensionInstalled = await SystemExtension.isInstalled()
systemExtensionInstalled = await SystemExtension.isInstalled() await MainActor.run {
self.systemExtensionInstalled = systemExtensionInstalled
isLoading = false isLoading = false
} }
} }
@@ -81,9 +91,16 @@ public struct DashboardView: View {
.alertBinding($alert) .alertBinding($alert)
.onChangeCompat(of: profile.status) { newValue in .onChangeCompat(of: profile.status) { newValue in
if newValue == .disconnecting || newValue == .connected { if newValue == .disconnecting || newValue == .connected {
Task.detached { Task {
await checkServiceError()
}
}
}
}
private nonisolated func checkServiceError() async {
if let serviceError = try? String(contentsOf: ExtensionProvider.errorFile) { if let serviceError = try? String(contentsOf: ExtensionProvider.errorFile) {
DispatchQueue.main.async { await MainActor.run {
alert = Alert(title: Text("Service Error"), message: Text(serviceError)) alert = Alert(title: Text("Service Error"), message: Text(serviceError))
} }
try? FileManager.default.removeItem(at: ExtensionProvider.errorFile) try? FileManager.default.removeItem(at: ExtensionProvider.errorFile)
@@ -91,6 +108,3 @@ public struct DashboardView: View {
} }
} }
} }
}
}
}
@@ -113,14 +113,6 @@ public struct ExtensionStatusView: View {
} }
} }
private func closeConnections() {
do {
try LibboxNewStandaloneCommandClient()!.closeConnections()
} catch {
alert = Alert(error)
}
}
private struct StatusItem<T>: View where T: View { private struct StatusItem<T>: View where T: View {
private let title: String private let title: String
@ViewBuilder private let content: () -> T @ViewBuilder private let content: () -> T
@@ -1,6 +1,7 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct InstallProfileButton: View { public struct InstallProfileButton: View {
@State private var alert: Alert? @State private var alert: Alert?
@@ -3,10 +3,11 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct InstallSystemExtensionButton: View { public struct InstallSystemExtensionButton: View {
@State private var alert: Alert? @State private var alert: Alert?
private let callback: () -> Void private let callback: () async -> Void
public init(_ callback: @escaping () -> Void) { public init(_ callback: @escaping () async -> Void) {
self.callback = callback self.callback = callback
} }
@@ -26,7 +27,7 @@
alert = Alert(errorMessage: "Need Reboot") alert = Alert(errorMessage: "Need Reboot")
} }
} }
callback() await callback()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
} }
@@ -3,6 +3,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct OverviewView: View { public struct OverviewView: View {
public static let NotificationUpdateSelectedProfile = Notification.Name("update-selected-profile") public static let NotificationUpdateSelectedProfile = Notification.Name("update-selected-profile")
@@ -38,7 +39,7 @@ public struct OverviewView: View {
if ApplicationLibrary.inPreview || profile.status.isConnectedStrict, systemProxyAvailable { if ApplicationLibrary.inPreview || profile.status.isConnectedStrict, systemProxyAvailable {
Toggle("HTTP Proxy", isOn: $systemProxyEnabled) Toggle("HTTP Proxy", isOn: $systemProxyEnabled)
.onChangeCompat(of: systemProxyEnabled) { newValue in .onChangeCompat(of: systemProxyEnabled) { newValue in
Task.detached { Task {
await setSystemProxyEnabled(newValue) await setSystemProxyEnabled(newValue)
} }
} }
@@ -55,7 +56,7 @@ public struct OverviewView: View {
if ApplicationLibrary.inPreview || profile.status.isConnectedStrict, systemProxyAvailable { if ApplicationLibrary.inPreview || profile.status.isConnectedStrict, systemProxyAvailable {
Toggle("HTTP Proxy", isOn: $systemProxyEnabled) Toggle("HTTP Proxy", isOn: $systemProxyEnabled)
.onChangeCompat(of: systemProxyEnabled) { newValue in .onChangeCompat(of: systemProxyEnabled) { newValue in
Task.detached { Task {
await setSystemProxyEnabled(newValue) await setSystemProxyEnabled(newValue)
} }
} }
@@ -75,7 +76,7 @@ public struct OverviewView: View {
.alertBinding($alert) .alertBinding($alert)
.onChangeCompat(of: selectedProfileID) { .onChangeCompat(of: selectedProfileID) {
reasserting = true reasserting = true
Task.detached { Task {
await switchProfile(selectedProfileID!) await switchProfile(selectedProfileID!)
} }
} }
@@ -96,25 +97,31 @@ public struct OverviewView: View {
#endif #endif
} }
private func switchProfile(_ newProfileID: Int64) { private nonisolated func switchProfile(_ newProfileID: Int64) async {
SharedPreferences.selectedProfileID = newProfileID await SharedPreferences.selectedProfileID.set(newProfileID)
NotificationCenter.default.post(name: OverviewView.NotificationUpdateSelectedProfile, object: newProfileID) NotificationCenter.default.post(name: OverviewView.NotificationUpdateSelectedProfile, object: newProfileID)
if profile.status.isConnected { if await profile.status.isConnected {
do { do {
try LibboxNewStandaloneCommandClient()!.serviceReload() try LibboxNewStandaloneCommandClient()!.serviceReload()
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
}
await MainActor.run {
reasserting = false reasserting = false
} }
}
private func setSystemProxyEnabled(_ isEnabled: Bool) { private nonisolated func setSystemProxyEnabled(_ isEnabled: Bool) async {
do { do {
try LibboxNewStandaloneCommandClient()!.setSystemProxyEnabled(isEnabled) try LibboxNewStandaloneCommandClient()!.setSystemProxyEnabled(isEnabled)
SharedPreferences.systemProxyEnabled = isEnabled await SharedPreferences.systemProxyEnabled.set(isEnabled)
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
} }
}
@@ -2,6 +2,7 @@ import Library
import NetworkExtension import NetworkExtension
import SwiftUI import SwiftUI
@MainActor
public struct StartStopButton: View { public struct StartStopButton: View {
@EnvironmentObject private var environments: ExtensionEnvironments @EnvironmentObject private var environments: ExtensionEnvironments
@@ -15,9 +16,9 @@ public struct StartStopButton: View {
Text("Enabled") Text("Enabled")
} }
#elseif os(macOS) #elseif os(macOS)
Button(action: {}, label: { Button {} label: {
Label("Stop", systemImage: "stop.fill") Label("Stop", systemImage: "stop.fill")
}) }
#endif #endif
} else if let profile = environments.extensionProfile { } else if let profile = environments.extensionProfile {
@@ -28,10 +29,9 @@ public struct StartStopButton: View {
Text("Enabled") Text("Enabled")
} }
#elseif os(macOS) #elseif os(macOS)
Button {} label: {
Button(action: {}, label: {
Label("Start", systemImage: "play.fill") Label("Start", systemImage: "play.fill")
}) }
.disabled(true) .disabled(true)
#endif #endif
} }
@@ -49,41 +49,42 @@ public struct StartStopButton: View {
Toggle(isOn: Binding(get: { Toggle(isOn: Binding(get: {
profile.status.isConnected profile.status.isConnected
}, set: { newValue, _ in }, set: { newValue, _ in
Task.detached { Task {
await switchProfile(newValue) await switchProfile(newValue)
} }
})) { })) {
Text("Enabled") Text("Enabled")
} }
#elseif os(macOS) #elseif os(macOS)
Button(action: { Button {
Task.detached { Task {
await switchProfile(!profile.status.isConnected) await switchProfile(!profile.status.isConnected)
} }
}, label: { } label: {
if !profile.status.isConnected { if !profile.status.isConnected {
Label("Start", systemImage: "play.fill") Label("Start", systemImage: "play.fill")
} else { } else {
Label("Stop", systemImage: "stop.fill") Label("Stop", systemImage: "stop.fill")
} }
}) }
#endif #endif
} }
.disabled(!profile.status.isEnabled) .disabled(!profile.status.isEnabled)
.alertBinding($alert) .alertBinding($alert)
} }
private func switchProfile(_ isEnabled: Bool) async { private nonisolated func switchProfile(_ isEnabled: Bool) async {
do { do {
if isEnabled { if isEnabled {
try await profile.start() try await profile.start()
environments.logClient.connect() await environments.logClient.connect()
} else { } else {
profile.stop() await profile.stop()
} }
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
return }
} }
} }
} }
@@ -2,6 +2,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct GroupItemView: View { public struct GroupItemView: View {
private let _group: Binding<OutboundGroup> private let _group: Binding<OutboundGroup>
private var group: OutboundGroup { private var group: OutboundGroup {
@@ -17,13 +18,13 @@ public struct GroupItemView: View {
@State private var alert: Alert? @State private var alert: Alert?
public var body: some View { public var body: some View {
Button(action: { Button {
if group.selectable, group.selected != item.tag { if group.selectable, group.selected != item.tag {
Task.detached { Task {
selectOutbound() await selectOutbound()
} }
} }
}, label: { } label: {
HStack { HStack {
VStack { VStack {
HStack { HStack {
@@ -56,7 +57,7 @@ public struct GroupItemView: View {
} }
} }
} }
}) }
#if !os(tvOS) #if !os(tvOS)
.buttonStyle(.borderless) .buttonStyle(.borderless)
.padding(EdgeInsets(top: 10, leading: 13, bottom: 10, trailing: 13)) .padding(EdgeInsets(top: 10, leading: 13, bottom: 10, trailing: 13))
@@ -66,15 +67,18 @@ public struct GroupItemView: View {
.alertBinding($alert) .alertBinding($alert)
} }
private func selectOutbound() { private nonisolated func selectOutbound() async {
do { do {
try LibboxNewStandaloneCommandClient()!.selectOutbound(group.tag, outboundTag: item.tag) try await LibboxNewStandaloneCommandClient()!.selectOutbound(group.tag, outboundTag: item.tag)
var newGroup = group var newGroup = await group
newGroup.selected = item.tag newGroup.selected = item.tag
await MainActor.run { [newGroup] in
_group.wrappedValue = newGroup _group.wrappedValue = newGroup
}
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
return }
} }
} }
@@ -2,6 +2,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct GroupView: View { public struct GroupView: View {
@State private var group: OutboundGroup @State private var group: OutboundGroup
@State private var geometryWidth: CGFloat = 300 @State private var geometryWidth: CGFloat = 300
@@ -25,8 +26,8 @@ public struct GroupView: View {
.cornerRadius(4) .cornerRadius(4)
Button { Button {
group.isExpand = !group.isExpand group.isExpand = !group.isExpand
Task.detached { Task {
setGroupExpand() await setGroupExpand()
} }
} label: { } label: {
if group.isExpand { if group.isExpand {
@@ -39,8 +40,8 @@ public struct GroupView: View {
.buttonStyle(.plain) .buttonStyle(.plain)
#endif #endif
Button { Button {
Task.detached { Task {
doURLTest() await doURLTest()
} }
} label: { } label: {
Image(systemName: "bolt.fill") Image(systemName: "bolt.fill")
@@ -137,22 +138,26 @@ public struct GroupView: View {
#endif #endif
} }
private func doURLTest() { private nonisolated func doURLTest() async {
do { do {
try LibboxNewStandaloneCommandClient()!.urlTest(group.tag) try await LibboxNewStandaloneCommandClient()!.urlTest(group.tag)
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
}
private func setGroupExpand() { private nonisolated func setGroupExpand() async {
do { do {
try LibboxNewStandaloneCommandClient()!.setGroupExpand(group.tag, isExpand: group.isExpand) try await LibboxNewStandaloneCommandClient()!.setGroupExpand(group.tag, isExpand: group.isExpand)
} catch { } catch {
await MainActor.run {
alert = Alert(error) alert = Alert(error)
} }
} }
} }
}
private extension Array { private extension Array {
func chunked(into size: Int) -> [[Element]] { func chunked(into size: Int) -> [[Element]] {
@@ -59,6 +59,7 @@ public extension NavigationPage {
} }
} }
@MainActor
var contentView: some View { var contentView: some View {
viewBuilder { viewBuilder {
switch self { switch self {
@@ -3,6 +3,7 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct EditProfileContentView: View { public struct EditProfileContentView: View {
#if os(macOS) #if os(macOS)
public static let windowID = "edit-profile-content" public static let windowID = "edit-profile-content"
@@ -33,8 +34,8 @@
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
loadContent() await loadContent()
} }
} }
} else { } else {
@@ -64,13 +65,13 @@
.toolbar { .toolbar {
ToolbarItemGroup(placement: .navigation) { ToolbarItemGroup(placement: .navigation) {
if !readOnly { if !readOnly {
Button(action: { Button {
Task.detached { Task {
saveContent() await saveContent()
} }
}, label: { } label: {
Image("save", label: Text("Save")) Image("save", label: Text("Save"))
}) }
.disabled(!isChanged) .disabled(!isChanged)
} }
} }
@@ -80,8 +81,8 @@
ToolbarItem(placement: .navigationBarTrailing) { ToolbarItem(placement: .navigationBarTrailing) {
if !readOnly { if !readOnly {
Button("Save") { Button("Save") {
Task.detached { Task {
saveContent() await saveContent()
} }
}.disabled(!isChanged) }.disabled(!isChanged)
} }
@@ -99,38 +100,45 @@
} }
} }
private func loadContent() { private func loadContent() async {
do { do {
try loadContent0() try await loadContentBackground()
} catch { } catch {
alert = Alert(error, dismiss.callAsFunction) alert = Alert(error)
} }
}
private func loadContent0() throws {
guard let profileID else {
throw NSError(domain: "Context destroyed", code: 0)
}
guard let profile = try ProfileManager.get(profileID) else {
throw NSError(domain: "Profile missing", code: 0)
}
profileContent = try profile.read()
self.profile = profile
isLoading = false isLoading = false
} }
private func saveContent() { private nonisolated func loadContentBackground() async throws {
guard let profileID else {
throw NSError(domain: "Context destroyed", code: 0)
}
guard let profile = try await ProfileManager.get(profileID) else {
throw NSError(domain: "Profile missing", code: 0)
}
let profileContent = try profile.read()
await MainActor.run {
self.profile = profile
self.profileContent = profileContent
}
}
private func saveContent() async {
guard let profile else { guard let profile else {
return return
} }
do { do {
try profile.write(profileContent) try await saveContentBackground(profile)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
} }
isChanged = false isChanged = false
} }
private nonisolated func saveContentBackground(_ profile: Profile) async throws {
try await profile.write(profileContent)
}
} }
#endif #endif
@@ -1,6 +1,7 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct EditProfileView: View { public struct EditProfileView: View {
#if os(macOS) #if os(macOS)
@Environment(\.openWindow) private var openWindow @Environment(\.openWindow) private var openWindow
@@ -43,6 +44,13 @@ public struct EditProfileView: View {
.multilineTextAlignment(.trailing) .multilineTextAlignment(.trailing)
} }
Toggle("Auto Update", isOn: $profile.autoUpdate) Toggle("Auto Update", isOn: $profile.autoUpdate)
FormItem("Auto Update Interval") {
TextField("Auto Update Interval", text: $profile.autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
.multilineTextAlignment(.trailing)
#if os(iOS)
.keyboardType(.numberPad)
#endif
}
} }
if profile.type == .remote { if profile.type == .remote {
Section("Status") { Section("Status") {
@@ -77,14 +85,14 @@ public struct EditProfileView: View {
} }
Button("Update") { Button("Update") {
isLoading = true isLoading = true
Task.detached { Task {
await updateProfile() await updateProfile()
} }
} }
.disabled(isLoading) .disabled(isLoading)
} }
Button("Delete", role: .destructive) { Button("Delete", role: .destructive) {
Task.detached { Task {
await deleteProfile() await deleteProfile()
} }
} }
@@ -104,37 +112,37 @@ public struct EditProfileView: View {
#if os(macOS) #if os(macOS)
.toolbar { .toolbar {
ToolbarItemGroup(placement: .navigation) { ToolbarItemGroup(placement: .navigation) {
Button(action: { Button {
isLoading = true isLoading = true
Task.detached { Task {
await saveProfile() await saveProfile()
} }
}, label: { } label: {
Image("save", bundle: ApplicationLibrary.bundle, label: Text("Save")) Image("save", bundle: ApplicationLibrary.bundle, label: Text("Save"))
}) }
.disabled(isLoading || !isChanged) .disabled(isLoading || !isChanged)
if profile.type != .remote { if profile.type != .remote {
Button(action: { Button {
openWindow(id: EditProfileContentView.windowID, value: EditProfileContentView.Context(profileID: profile.id!, readOnly: false)) openWindow(id: EditProfileContentView.windowID, value: EditProfileContentView.Context(profileID: profile.id!, readOnly: false))
}, label: { } label: {
Label("Edit Content", systemImage: "pencil") Label("Edit Content", systemImage: "pencil")
}) }
.disabled(isLoading) .disabled(isLoading)
} else { } else {
Button(action: { Button {
isLoading = true isLoading = true
Task.detached { Task {
await updateProfile() await updateProfile()
} }
}, label: { } label: {
Label("Update", systemImage: "arrow.clockwise") Label("Update", systemImage: "arrow.clockwise")
}) }
.disabled(isLoading) .disabled(isLoading)
Button(action: { Button {
openWindow(id: EditProfileContentView.windowID, value: EditProfileContentView.Context(profileID: profile.id!, readOnly: true)) openWindow(id: EditProfileContentView.windowID, value: EditProfileContentView.Context(profileID: profile.id!, readOnly: true))
}, label: { } label: {
Label("View Content", systemImage: "doc.text.fill") Label("View Content", systemImage: "doc.text.fill")
}) }
.disabled(isLoading) .disabled(isLoading)
} }
} }
@@ -144,7 +152,7 @@ public struct EditProfileView: View {
ToolbarItem(placement: .navigationBarTrailing) { ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") { Button("Save") {
isLoading = true isLoading = true
Task.detached { Task {
await saveProfile() await saveProfile()
} }
}.disabled(!isChanged) }.disabled(!isChanged)
@@ -161,7 +169,12 @@ public struct EditProfileView: View {
} }
do { do {
try await Task.sleep(nanoseconds: UInt64(100 * Double(NSEC_PER_MSEC))) try await Task.sleep(nanoseconds: UInt64(100 * Double(NSEC_PER_MSEC)))
try profile.updateRemoteProfile() try await profile.updateRemoteProfile()
#if os(iOS) || os(tvOS)
try await UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
} catch { } catch {
alert = Alert(error) alert = Alert(error)
} }
@@ -169,7 +182,7 @@ public struct EditProfileView: View {
private func deleteProfile() async { private func deleteProfile() async {
do { do {
try ProfileManager.delete(profile) try await ProfileManager.delete(profile)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
@@ -180,7 +193,7 @@ public struct EditProfileView: View {
private func saveProfile() async { private func saveProfile() async {
do { do {
_ = try ProfileManager.update(profile) _ = try await ProfileManager.update(profile)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
@@ -194,9 +207,7 @@ public struct EditProfileView: View {
if let updateCallback { if let updateCallback {
updateCallback() updateCallback()
} else { } else {
await MainActor.run {
NotificationCenter.default.post(name: ProfileView.notificationName, object: nil) NotificationCenter.default.post(name: ProfileView.notificationName, object: nil)
} }
} }
} }
}
@@ -2,6 +2,7 @@ import Library
import SwiftUI import SwiftUI
#if os(macOS) #if os(macOS)
@MainActor
public struct EditProfileWindowView: View { public struct EditProfileWindowView: View {
public static let windowID = "edit-profile" public static let windowID = "edit-profile"
@@ -21,7 +22,7 @@ import SwiftUI
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
await doReload() await doReload()
} }
} }
@@ -41,7 +42,7 @@ import SwiftUI
return return
} }
do { do {
profile = try ProfileManager.get(profileID) profile = try await ProfileManager.get(profileID)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
@@ -53,4 +54,5 @@ import SwiftUI
isLoading = false isLoading = false
} }
} }
#endif #endif
@@ -5,6 +5,7 @@
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct ImportProfileView: View { public struct ImportProfileView: View {
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@@ -13,9 +14,9 @@
@State private var alert: Alert? @State private var alert: Alert?
@State private var connection: NWSocket? @State private var connection: NWSocket?
@State private var profiles: [LibboxProfilePreview]? @State private var profiles: [LibboxProfilePreview]?
private let callback: () -> Void private let callback: () async -> Void
public init(callback: @escaping () -> Void) { public init(callback: @escaping () async -> Void) {
self.callback = callback self.callback = callback
} }
@@ -26,7 +27,7 @@
.applicationService(name: "sing-box:profile")) .applicationService(name: "sing-box:profile"))
{ endpoint in { endpoint in
selected = true selected = true
Task.detached { Task {
await handleEndpoint(endpoint) await handleEndpoint(endpoint)
} }
} label: { } label: {
@@ -42,7 +43,7 @@
ForEach(profiles, id: \.profileID) { profile in ForEach(profiles, id: \.profileID) { profile in
Button(profile.name) { Button(profile.name) {
isLoading = true isLoading = true
Task.detached { Task {
selectProfile(profileID: profile.profileID) selectProfile(profileID: profile.profileID)
isLoading = false isLoading = false
} }
@@ -68,14 +69,14 @@
self.connection = NWSocket(connection) self.connection = NWSocket(connection)
connection.start(queue: .global()) connection.start(queue: .global())
do { do {
try loopMessages() try await loopMessages()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
reset() reset()
} }
} }
private func loopMessages() throws { private func loopMessages() async throws {
guard let connection else { guard let connection else {
return return
} }
@@ -110,7 +111,7 @@
if let error { if let error {
throw error throw error
} }
try importProfile(content!) try await importProfile(content!)
default: default:
throw NSError(domain: "unknown message type \(message[0])", code: 0) throw NSError(domain: "unknown message type \(message[0])", code: 0)
} }
@@ -131,7 +132,7 @@
} }
} }
private func importProfile(_ content: LibboxProfileContent) throws { private nonisolated func importProfile(_ content: LibboxProfileContent) async throws {
var type: ProfileType = .local var type: ProfileType = .local
switch content.type { switch content.type {
case LibboxProfileTypeLocal: case LibboxProfileTypeLocal:
@@ -143,8 +144,7 @@
default: default:
break break
} }
let nextProfileID = try await ProfileManager.nextID()
let nextProfileID = try ProfileManager.nextID()
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true) let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json") let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
@@ -153,10 +153,10 @@
if content.lastUpdated > 0 { if content.lastUpdated > 0 {
lastUpdated = Date(timeIntervalSince1970: Double(content.lastUpdated)) lastUpdated = Date(timeIntervalSince1970: Double(content.lastUpdated))
} }
try ProfileManager.create(Profile(name: content.name, type: type, path: profileConfig.relativePath, remoteURL: content.remotePath, autoUpdate: content.autoUpdate, lastUpdated: lastUpdated)) try await ProfileManager.create(Profile(name: content.name, type: type, path: profileConfig.relativePath, remoteURL: content.remotePath, autoUpdate: content.autoUpdate, lastUpdated: lastUpdated))
DispatchQueue.main.async { await callback()
await MainActor.run {
dismiss() dismiss()
callback()
} }
} }
} }
@@ -3,6 +3,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct NewProfileView: View { public struct NewProfileView: View {
#if os(macOS) #if os(macOS)
public static let windowID = "new-profile" public static let windowID = "new-profile"
@@ -16,6 +17,8 @@ public struct NewProfileView: View {
@State private var fileImport = false @State private var fileImport = false
@State private var fileURL: URL! @State private var fileURL: URL!
@State private var remotePath = "" @State private var remotePath = ""
@State private var autoUpdate = true
@State private var autoUpdateInterval: Int32 = 60
@State private var pickerPresented = false @State private var pickerPresented = false
@State private var alert: Alert? @State private var alert: Alert?
@@ -24,8 +27,8 @@ public struct NewProfileView: View {
public let url: String public let url: String
} }
private let callback: (() -> Void)? private let callback: (() async -> Void)?
public init(_ importRequest: ImportRequest? = nil, _ callback: (() -> Void)? = nil) { public init(_ importRequest: ImportRequest? = nil, _ callback: (() async -> Void)? = nil) {
self.callback = callback self.callback = callback
if let importRequest { if let importRequest {
_profileName = .init(initialValue: importRequest.name) _profileName = .init(initialValue: importRequest.name)
@@ -87,12 +90,20 @@ public struct NewProfileView: View {
TextField("URL", text: $remotePath, prompt: Text("Required")) TextField("URL", text: $remotePath, prompt: Text("Required"))
.multilineTextAlignment(.trailing) .multilineTextAlignment(.trailing)
} }
Toggle("Auto Update", isOn: $autoUpdate)
FormItem("Auto Update Interval") {
TextField("Auto Update Interval", text: $autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
.multilineTextAlignment(.trailing)
#if os(iOS)
.keyboardType(.numberPad)
#endif
}
} }
Section { Section {
if !isSaving { if !isSaving {
Button("Create") { Button("Create") {
isSaving = true isSaving = true
Task.detached { Task {
await createProfile() await createProfile()
} }
} }
@@ -140,22 +151,20 @@ public struct NewProfileView: View {
} }
} }
do { do {
try createProfile0() try await createProfileBackground()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
} }
await MainActor.run {
dismiss()
if let callback { if let callback {
callback() await callback()
} }
dismiss()
#if os(macOS) #if os(macOS)
NotificationCenter.default.post(name: ProfileView.notificationName, object: nil) NotificationCenter.default.post(name: ProfileView.notificationName, object: nil)
resetFields() resetFields()
#endif #endif
} }
}
private func resetFields() { private func resetFields() {
profileName = "" profileName = ""
@@ -165,25 +174,31 @@ public struct NewProfileView: View {
remotePath = "" remotePath = ""
} }
private func createProfile0() throws { private nonisolated func createProfileBackground() async throws {
let nextProfileID = try ProfileManager.nextID() let nextProfileID = try await ProfileManager.nextID()
var savePath = "" var savePath = ""
var remoteURL: String? = nil var remoteURL: String? = nil
var lastUpdated: Date? = nil var lastUpdated: Date? = nil
let profileName = await profileName
let profileType = await profileType
let fileImport = await fileImport
let fileURL = await fileURL
let remotePath = await remotePath
let autoUpdate = await autoUpdate
let autoUpdateInterval = await autoUpdateInterval
if profileType == .local { if profileType == .local {
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true) let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json") let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
if fileImport { if fileImport {
guard let fileURL else { guard let fileURL else {
alert = Alert(errorMessage: "Missing file") throw NSError(domain: "Missing file", code: 0)
return
} }
if !fileURL.startAccessingSecurityScopedResource() { if !fileURL.startAccessingSecurityScopedResource() {
alert = Alert(errorMessage: "Missing access to selected file") throw NSError(domain: "Missing access to selected file", code: 0)
return
} }
defer { defer {
fileURL.stopAccessingSecurityScopedResource() fileURL.stopAccessingSecurityScopedResource()
@@ -223,6 +238,14 @@ public struct NewProfileView: View {
remoteURL = remotePath remoteURL = remotePath
lastUpdated = .now lastUpdated = .now
} }
try ProfileManager.create(Profile(name: profileName, type: profileType, path: savePath, remoteURL: remoteURL, lastUpdated: lastUpdated)) try await ProfileManager.create(Profile(
name: profileName,
type: profileType,
path: savePath,
remoteURL: remoteURL,
autoUpdate: autoUpdate,
autoUpdateInterval: autoUpdateInterval,
lastUpdated: lastUpdated
))
} }
} }
@@ -4,6 +4,7 @@ import Library
import Network import Network
import SwiftUI import SwiftUI
@MainActor
public struct ProfileView: View { public struct ProfileView: View {
public static let notificationName = Notification.Name("\(FilePath.packageName).update-profile") public static let notificationName = Notification.Name("\(FilePath.packageName).update-profile")
@@ -36,8 +37,8 @@ public struct ProfileView: View {
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
doReload() await doReload()
} }
} }
} else { } else {
@@ -46,9 +47,7 @@ public struct ProfileView: View {
if let importRemoteProfileRequest { if let importRemoteProfileRequest {
NavigationDestinationCompat(isPresented: $importRemoteProfilePresented) { NavigationDestinationCompat(isPresented: $importRemoteProfilePresented) {
NewProfileView(importRemoteProfileRequest) { NewProfileView(importRemoteProfileRequest) {
Task.detached { await doReload()
doReload()
}
} }
} }
} }
@@ -56,9 +55,7 @@ public struct ProfileView: View {
#if os(iOS) #if os(iOS)
NavigationLink { NavigationLink {
NewProfileView { NewProfileView {
Task.detached { await doReload()
doReload()
}
} }
} label: { } label: {
Text("New Profile").foregroundColor(.accentColor) Text("New Profile").foregroundColor(.accentColor)
@@ -68,9 +65,7 @@ public struct ProfileView: View {
Section { Section {
NavigationLink { NavigationLink {
NewProfileView { NewProfileView {
Task.detached { await doReload()
doReload()
}
} }
} label: { } label: {
Text("New Profile").foregroundColor(.accentColor) Text("New Profile").foregroundColor(.accentColor)
@@ -78,9 +73,7 @@ public struct ProfileView: View {
if ApplicationLibrary.inPreview || devicePickerSupports(.applicationService(name: "sing-box"), parameters: { .applicationService }) { if ApplicationLibrary.inPreview || devicePickerSupports(.applicationService(name: "sing-box"), parameters: { .applicationService }) {
NavigationLink { NavigationLink {
ImportProfileView { ImportProfileView {
Task.detached { await doReload()
doReload()
}
} }
} label: { } label: {
Text("Import Profile").foregroundColor(.accentColor) Text("Import Profile").foregroundColor(.accentColor)
@@ -138,8 +131,8 @@ public struct ProfileView: View {
#if os(macOS) #if os(macOS)
if observer == nil { if observer == nil {
observer = NotificationCenter.default.addObserver(forName: ProfileView.notificationName, object: nil, queue: .main) { _ in observer = NotificationCenter.default.addObserver(forName: ProfileView.notificationName, object: nil, queue: .main) { _ in
Task.detached { Task {
doReload() await doReload()
} }
} }
} }
@@ -166,11 +159,11 @@ public struct ProfileView: View {
} }
.toolbar { .toolbar {
ToolbarItem { ToolbarItem {
Button(action: { Button {
openWindow(id: NewProfileView.windowID) openWindow(id: NewProfileView.windowID)
}, label: { } label: {
Label("New Profile", systemImage: "plus.square.fill") Label("New Profile", systemImage: "plus.square.fill")
}) }
} }
} }
#elseif os(iOS) #elseif os(iOS)
@@ -188,14 +181,14 @@ public struct ProfileView: View {
title: Text("Import Profile"), title: Text("Import Profile"),
message: Text("Are you sure to import profile \(profile.name)?"), message: Text("Are you sure to import profile \(profile.name)?"),
primaryButton: .default(Text("Import")) { primaryButton: .default(Text("Import")) {
Task {
do { do {
try profile.importProfile() try await profile.importProfile()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
} }
Task.detached { await doReload()
doReload()
} }
}, },
secondaryButton: .cancel() secondaryButton: .cancel()
@@ -218,28 +211,18 @@ public struct ProfileView: View {
) )
} }
private func deleteSelectedProfiles(_ profileID: [Int64]) { private func doReload() async {
do {
if try ProfileManager.delete(by: profileID) > 0 {
isLoading = true
}
} catch {
alert = Alert(error)
}
}
private func doReload() {
defer {
isLoading = false
}
if ApplicationLibrary.inPreview { if ApplicationLibrary.inPreview {
profileList = [ profileList = [
Profile(id: 0, name: "profile local", type: .local, path: ""), Profile(id: 0, name: "profile local", type: .local, path: ""),
Profile(id: 1, name: "profile remote", type: .remote, path: "", lastUpdated: Date(timeIntervalSince1970: 0)), Profile(id: 1, name: "profile remote", type: .remote, path: "", lastUpdated: Date(timeIntervalSince1970: 0)),
] ]
} else { } else {
defer {
isLoading = false
}
do { do {
profileList = try ProfileManager.list() profileList = try await ProfileManager.list()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
@@ -247,25 +230,29 @@ public struct ProfileView: View {
} }
} }
private func updateProfile(_ profile: Profile) { private func updateProfile(_ profile: Profile) async {
do { await updateProfileBackground(profile)
_ = try profile.updateRemoteProfile()
} catch {
alert = Alert(error)
}
isUpdating = false isUpdating = false
} }
private func deleteProfile(_ profile: Profile) { private nonisolated func updateProfileBackground(_ profile: Profile) async {
Task.detached {
do { do {
_ = try ProfileManager.delete(profile) _ = try await profile.updateRemoteProfile()
} catch {
await MainActor.run {
alert = Alert(error)
}
}
}
private func deleteProfile(_ profile: Profile) async {
do {
_ = try await ProfileManager.delete(profile)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
} }
doReload() await doReload()
}
} }
private func moveProfile(from source: IndexSet, to destination: Int) { private func moveProfile(from source: IndexSet, to destination: Int) {
@@ -273,11 +260,12 @@ public struct ProfileView: View {
for (index, profile) in profileList.enumerated() { for (index, profile) in profileList.enumerated() {
profile.order = UInt32(index) profile.order = UInt32(index)
} }
Task {
do { do {
try ProfileManager.update(profileList) try await ProfileManager.update(profileList)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return }
} }
} }
@@ -286,9 +274,9 @@ public struct ProfileView: View {
profileList[index] profileList[index]
} }
profileList.remove(atOffsets: profileIndex) profileList.remove(atOffsets: profileIndex)
Task.detached { Task {
do { do {
_ = try ProfileManager.delete(profileToDelete) _ = try await ProfileManager.delete(profileToDelete)
} catch { } catch {
alert = Alert(error) alert = Alert(error)
} }
@@ -315,13 +303,14 @@ public struct ProfileView: View {
#endif #endif
} }
@MainActor
private var body0: some View { private var body0: some View {
viewBuilder { viewBuilder {
#if !os(macOS) #if !os(macOS)
NavigationLink { NavigationLink {
EditProfileView { EditProfileView {
Task.detached { Task {
parent.doReload() await parent.doReload()
} }
}.environmentObject(profile) }.environmentObject(profile)
} label: { } label: {
@@ -334,15 +323,17 @@ public struct ProfileView: View {
if profile.type == .remote { if profile.type == .remote {
Button { Button {
parent.isUpdating = true parent.isUpdating = true
Task.detached { Task {
parent.updateProfile(profile) await parent.updateProfile(profile)
} }
} label: { } label: {
Label("Update", systemImage: "arrow.clockwise") Label("Update", systemImage: "arrow.clockwise")
} }
} }
Button(role: .destructive) { Button(role: .destructive) {
parent.deleteProfile(profile) Task {
await parent.deleteProfile(profile)
}
} label: { } label: {
Label("Delete", systemImage: "trash.fill") Label("Delete", systemImage: "trash.fill")
} }
@@ -358,28 +349,30 @@ public struct ProfileView: View {
} }
HStack { HStack {
if profile.type == .remote { if profile.type == .remote {
Button(action: { Button {
parent.isUpdating = true parent.isUpdating = true
Task.detached { Task {
parent.updateProfile(profile) await parent.updateProfile(profile)
} }
}, label: { } label: {
Image(systemName: "arrow.clockwise") Image(systemName: "arrow.clockwise")
}) }
} }
ProfileShareButton(parent.$alert, profile) { ProfileShareButton(parent.$alert, profile) {
Image(systemName: "square.and.arrow.up.fill") Image(systemName: "square.and.arrow.up.fill")
} }
Button(action: { Button {
parent.openWindow(id: EditProfileWindowView.windowID, value: profile.mustID) parent.openWindow(id: EditProfileWindowView.windowID, value: profile.mustID)
}, label: { } label: {
Image(systemName: "pencil") Image(systemName: "pencil")
}) }
Button(action: { Button {
parent.deleteProfile(profile) Task {
}, label: { await parent.deleteProfile(profile)
}
} label: {
Image(systemName: "trash.fill") Image(systemName: "trash.fill")
}) }
} }
.frame(maxWidth: .infinity, alignment: .trailing) .frame(maxWidth: .infinity, alignment: .trailing)
} }
@@ -3,6 +3,7 @@ import Library
import SwiftUI import SwiftUI
import UniformTypeIdentifiers import UniformTypeIdentifiers
@MainActor
public struct ServiceLogView: View { public struct ServiceLogView: View {
#if os(macOS) #if os(macOS)
public static let windowID = "service-log" public static let windowID = "service-log"
@@ -20,8 +21,8 @@ public struct ServiceLogView: View {
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
loadContent() await loadContent()
} }
} }
} else { } else {
@@ -44,8 +45,8 @@ public struct ServiceLogView: View {
fileExporterPresented = true fileExporterPresented = true
} }
Button("Delete", role: .destructive) { Button("Delete", role: .destructive) {
Task.detached { Task {
deleteContent() await deleteContent()
} }
} }
} }
@@ -66,7 +67,8 @@ public struct ServiceLogView: View {
#endif #endif
} }
private func loadContent() { private nonisolated func loadContent() async {
var content = ""
do { do {
content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log")) content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log"))
} catch {} } catch {}
@@ -75,13 +77,16 @@ public struct ServiceLogView: View {
content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old")) content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old"))
} catch {} } catch {}
} }
await MainActor.run { [content] in
self.content = content
isLoading = false isLoading = false
} }
}
private func deleteContent() { private nonisolated func deleteContent() async {
try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log")) try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log"))
try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old")) try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old"))
DispatchQueue.main.async { await MainActor.run {
dismiss() dismiss()
isLoading = true isLoading = true
} }
@@ -7,6 +7,7 @@ import SwiftUI
import ServiceManagement import ServiceManagement
#endif #endif
@MainActor
public struct SettingView: View { public struct SettingView: View {
#if os(macOS) #if os(macOS)
@Environment(\.openWindow) private var openWindow @Environment(\.openWindow) private var openWindow
@@ -38,7 +39,7 @@ public struct SettingView: View {
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
await loadSettings() await loadSettings()
} }
} }
@@ -48,14 +49,14 @@ public struct SettingView: View {
Section("MacOS") { Section("MacOS") {
Toggle("Start At Login", isOn: $startAtLogin) Toggle("Start At Login", isOn: $startAtLogin)
.onChangeCompat(of: startAtLogin) { newValue in .onChangeCompat(of: startAtLogin) { newValue in
Task.detached { Task {
updateLoginItems(newValue) updateLoginItems(newValue)
} }
} }
Toggle("Show in Menu Bar", isOn: showMenuBarExtra) Toggle("Show in Menu Bar", isOn: showMenuBarExtra)
.onChange(of: showMenuBarExtra.wrappedValue) { newValue in .onChange(of: showMenuBarExtra.wrappedValue) { newValue in
Task.detached { Task {
SharedPreferences.showMenuBarExtra = newValue await SharedPreferences.showMenuBarExtra.set(newValue)
if !newValue { if !newValue {
keepMenuBarInBackground = false keepMenuBarInBackground = false
} }
@@ -64,8 +65,8 @@ public struct SettingView: View {
if showMenuBarExtra.wrappedValue { if showMenuBarExtra.wrappedValue {
Toggle("Keep Menu Bar in Background", isOn: $keepMenuBarInBackground) Toggle("Keep Menu Bar in Background", isOn: $keepMenuBarInBackground)
.onChangeCompat(of: keepMenuBarInBackground) { newValue in .onChangeCompat(of: keepMenuBarInBackground) { newValue in
Task.detached { Task {
SharedPreferences.menuBarExtraInBackground = newValue await SharedPreferences.menuBarExtraInBackground.set(newValue)
} }
} }
} }
@@ -74,22 +75,22 @@ public struct SettingView: View {
Section("Packet Tunnel") { Section("Packet Tunnel") {
Toggle("Always On", isOn: $alwaysOn) Toggle("Always On", isOn: $alwaysOn)
.onChangeCompat(of: alwaysOn) { newValue in .onChangeCompat(of: alwaysOn) { newValue in
Task.detached { Task {
SharedPreferences.alwaysOn = newValue await SharedPreferences.alwaysOn.set(newValue)
await updateAlwaysOn(newValue) await updateAlwaysOn(newValue)
} }
} }
Toggle("Disable Memory Limit", isOn: $disableMemoryLimit) Toggle("Disable Memory Limit", isOn: $disableMemoryLimit)
.onChangeCompat(of: disableMemoryLimit) { newValue in .onChangeCompat(of: disableMemoryLimit) { newValue in
Task.detached { Task {
SharedPreferences.disableMemoryLimit = newValue await SharedPreferences.disableMemoryLimit.set(newValue)
} }
} }
#if !os(tvOS) #if !os(tvOS)
Toggle("Include All Networks", isOn: $includeAllNetworks) Toggle("Include All Networks", isOn: $includeAllNetworks)
.onChangeCompat(of: includeAllNetworks) { newValue in .onChangeCompat(of: includeAllNetworks) { newValue in
Task.detached { Task {
SharedPreferences.includeAllNetworks = newValue await SharedPreferences.includeAllNetworks.set(newValue)
} }
} }
#endif #endif
@@ -121,8 +122,8 @@ public struct SettingView: View {
Text("View Service Log") Text("View Service Log")
} }
Button("Clear Working Directory") { Button("Clear Working Directory") {
Task.detached { Task {
clearWorkingDirectory() await clearWorkingDirectory()
} }
} }
.foregroundColor(.red) .foregroundColor(.red)
@@ -135,8 +136,8 @@ public struct SettingView: View {
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: FilePath.workingDirectory.relativePath) NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: FilePath.workingDirectory.relativePath)
} }
Button { Button {
Task.detached { Task {
clearWorkingDirectory() await clearWorkingDirectory()
} }
} label: { } label: {
Text("Clear Working Directory").foregroundColor(.red) Text("Clear Working Directory").foregroundColor(.red)
@@ -174,12 +175,12 @@ public struct SettingView: View {
private func loadSettings() async { private func loadSettings() async {
#if os(macOS) #if os(macOS)
startAtLogin = SMAppService.mainApp.status == .enabled startAtLogin = SMAppService.mainApp.status == .enabled
keepMenuBarInBackground = SharedPreferences.menuBarExtraInBackground keepMenuBarInBackground = await SharedPreferences.menuBarExtraInBackground.get()
#endif #endif
alwaysOn = SharedPreferences.alwaysOn alwaysOn = await SharedPreferences.alwaysOn.get()
disableMemoryLimit = SharedPreferences.disableMemoryLimit disableMemoryLimit = await SharedPreferences.disableMemoryLimit.get()
#if !os(tvOS) #if !os(tvOS)
includeAllNetworks = SharedPreferences.includeAllNetworks includeAllNetworks = await SharedPreferences.includeAllNetworks.get()
#endif #endif
if ApplicationLibrary.inPreview { if ApplicationLibrary.inPreview {
version = "<redacted>" version = "<redacted>"
@@ -191,14 +192,23 @@ public struct SettingView: View {
dataSize = "Loading..." dataSize = "Loading..."
taiwanFlagAvailable = !DeviceCensorship.isChinaDevice() taiwanFlagAvailable = !DeviceCensorship.isChinaDevice()
isLoading = false isLoading = false
dataSize = (try? FilePath.workingDirectory.formattedSize()) ?? "Unknown" await loadSettingsBackground()
} }
} }
private func clearWorkingDirectory() { private nonisolated func loadSettingsBackground() async {
let dataSize = (try? FilePath.workingDirectory.formattedSize()) ?? "Unknown"
await MainActor.run {
self.dataSize = dataSize
}
}
private nonisolated func clearWorkingDirectory() async {
try? FileManager.default.removeItem(at: FilePath.workingDirectory) try? FileManager.default.removeItem(at: FilePath.workingDirectory)
await MainActor.run {
isLoading = true isLoading = true
} }
}
private func updateAlwaysOn(_ newState: Bool) async { private func updateAlwaysOn(_ newState: Bool) async {
guard let profile = try? await ExtensionProfile.load() else { guard let profile = try? await ExtensionProfile.load() else {
+9 -8
View File
@@ -20,12 +20,13 @@ struct StartServiceIntent: AppIntent {
guard let extensionProfile = try await (ExtensionProfile.load()) else { guard let extensionProfile = try await (ExtensionProfile.load()) else {
throw NSError(domain: "NetworkExtension not installed", code: 0) throw NSError(domain: "NetworkExtension not installed", code: 0)
} }
let profileList = try ProfileManager.list() let profileList = try await ProfileManager.list()
let specifiedProfile = profileList.first { $0.name == profile } let specifiedProfile = profileList.first { $0.name == profile }
var profileChanged = false var profileChanged = false
if let specifiedProfile { if let specifiedProfile {
if SharedPreferences.selectedProfileID != specifiedProfile.id! { let specifiedProfileID = specifiedProfile.mustID
SharedPreferences.selectedProfileID = specifiedProfile.id! if await SharedPreferences.selectedProfileID.get() != specifiedProfileID {
await SharedPreferences.selectedProfileID.set(specifiedProfileID)
profileChanged = true profileChanged = true
} }
} else if profile != "default" { } else if profile != "default" {
@@ -147,7 +148,7 @@ struct GetCurrentProfile: AppIntent {
} }
func perform() async throws -> some IntentResult { func perform() async throws -> some IntentResult {
guard let profile = try ProfileManager.get(SharedPreferences.selectedProfileID) else { guard let profile = try await ProfileManager.get(SharedPreferences.selectedProfileID.get()) else {
throw NSError(domain: "No profile selected", code: 0) throw NSError(domain: "No profile selected", code: 0)
} }
return .result(value: profile.name) return .result(value: profile.name)
@@ -169,20 +170,20 @@ struct UpdateProfileIntent: AppIntent {
init() {} init() {}
func perform() async throws -> some IntentResult { func perform() async throws -> some IntentResult {
guard let profile = try ProfileManager.get(by: profile) else { guard let profile = try await ProfileManager.get(by: profile) else {
throw NSError(domain: "Specified profile not found: \(profile)", code: 0) throw NSError(domain: "Specified profile not found: \(profile)", code: 0)
} }
if profile.type != .remote { if profile.type != .remote {
throw NSError(domain: "Specified profile is not a remote profile", code: 0) throw NSError(domain: "Specified profile is not a remote profile", code: 0)
} }
try profile.updateRemoteProfile() try await profile.updateRemoteProfile()
return .result() return .result()
} }
} }
class ProfileProvider: DynamicOptionsProvider { class ProfileProvider: DynamicOptionsProvider {
func results() async throws -> [String] { func results() async throws -> [String] {
var profileNames = try ProfileManager.list().map(\.name) var profileNames = try await ProfileManager.list().map(\.name)
if !profileNames.contains("default") { if !profileNames.contains("default") {
profileNames.insert("default", at: 0) profileNames.insert("default", at: 0)
} }
@@ -192,6 +193,6 @@ class ProfileProvider: DynamicOptionsProvider {
class RemoteProfileProvider: DynamicOptionsProvider { class RemoteProfileProvider: DynamicOptionsProvider {
func results() async throws -> [String] { func results() async throws -> [String] {
try ProfileManager.listRemote().map(\.name) try await ProfileManager.listRemote().map(\.name)
} }
} }
+6 -3
View File
@@ -1,7 +1,7 @@
import Foundation import Foundation
import GRDB import GRDB
class Database { actor Database {
private static var writer: (any DatabaseWriter)? private static var writer: (any DatabaseWriter)?
static func sharedWriter() throws -> any DatabaseWriter { static func sharedWriter() throws -> any DatabaseWriter {
@@ -11,8 +11,6 @@ class Database {
try FileManager.default.createDirectory(at: FilePath.sharedDirectory, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: FilePath.sharedDirectory, withIntermediateDirectories: true)
let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath) let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath)
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
migrator.eraseDatabaseOnSchemaChange = true
migrator.registerMigration("initialize") { db in migrator.registerMigration("initialize") { db in
try db.create(table: "profiles") { t in try db.create(table: "profiles") { t in
t.autoIncrementedPrimaryKey("id") t.autoIncrementedPrimaryKey("id")
@@ -29,6 +27,11 @@ class Database {
t.column("data", .blob) 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) try migrator.migrate(database)
writer = database writer = database
+4 -3
View File
@@ -14,6 +14,7 @@ public extension Profile {
} }
if type == .remote { if type == .remote {
content.autoUpdate = autoUpdate content.autoUpdate = autoUpdate
content.autoUpdateInterval = autoUpdateInterval
if let lastUpdated { if let lastUpdated {
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970) content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
} }
@@ -41,8 +42,8 @@ public extension LibboxProfileContent {
return content! return content!
} }
func importProfile() throws { func importProfile() async throws {
let nextProfileID = try ProfileManager.nextID() let nextProfileID = try await ProfileManager.nextID()
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true) let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json") let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
@@ -51,7 +52,7 @@ public extension LibboxProfileContent {
if lastUpdated > 0 { if lastUpdated > 0 {
lastUpdatedAt = Date(timeIntervalSince1970: Double(lastUpdated)) 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 { func generateShareFile() throws -> URL {
+2 -2
View File
@@ -3,7 +3,7 @@ import GRDB
import Libbox import Libbox
public extension Profile { public extension Profile {
func updateRemoteProfile() throws { nonisolated func updateRemoteProfile() async throws {
if type != .remote { if type != .remote {
return return
} }
@@ -15,6 +15,6 @@ public extension Profile {
} }
try write(remoteContent) try write(remoteContent)
lastUpdated = Date() 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 public var path: String
@Published public var remoteURL: String? @Published public var remoteURL: String?
@Published public var autoUpdate: Bool @Published public var autoUpdate: Bool
@Published public var autoUpdateInterval: Int32
public var lastUpdated: Date? 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.id = id
self.name = name self.name = name
self.order = order self.order = order
@@ -24,6 +25,7 @@ public class Profile: Record, Identifiable, ObservableObject {
self.path = path self.path = path
self.remoteURL = remoteURL self.remoteURL = remoteURL
self.autoUpdate = autoUpdate self.autoUpdate = autoUpdate
self.autoUpdateInterval = autoUpdateInterval
self.lastUpdated = lastUpdated self.lastUpdated = lastUpdated
super.init() super.init()
} }
@@ -33,7 +35,7 @@ public class Profile: Record, Identifiable, ObservableObject {
} }
enum Columns: String, ColumnExpression { 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 { required init(row: Row) throws {
@@ -44,6 +46,7 @@ public class Profile: Record, Identifiable, ObservableObject {
path = row[Columns.path] ?? "" path = row[Columns.path] ?? ""
remoteURL = row[Columns.remoteURL] ?? "" remoteURL = row[Columns.remoteURL] ?? ""
autoUpdate = row[Columns.autoUpdate] ?? false autoUpdate = row[Columns.autoUpdate] ?? false
autoUpdateInterval = row[Columns.autoUpdateInterval] ?? 0
lastUpdated = row[Columns.lastUpdated] ?? Date() lastUpdated = row[Columns.lastUpdated] ?? Date()
try super.init(row: row) try super.init(row: row)
} }
@@ -56,6 +59,7 @@ public class Profile: Record, Identifiable, ObservableObject {
container[Columns.path] = path container[Columns.path] = path
container[Columns.remoteURL] = remoteURL container[Columns.remoteURL] = remoteURL
container[Columns.autoUpdate] = autoUpdate container[Columns.autoUpdate] = autoUpdate
container[Columns.autoUpdateInterval] = autoUpdateInterval
container[Columns.lastUpdated] = lastUpdated container[Columns.lastUpdated] = lastUpdated
} }
+29 -29
View File
@@ -2,86 +2,86 @@ import Foundation
import GRDB import GRDB
public enum ProfileManager { public enum ProfileManager {
public static func create(_ profile: Profile) throws { public nonisolated static func create(_ profile: Profile) async throws {
profile.order = try nextOrder() profile.order = try await nextOrder()
try Database.sharedWriter().write { db in try await Database.sharedWriter().write { db in
try profile.insert(db, onConflict: .fail) try profile.insert(db, onConflict: .fail)
} }
} }
public static func get(_ profileID: Int64) throws -> Profile? { public nonisolated static func get(_ profileID: Int64) async throws -> Profile? {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try Profile.fetchOne(db, id: profileID) try Profile.fetchOne(db, id: profileID)
} }
} }
public static func get(by profileName: String) throws -> Profile? { public nonisolated static func get(by profileName: String) async throws -> Profile? {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try Profile.filter(Column("name") == profileName).fetchOne(db) try Profile.filter(Column("name") == profileName).fetchOne(db)
} }
} }
public static func delete(_ profile: Profile) throws { public nonisolated static func delete(_ profile: Profile) async throws {
_ = try Database.sharedWriter().write { db in _ = try await Database.sharedWriter().write { db in
try profile.delete(db) try profile.delete(db)
} }
} }
public static func delete(by id: Int64) throws { public nonisolated static func delete(by id: Int64) async throws {
_ = try Database.sharedWriter().write { db in _ = try await Database.sharedWriter().write { db in
try Profile.deleteOne(db, id: id) try Profile.deleteOne(db, id: id)
} }
} }
public static func delete(_ profileList: [Profile]) throws -> Int { public nonisolated static func delete(_ profileList: [Profile]) async throws -> Int {
try Database.sharedWriter().write { db in try await Database.sharedWriter().write { db in
try Profile.deleteAll(db, keys: profileList.map { try Profile.deleteAll(db, keys: profileList.map {
["id": $0.id!] ["id": $0.id!]
}) })
} }
} }
public static func delete(by id: [Int64]) throws -> Int { public nonisolated static func delete(by id: [Int64]) async throws -> Int {
try Database.sharedWriter().write { db in try await Database.sharedWriter().write { db in
try Profile.deleteAll(db, ids: id) try Profile.deleteAll(db, ids: id)
} }
} }
public static func update(_ profile: Profile) throws { public nonisolated static func update(_ profile: Profile) async throws {
_ = try Database.sharedWriter().write { db in _ = try await Database.sharedWriter().write { db in
try profile.updateChanges(db) try profile.updateChanges(db)
} }
} }
public static func update(_ profileList: [Profile]) throws { public nonisolated static func update(_ profileList: [Profile]) async throws {
// TODO: batch update // TODO: batch update
try Database.sharedWriter().write { db in try await Database.sharedWriter().write { db in
for profile in profileList { for profile in profileList {
try profile.updateChanges(db) try profile.updateChanges(db)
} }
} }
} }
public static func list() throws -> [Profile] { public nonisolated static func list() async throws -> [Profile] {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try Profile.all().order(Column("order").asc).fetchAll(db) try Profile.all().order(Column("order").asc).fetchAll(db)
} }
} }
public static func listRemote() throws -> [Profile] { public nonisolated static func listRemote() async throws -> [Profile] {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db) try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db)
} }
} }
public static func listAutoUpdateEnabled() throws -> [Profile] { public nonisolated static func listAutoUpdateEnabled() async throws -> [Profile] {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db) try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
} }
} }
public static func nextID() throws -> Int64 { public nonisolated static func nextID() async throws -> Int64 {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) { if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) {
return lastProfile.id! + 1 return lastProfile.id! + 1
} else { } else {
@@ -90,8 +90,8 @@ public enum ProfileManager {
} }
} }
private static func nextOrder() throws -> UInt32 { private nonisolated static func nextOrder() async throws -> UInt32 {
try Database.sharedWriter().read { db in try await Database.sharedWriter().read { db in
try UInt32(Profile.fetchCount(db)) try UInt32(Profile.fetchCount(db))
} }
} }
@@ -3,7 +3,7 @@ import Foundation
import GRDB import GRDB
extension SharedPreferences { extension SharedPreferences {
@propertyWrapper public class Preference<T: Codable> { public class Preference<T: Codable> {
private let name: String private let name: String
private let defaultValue: T private let defaultValue: T
@@ -12,53 +12,32 @@ extension SharedPreferences {
self.defaultValue = defaultValue self.defaultValue = defaultValue
} }
public var wrappedValue: T { public nonisolated func get() async -> T {
get {
do { do {
return try SharedPreferences.read(name) ?? defaultValue return try await SharedPreferences.read(name) ?? defaultValue
} catch { } catch {
NSLog("read preferences error: \(error)") NSLog("read preferences error: \(error)")
return defaultValue return defaultValue
} }
} }
set {
public func getBlocking() -> T {
runBlocking { [self] in
await get()
}
}
public nonisolated func set(_ newValue: T) async {
do { do {
try SharedPreferences.write(name, newValue) try await SharedPreferences.write(name, newValue)
} catch { } catch {
NSLog("write preferences error: \(error)") NSLog("write preferences error: \(error)")
} }
} }
} }
}
@propertyWrapper public class NullablePreference<T: Codable> { private nonisolated static func read<T: Codable>(_ name: String) async throws -> T? {
private let name: String guard let item = try await (Database.sharedWriter().read { db in
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) try Item.fetchOne(db, id: name)
}) })
else { else {
@@ -67,14 +46,14 @@ extension SharedPreferences {
return try BinaryDecoder().decode(from: item.data) 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 { if value == nil {
_ = try Database.sharedWriter().write { db in _ = try await Database.sharedWriter().write { db in
try Item.deleteOne(db, id: name) try Item.deleteOne(db, id: name)
} }
} else { } else {
let data = try BinaryEncoder().encode(value) 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) try Item(name: name, data: data).insert(db)
} }
} }
+11 -10
View File
@@ -1,31 +1,32 @@
import Foundation import Foundation
public enum SharedPreferences { 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) #if os(macOS)
private static let disableMemoryLimitByDefault = true private static let disableMemoryLimitByDefault = true
#else #else
private static let disableMemoryLimitByDefault = false private static let disableMemoryLimitByDefault = false
#endif #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) #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 #endif
@Preference<Int>("max_log_lines", defaultValue: 300) public static var maxLogLines public static let maxLogLines = Preference<Int>("max_log_lines", defaultValue: 300)
@Preference<Bool>("always_on", defaultValue: false) public static var alwaysOn public static let alwaysOn = Preference<Bool>("always_on", defaultValue: false)
#if os(macOS) #if os(macOS)
@Preference<Bool>("show_menu_bar_extra", defaultValue: true) public static var showMenuBarExtra public static let showMenuBarExtra = Preference<Bool>("show_menu_bar_extra", defaultValue: true)
@Preference<Bool>("menu_bar_extra_in_background", defaultValue: false) public static var menuBarExtraInBackground public static let menuBarExtraInBackground = Preference<Bool>("menu_bar_extra_in_background", defaultValue: false)
@Preference<Bool>("started_by_user", defaultValue: false) public static var startedByUser public static let startedByUser = Preference<Bool>("started_by_user", defaultValue: false)
#endif #endif
#if os(iOS) #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 #endif
@Preference<Bool>("system_proxy_enabled", defaultValue: true) public static var systemProxyEnabled public static let systemProxyEnabled = Preference<Bool>("system_proxy_enabled", defaultValue: true)
} }
+16 -9
View File
@@ -14,7 +14,7 @@ public class ProfileServer {
if state == .ready { if state == .ready {
Task.detached { Task.detached {
try await Task.sleep(nanoseconds: NSEC_PER_MSEC * 100) 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) self.connection = NWSocket(connection)
} }
func process() { func process() async {
do { do {
try writeProfilePreviewList() try await writeProfilePreviewList()
} catch { } catch {
NSLog("profile server: write profile list: \(error.localizedDescription)") NSLog("profile server: write profile list: \(error.localizedDescription)")
writeError(error.localizedDescription) writeError(error.localizedDescription)
@@ -63,13 +63,22 @@ public class ProfileServer {
let messageType = Int64(data[0]) let messageType = Int64(data[0])
switch messageType { switch messageType {
case LibboxMessageTypeProfileContentRequest: case LibboxMessageTypeProfileContentRequest:
Task {
try await processProfileContentRequest(data)
}
default:
throw NSError(domain: "unexpected message type \(messageType)", code: 0)
}
}
private func processProfileContentRequest(_ data: Data) async throws {
var error: NSError? var error: NSError?
let request = LibboxDecodeProfileContentRequest(data, &error) let request = LibboxDecodeProfileContentRequest(data, &error)
if let error { if let error {
throw error throw error
} }
let profile = try ProfileManager.get(request!.profileID) let profile = try await ProfileManager.get(request!.profileID)
guard let profile else { guard let profile else {
throw NSError(domain: "profile not found", code: 0) throw NSError(domain: "profile not found", code: 0)
} }
@@ -89,18 +98,16 @@ public class ProfileServer {
} }
if profile.type == .remote { if profile.type == .remote {
content.autoUpdate = profile.autoUpdate content.autoUpdate = profile.autoUpdate
content.autoUpdateInterval = profile.autoUpdateInterval
if let lastUpdated = profile.lastUpdated { if let lastUpdated = profile.lastUpdated {
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970) content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
} }
} }
try connection.write(content.encode()) try connection.write(content.encode())
default:
throw NSError(domain: "unexpected message type \(messageType)", code: 0)
}
} }
private func writeProfilePreviewList() throws { private func writeProfilePreviewList() async throws {
let profiles = try ProfileManager.list() let profiles = try await ProfileManager.list()
let encoder = LibboxProfileEncoder() let encoder = LibboxProfileEncoder()
for profile in profiles { for profile in profiles {
let preview = LibboxProfilePreview() let preview = LibboxProfilePreview()
+19 -17
View File
@@ -37,8 +37,8 @@ public class CommandClient: ObservableObject {
if let connectTask { if let connectTask {
connectTask.cancel() connectTask.cancel()
} }
connectTask = Task.detached { connectTask = Task {
await self.connect0() await connect0()
} }
} }
@@ -53,7 +53,7 @@ public class CommandClient: ObservableObject {
} }
} }
private func connect0() async { private nonisolated func connect0() async {
let clientOptions = LibboxCommandClientOptions() let clientOptions = LibboxCommandClientOptions()
switch connectionType { switch connectionType {
case .status: case .status:
@@ -73,7 +73,9 @@ public class CommandClient: ObservableObject {
try Task.checkCancellation() try Task.checkCancellation()
do { do {
try client.connect() try client.connect()
await MainActor.run {
commandClient = client commandClient = client
}
return return
} catch {} } catch {}
try Task.checkCancellation() try Task.checkCancellation()
@@ -90,19 +92,19 @@ public class CommandClient: ObservableObject {
self.commandClient = commandClient self.commandClient = commandClient
} }
func connected() { nonisolated func connected() {
DispatchQueue.main.sync { Task { @MainActor [self] in
self.commandClient.isConnected = true self.commandClient.isConnected = true
} }
} }
func disconnected(_: String?) { nonisolated func disconnected(_: String?) {
DispatchQueue.main.sync { Task { @MainActor [self] in
self.commandClient.isConnected = false self.commandClient.isConnected = false
} }
} }
func writeLog(_ message: String?) { nonisolated func writeLog(_ message: String?) {
guard let message else { guard let message else {
return return
} }
@@ -111,18 +113,18 @@ public class CommandClient: ObservableObject {
logList.removeFirst() logList.removeFirst()
} }
logList.append(message) logList.append(message)
DispatchQueue.main.sync { Task { @MainActor [self, logList] in
self.commandClient.logList = logList self.commandClient.logList = logList
} }
} }
func writeStatus(_ message: LibboxStatusMessage?) { nonisolated func writeStatus(_ message: LibboxStatusMessage?) {
DispatchQueue.main.sync { Task { @MainActor [self] in
self.commandClient.status = message self.commandClient.status = message
} }
} }
func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) { nonisolated func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) {
guard let groups else { guard let groups else {
return return
} }
@@ -130,20 +132,20 @@ public class CommandClient: ObservableObject {
while groups.hasNext() { while groups.hasNext() {
newGroups.append(groups.next()!) newGroups.append(groups.next()!)
} }
DispatchQueue.main.sync { Task { @MainActor [self, newGroups] in
self.commandClient.groups = newGroups self.commandClient.groups = newGroups
} }
} }
func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) { nonisolated func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) {
DispatchQueue.main.sync { Task { @MainActor [self] in
self.commandClient.clashModeList = modeList!.toArray() self.commandClient.clashModeList = modeList!.toArray()
self.commandClient.clashMode = currentMode! self.commandClient.clashMode = currentMode!
} }
} }
func updateClashMode(_ newMode: String?) { nonisolated func updateClashMode(_ newMode: String?) {
DispatchQueue.main.sync { Task { @MainActor [self] in
self.commandClient.clashMode = newMode! self.commandClient.clashMode = newMode!
} }
} }
+16 -3
View File
@@ -2,12 +2,24 @@ import Foundation
import Libbox import Libbox
import NetworkExtension 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 semaphore = DispatchSemaphore(value: 0)
let box = resultBox<T>() 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 { do {
let value = try await body() let value = try await tBlock()
box.result = .success(value) box.result = .success(value)
} catch { } catch {
box.result = .failure(error) box.result = .failure(error)
@@ -20,4 +32,5 @@ func runBlocking<T>(_ body: @escaping () async throws -> T) throws -> T {
private class resultBox<T> { private class resultBox<T> {
var result: Result<T, Error>! var result: Result<T, Error>!
var result0: T!
} }
+3 -3
View File
@@ -12,12 +12,12 @@ public class ExtensionEnvironments: ObservableObject {
} }
public func postReload() { public func postReload() {
Task.detached { Task {
await self.reload() await reload()
} }
} }
public func reload() async { public nonisolated func reload() async {
if let newProfile = try? await ExtensionProfile.load() { if let newProfile = try? await ExtensionProfile.load() {
if extensionProfile == nil || extensionProfile?.status == .invalid { if extensionProfile == nil || extensionProfile?.status == .invalid {
newProfile.register() newProfile.register()
@@ -11,6 +11,12 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
} }
public func openTun(_ options: LibboxTunOptionsProtocol?, ret0_: UnsafeMutablePointer<Int32>?) throws { 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 { guard let options else {
throw NSError(domain: "nil options", code: 0) 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())) let proxyServer = NEProxyServer(address: options.getHTTPProxyServer(), port: Int(options.getHTTPProxyServerPort()))
proxySettings.httpServer = proxyServer proxySettings.httpServer = proxyServer
proxySettings.httpsServer = proxyServer proxySettings.httpsServer = proxyServer
if SharedPreferences.systemProxyEnabled { if try await SharedPreferences.systemProxyEnabled.get() {
proxySettings.httpEnabled = true proxySettings.httpEnabled = true
proxySettings.httpsEnabled = true proxySettings.httpsEnabled = true
} }
@@ -169,7 +175,9 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
} }
public func serviceReload() throws { public func serviceReload() throws {
tunnel.reloadService() Task {
await tunnel.reloadService()
}
} }
public func getSystemProxyStatus() -> LibboxSystemProxyStatus? { public func getSystemProxyStatus() -> LibboxSystemProxyStatus? {
+2 -6
View File
@@ -14,10 +14,6 @@ public class ExtensionProfile: ObservableObject {
status = manager.connection.status status = manager.connection.status
} }
deinit {
unregister()
}
public func register() { public func register() {
observer = NotificationCenter.default.addObserver( observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange, forName: NSNotification.Name.NEVPNStatusDidChange,
@@ -54,13 +50,13 @@ public class ExtensionProfile: ObservableObject {
public func start() async throws { public func start() async throws {
manager.isEnabled = true manager.isEnabled = true
if SharedPreferences.alwaysOn { if try await SharedPreferences.alwaysOn.get() {
manager.isOnDemandEnabled = true manager.isOnDemandEnabled = true
setOnDemandRules() setOnDemandRules()
} }
#if !os(tvOS) #if !os(tvOS)
if let protocolConfiguration = manager.protocolConfiguration { if let protocolConfiguration = manager.protocolConfiguration {
let includeAllNetworks = SharedPreferences.includeAllNetworks let includeAllNetworks = try await SharedPreferences.includeAllNetworks.get()
protocolConfiguration.includeAllNetworks = includeAllNetworks protocolConfiguration.includeAllNetworks = includeAllNetworks
if #available(iOS 16.4, macOS 13.3, *) { if #available(iOS 16.4, macOS 13.3, *) {
protocolConfiguration.excludeCellularServices = !includeAllNetworks protocolConfiguration.excludeCellularServices = !includeAllNetworks
+10 -15
View File
@@ -13,8 +13,6 @@ open class ExtensionProvider: NEPacketTunnelProvider {
private var platformInterface: ExtensionPlatformInterface! private var platformInterface: ExtensionPlatformInterface!
override open func startTunnel(options _: [String: NSObject]?) async throws { override open func startTunnel(options _: [String: NSObject]?) async throws {
NSLog("Here I am")
try? FileManager.default.removeItem(at: ExtensionProvider.errorFile) try? FileManager.default.removeItem(at: ExtensionProvider.errorFile)
do { do {
@@ -45,12 +43,12 @@ open class ExtensionProvider: NEPacketTunnelProvider {
writeError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)") writeError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)")
} }
LibboxSetMemoryLimit(!SharedPreferences.disableMemoryLimit) try await LibboxSetMemoryLimit(!SharedPreferences.disableMemoryLimit.get())
if platformInterface == nil { if platformInterface == nil {
platformInterface = ExtensionPlatformInterface(self) platformInterface = ExtensionPlatformInterface(self)
} }
commandServer = LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines)) commandServer = try await LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines.get()))
do { do {
try commandServer.start() try commandServer.start()
} catch { } catch {
@@ -58,8 +56,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
return return
} }
writeMessage("(packet-tunnel) log server started") writeMessage("(packet-tunnel) log server started")
await startService()
startService()
} }
func writeMessage(_ message: String) { func writeMessage(_ message: String) {
@@ -83,10 +80,10 @@ open class ExtensionProvider: NEPacketTunnelProvider {
cancelTunnelWithError(NSError(domain: message, code: 0)) cancelTunnelWithError(NSError(domain: message, code: 0))
} }
private func startService() { private func startService() async {
let profile: Profile? let profile: Profile?
do { do {
profile = try ProfileManager.get(Int64(SharedPreferences.selectedProfileID)) profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get()))
} catch { } catch {
writeFatalError("(packet-tunnel) error: missing default profile: \(error.localizedDescription)") writeFatalError("(packet-tunnel) error: missing default profile: \(error.localizedDescription)")
return return
@@ -97,7 +94,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
} }
let configContent: String let configContent: String
do { do {
configContent = try profile.read() configContent = try await profile.read()
} catch { } catch {
writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)") writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)")
return return
@@ -120,9 +117,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
boxService = service boxService = service
commandServer.setService(service) commandServer.setService(service)
#if os(macOS) #if os(macOS)
Task.detached { await SharedPreferences.startedByUser.set(true)
SharedPreferences.startedByUser = true
}
#endif #endif
} }
@@ -138,14 +133,14 @@ open class ExtensionProvider: NEPacketTunnelProvider {
} }
} }
func reloadService() { func reloadService() async {
writeMessage("(packet-tunnel) reloading service") writeMessage("(packet-tunnel) reloading service")
reasserting = true reasserting = true
defer { defer {
reasserting = false reasserting = false
} }
stopService() stopService()
startService() await startService()
} }
override open func stopTunnel(with reason: NEProviderStopReason) async { override open func stopTunnel(with reason: NEProviderStopReason) async {
@@ -158,7 +153,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
} }
#if os(macOS) #if os(macOS)
if reason == .userInitiated { if reason == .userInitiated {
SharedPreferences.startedByUser = reason == .userInitiated await SharedPreferences.startedByUser.set(reason == .userInitiated)
} }
#endif #endif
} }
+6 -2
View File
@@ -76,7 +76,12 @@
} }
public static func isInstalled() async -> Bool { public static func isInstalled() async -> Bool {
await (try? Task.detached { await (try? Task {
try await isInstalledBackground()
}.result.get()) == true
}
public nonisolated static func isInstalledBackground() async throws -> Bool {
for _ in 0 ..< 3 { for _ in 0 ..< 3 {
do { do {
let propList = try SystemExtension().getProperties() let propList = try SystemExtension().getProperties()
@@ -93,7 +98,6 @@
} }
} }
return false return false
}.result.get()) == true
} }
public static func install(forceUpdate: Bool = false, inBackground _: Bool = false) async throws -> OSSystemExtensionRequest.Result? { public static func install(forceUpdate: Bool = false, inBackground _: Bool = false) async throws -> OSSystemExtensionRequest.Result? {
+5 -5
View File
@@ -12,17 +12,17 @@ open class ApplicationDelegate: NSObject, NSApplicationDelegate {
let launchedAsLogInItem = let launchedAsLogInItem =
event?.eventID == kAEOpenApplication && event?.eventID == kAEOpenApplication &&
event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem
if !launchedAsLogInItem || !SharedPreferences.showMenuBarExtra || !SharedPreferences.menuBarExtraInBackground { if !launchedAsLogInItem || !SharedPreferences.showMenuBarExtra.getBlocking() || !SharedPreferences.menuBarExtraInBackground.getBlocking() {
NSApp.setActivationPolicy(.regular) NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true) NSApp.activate(ignoringOtherApps: true)
} else { } else {
NSApp.windows.first?.close() NSApp.windows.first?.close()
} }
Task.detached { Task {
do { do {
try ProfileUpdateTask.setup() try await ProfileUpdateTask.configure()
if launchedAsLogInItem { if launchedAsLogInItem {
if SharedPreferences.startedByUser { if await SharedPreferences.startedByUser.get() {
if let profile = try await ExtensionProfile.load() { if let profile = try await ExtensionProfile.load() {
try await profile.start() try await profile.start()
} }
@@ -35,7 +35,7 @@ open class ApplicationDelegate: NSObject, NSApplicationDelegate {
} }
public func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool { public func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool {
!SharedPreferences.menuBarExtraInBackground !SharedPreferences.menuBarExtraInBackground.getBlocking()
} }
public func applicationShouldHandleReopen(_: NSApplication, hasVisibleWindows flag: Bool) -> Bool { public func applicationShouldHandleReopen(_: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
+5 -12
View File
@@ -12,7 +12,7 @@ public struct MacApplication: Scene {
Window("sing-box", id: "main", content: { Window("sing-box", id: "main", content: {
MainView() MainView()
.onAppear { .onAppear {
Task.detached { Task {
await initialize() await initialize()
} }
} }
@@ -61,21 +61,15 @@ public struct MacApplication: Scene {
.menuBarExtraAccess(isPresented: $isMenuPresented) .menuBarExtraAccess(isPresented: $isMenuPresented)
} }
private func initialize() { private func initialize() async {
let initialShowMenuBarExtra = SharedPreferences.showMenuBarExtra showMenuBarExtra = await SharedPreferences.showMenuBarExtra.get()
DispatchQueue.main.async {
showMenuBarExtra = initialShowMenuBarExtra
}
} }
private func hide(closeApp: Bool) { private func hide(closeApp: Bool) {
Task.detached { Task {
if SharedPreferences.menuBarExtraInBackground { if await SharedPreferences.menuBarExtraInBackground.get() {
DispatchQueue.main.async {
hide0(closeApp: closeApp) hide0(closeApp: closeApp)
}
} else { } else {
DispatchQueue.main.async {
if closeApp { if closeApp {
NSApp.terminate(nil) NSApp.terminate(nil)
} else { } else {
@@ -84,7 +78,6 @@ public struct MacApplication: Scene {
} }
} }
} }
}
private func hide0(closeApp: Bool) { private func hide0(closeApp: Bool) {
if closeApp || NSApp.keyWindow?.identifier?.rawValue == "main" { if closeApp || NSApp.keyWindow?.identifier?.rawValue == "main" {
+16 -5
View File
@@ -3,6 +3,7 @@ import Libbox
import Library import Library
import SwiftUI import SwiftUI
@MainActor
public struct MainView: View { public struct MainView: View {
@Environment(\.controlActiveState) private var controlActiveState @Environment(\.controlActiveState) private var controlActiveState
@EnvironmentObject private var environments: ExtensionEnvironments @EnvironmentObject private var environments: ExtensionEnvironments
@@ -32,8 +33,8 @@ public struct MainView: View {
environments.postReload() environments.postReload()
#if !DEBUG #if !DEBUG
if Variant.useSystemExtension { if Variant.useSystemExtension {
Task.detached { Task {
await checkApplicationPath() checkApplicationPath()
} }
} }
#endif #endif
@@ -73,9 +74,18 @@ public struct MainView: View {
selection = .profiles selection = .profiles
} }
} else if url.pathExtension == "bpf" { } else if url.pathExtension == "bpf" {
Task {
await importURLProfile(url)
}
} else {
alert = Alert(errorMessage: "Handled unknown URL \(url.absoluteString)")
}
}
private func importURLProfile(_ url: URL) async {
do { do {
_ = url.startAccessingSecurityScopedResource() _ = url.startAccessingSecurityScopedResource()
importProfile = try .from(Data(contentsOf: url)) importProfile = try await .from(readURL(url))
url.stopAccessingSecurityScopedResource() url.stopAccessingSecurityScopedResource()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
@@ -84,9 +94,10 @@ public struct MainView: View {
if selection != .profiles { if selection != .profiles {
selection = .profiles selection = .profiles
} }
} else {
alert = Alert(errorMessage: "Handled unknown URL \(url.absoluteString)")
} }
private nonisolated func readURL(_ url: URL) async throws -> Data {
try Data(contentsOf: url)
} }
private func checkApplicationPath() { private func checkApplicationPath() {
+16 -12
View File
@@ -6,6 +6,7 @@ import MacControlCenterUI
import MenuBarExtraAccess import MenuBarExtraAccess
import SwiftUI import SwiftUI
@MainActor
public struct MenuView: View { public struct MenuView: View {
@Environment(\.openWindow) private var openWindow @Environment(\.openWindow) private var openWindow
@@ -25,7 +26,7 @@ public struct MenuView: View {
MenuHeader("sing-box") { MenuHeader("sing-box") {
if isLoading { if isLoading {
Text("Loading...").foregroundColor(.secondary).onAppear { Text("Loading...").foregroundColor(.secondary).onAppear {
Task.detached { Task {
await loadProfile() await loadProfile()
} }
} }
@@ -81,7 +82,7 @@ public struct MenuView: View {
Toggle(isOn: Binding(get: { Toggle(isOn: Binding(get: {
profile.status.isConnected profile.status.isConnected
}, set: { _ in }, set: { _ in
Task.detached { Task {
await switchProfile(!profile.status.isConnected) await switchProfile(!profile.status.isConnected)
} }
})) {} })) {}
@@ -122,7 +123,7 @@ public struct MenuView: View {
viewBuilder { viewBuilder {
if isLoading { if isLoading {
ProgressView().onAppear { ProgressView().onAppear {
Task.detached { Task {
await doReload() await doReload()
} }
} }
@@ -139,7 +140,7 @@ public struct MenuView: View {
.pickerStyle(.inline) .pickerStyle(.inline)
.onChangeCompat(of: selectedProfileID) { .onChangeCompat(of: selectedProfileID) {
reasserting = true reasserting = true
Task.detached { Task {
await switchProfile(selectedProfileID!) await switchProfile(selectedProfileID!)
} }
} }
@@ -162,12 +163,12 @@ public struct MenuView: View {
.alertBinding($alert) .alertBinding($alert)
} }
private func doReload() { private func doReload() async {
defer { defer {
isLoading = false isLoading = false
} }
do { do {
profileList = try ProfileManager.list() profileList = try await ProfileManager.list()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
return return
@@ -175,28 +176,31 @@ public struct MenuView: View {
if profileList.isEmpty { if profileList.isEmpty {
return return
} }
selectedProfileID = await SharedPreferences.selectedProfileID.get()
selectedProfileID = SharedPreferences.selectedProfileID
if profileList.filter({ profile in if profileList.filter({ profile in
profile.id == selectedProfileID profile.id == selectedProfileID
}) })
.isEmpty { .isEmpty {
selectedProfileID = profileList[0].id! selectedProfileID = profileList[0].id!
SharedPreferences.selectedProfileID = selectedProfileID await SharedPreferences.selectedProfileID.set(selectedProfileID)
} }
} }
private func switchProfile(_ newProfileID: Int64) { private func switchProfile(_ newProfileID: Int64) async {
SharedPreferences.selectedProfileID = newProfileID await SharedPreferences.selectedProfileID.set(newProfileID)
NotificationCenter.default.post(name: OverviewView.NotificationUpdateSelectedProfile, object: newProfileID) NotificationCenter.default.post(name: OverviewView.NotificationUpdateSelectedProfile, object: newProfileID)
if profile.status.isConnected { if profile.status.isConnected {
do { do {
try LibboxNewStandaloneCommandClient()?.serviceReload() try await serviceReload()
} catch { } catch {
alert = Alert(error) alert = Alert(error)
} }
} }
reasserting = false reasserting = false
} }
private nonisolated func serviceReload() async throws {
try LibboxNewStandaloneCommandClient()?.serviceReload()
}
} }
} }
+27 -24
View File
@@ -11,51 +11,54 @@ class ApplicationDelegate: NSObject, UIApplicationDelegate {
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
NSLog("Here I stand") NSLog("Here I stand")
LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, false) LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, false)
Task.detached { Task {
do { await setup()
try await UIProfileUpdateTask.setup()
NSLog("setup background task success")
} catch {
NSLog("setup background task error: \(error.localizedDescription)")
}
}
Task.detached {
await self.requestNetworkPermission()
}
if #available(iOS 16.0, *) {
Task.detached {
await self.setupProfileServer()
}
} }
return true return true
} }
@available(iOS 16.0, *) private func setup() async {
private func setupProfileServer() { await setupBackground()
if UIDevice.current.userInterfaceIdiom == .phone {
await requestNetworkPermission()
}
}
private nonisolated func setupBackground() async {
do {
try await UIProfileUpdateTask.configure()
NSLog("setup background task success")
} catch {
NSLog("setup background task error: \(error.localizedDescription)")
}
if #available(iOS 16.0, *) {
do { do {
let profileServer = try ProfileServer() let profileServer = try ProfileServer()
profileServer.start() profileServer.start()
await MainActor.run {
self.profileServer = profileServer self.profileServer = profileServer
}
NSLog("started profile server")
} catch { } catch {
NSLog("setup profile server error: \(error.localizedDescription)") NSLog("setup profile server error: \(error.localizedDescription)")
} }
} }
private func requestNetworkPermission() {
if UIDevice.current.userInterfaceIdiom != .phone {
return
} }
if SharedPreferences.networkPermissionRequested {
private nonisolated func requestNetworkPermission() async {
if await SharedPreferences.networkPermissionRequested.get() {
return return
} }
if !DeviceCensorship.isChinaDevice() { if !DeviceCensorship.isChinaDevice() {
SharedPreferences.networkPermissionRequested = true await SharedPreferences.networkPermissionRequested.set(true)
return return
} }
URLSession.shared.dataTask(with: URL(string: "http://captive.apple.com")!) { _, response, _ in URLSession.shared.dataTask(with: URL(string: "http://captive.apple.com")!) { _, response, _ in
if let response = response as? HTTPURLResponse { if let response = response as? HTTPURLResponse {
if response.statusCode == 200 { if response.statusCode == 200 {
SharedPreferences.networkPermissionRequested = true Task {
await SharedPreferences.networkPermissionRequested.set(true)
}
} }
} }
}.resume() }.resume()
@@ -6,7 +6,13 @@ import MacLibrary
class IndependentApplicationDelegate: ApplicationDelegate { class IndependentApplicationDelegate: ApplicationDelegate {
public func applicationWillFinishLaunching(_: Notification) { public func applicationWillFinishLaunching(_: Notification) {
Variant.useSystemExtension = true Variant.useSystemExtension = true
Task.detached { Task {
await setupSystemExtension()
}
}
private nonisolated func setupSystemExtension() async {
do {
if await SystemExtension.isInstalled() { if await SystemExtension.isInstalled() {
if let result = try await SystemExtension.install() { if let result = try await SystemExtension.install() {
if result == .willCompleteAfterReboot { if result == .willCompleteAfterReboot {
@@ -14,6 +20,8 @@ class IndependentApplicationDelegate: ApplicationDelegate {
} }
} }
} }
} catch {
NSLog("setup system extension error: \(error.localizedDescription)")
} }
} }
} }
+8 -4
View File
@@ -8,14 +8,18 @@ class ApplicationDelegate: NSObject, UIApplicationDelegate {
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
NSLog("Here I stand") NSLog("Here I stand")
LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, true) LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, true)
Task.detached { Task {
await setupBackground()
}
return true
}
private nonisolated func setupBackground() async {
do { do {
try await UIProfileUpdateTask.setup() try await UIProfileUpdateTask.configure()
NSLog("setup background task success") NSLog("setup background task success")
} catch { } catch {
NSLog("setup background task error: \(error.localizedDescription)") NSLog("setup background task error: \(error.localizedDescription)")
} }
} }
return true
}
} }
+4 -4
View File
@@ -2489,7 +2489,7 @@
"@executable_path/../../../../Frameworks", "@executable_path/../../../../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 13.0; MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.5.0-rc.1; MARKETING_VERSION = 1.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.system; PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.system;
PRODUCT_NAME = "$(inherited)"; PRODUCT_NAME = "$(inherited)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@@ -2525,7 +2525,7 @@
"@executable_path/../../../../Frameworks", "@executable_path/../../../../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 13.0; MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.5.0-rc.1; MARKETING_VERSION = 1.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.system; PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.system;
PRODUCT_NAME = "$(inherited)"; PRODUCT_NAME = "$(inherited)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@@ -2565,7 +2565,7 @@
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 13.0; MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.5.0-rc.1; MARKETING_VERSION = 1.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.independent; PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.independent;
PRODUCT_NAME = SFM; PRODUCT_NAME = SFM;
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@@ -2604,7 +2604,7 @@
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 13.0; MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.5.0-rc.1; MARKETING_VERSION = 1.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.independent; PRODUCT_BUNDLE_IDENTIFIER = io.nekohasekai.sfa.independent;
PRODUCT_NAME = SFM; PRODUCT_NAME = SFM;
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";