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