Refactor to MVVM architecture

This commit is contained in:
世界
2025-11-26 22:25:48 +08:00
parent 61f1036f57
commit b71cbae382
31 changed files with 1551 additions and 1229 deletions
@@ -10,42 +10,34 @@
public let readOnly: Bool
}
private let profileID: Int64?
private let readOnly: Bool
@StateObject private var viewModel: EditProfileContentViewModel
public init(_ context: Context?) {
profileID = context?.profileID
readOnly = context?.readOnly == true
_viewModel = StateObject(wrappedValue: EditProfileContentViewModel(profileID: context?.profileID))
}
@Environment(\.dismiss) private var dismiss
@State private var isLoading = true
@State private var profile: Profile!
@State private var profileContent = ""
@State private var isChanged = false
@State private var alert: Alert?
public var body: some View {
viewBuilder {
if isLoading {
if viewModel.isLoading {
ProgressView().onAppear {
Task {
await loadContent()
await viewModel.loadContent()
}
}
} else {
viewBuilder {
if readOnly {
TextEditor(text: .constant(profileContent))
TextEditor(text: .constant(viewModel.profileContent))
} else {
TextEditor(text: $profileContent)
TextEditor(text: $viewModel.profileContent)
}
}
.font(Font.system(.caption2, design: .monospaced))
.autocorrectionDisabled(true)
// https://stackoverflow.com/questions/66721935/swiftui-how-to-disable-the-smart-quotes-in-texteditor
// https://stackoverflow.com/questions/74034171/textfield-with-autocorrectiondisabled-still-shows-predictive-text-bar
.textContentType(.init(rawValue: ""))
#if os(iOS)
.keyboardType(.asciiCapable)
@@ -54,12 +46,12 @@
#elseif os(macOS)
.padding()
#endif
.onChangeCompat(of: profileContent) {
isChanged = true
.onChangeCompat(of: viewModel.profileContent) {
viewModel.markAsChanged()
}
}
}
.alertBinding($alert)
.alertBinding($viewModel.alert)
.navigationTitle(navigationTitle)
#if os(macOS)
.toolbar {
@@ -67,15 +59,15 @@
if !readOnly {
Button {
Task {
await saveContent()
await viewModel.saveContent()
}
} label: {
Label("Save", image: "save")
}
.disabled(!isChanged)
.disabled(!viewModel.isChanged)
} else {
Button {
NSPasteboard.general.setString(profileContent, forType: .fileContents)
NSPasteboard.general.setString(viewModel.profileContent, forType: .fileContents)
} label: {
Label("Copy", systemImage: "clipboard.fill")
}
@@ -88,12 +80,12 @@
if !readOnly {
Button("Save") {
Task {
await saveContent()
await viewModel.saveContent()
}
}.disabled(!isChanged)
}.disabled(!viewModel.isChanged)
} else {
Button("Copy") {
UIPasteboard.general.string = profileContent
UIPasteboard.general.string = viewModel.profileContent
}
}
}
@@ -109,46 +101,6 @@
return String(localized: "Edit Content")
}
}
private func loadContent() async {
do {
try await loadContentBackground()
} catch {
alert = Alert(error)
}
isLoading = false
}
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 await saveContentBackground(profile)
} catch {
alert = Alert(error)
return
}
isChanged = false
}
private nonisolated func saveContentBackground(_ profile: Profile) async throws {
try await profile.write(profileContent)
}
}
#endif
@@ -0,0 +1,66 @@
#if os(iOS) || os(macOS)
import Foundation
import Library
import SwiftUI
@MainActor
public final class EditProfileContentViewModel: ObservableObject {
@Published public var isLoading = true
@Published public var profile: Profile?
@Published public var profileContent = ""
@Published public var isChanged = false
@Published public var alert: Alert?
private let profileID: Int64?
public init(profileID: Int64?) {
self.profileID = profileID
}
public func markAsChanged() {
isChanged = true
}
public func loadContent() async {
do {
try await loadContentBackground()
} catch {
alert = Alert(error)
}
isLoading = false
}
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
}
}
public func saveContent() async {
guard let profile else {
return
}
do {
try await saveContentBackground(profile)
} catch {
alert = Alert(error)
return
}
isChanged = false
}
private nonisolated func saveContentBackground(_ profile: Profile) async throws {
let profileContent = await profileContent
try profile.write(profileContent)
}
}
#endif
@@ -7,12 +7,7 @@ public struct EditProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var profile: Profile
@State private var isLoading = false
@State private var isChanged = false
@State private var alert: Alert?
@State private var shareLinkPresented = false
@State private var shareLinkText: String?
@StateObject private var viewModel = EditProfileViewModel()
public init() {}
public var body: some View {
@@ -80,19 +75,19 @@ public struct EditProfileView: View {
}
#endif
FormButton {
isLoading = true
viewModel.isLoading = true
Task {
await updateProfile()
await viewModel.updateProfile(profile, environments: environments)
}
} label: {
Label("Update", systemImage: "arrow.clockwise")
}
.foregroundColor(.accentColor)
.disabled(isLoading)
.disabled(viewModel.isLoading)
}
FormButton(role: .destructive) {
Task {
await deleteProfile()
await viewModel.deleteProfile(profile, environments: environments, dismiss: dismiss)
}
} label: {
Label("Delete", systemImage: "trash.fill")
@@ -101,84 +96,42 @@ public struct EditProfileView: View {
}
}
.onChangeCompat(of: profile.name) {
isChanged = true
viewModel.markAsChanged()
}
.onChangeCompat(of: profile.remoteURL) {
isChanged = true
viewModel.markAsChanged()
}
.onChangeCompat(of: profile.autoUpdate) {
isChanged = true
viewModel.markAsChanged()
}
.disabled(isLoading)
.disabled(viewModel.isLoading)
#if os(macOS)
.toolbar {
ToolbarItemGroup(placement: .navigation) {
Button {
isLoading = true
viewModel.isLoading = true
Task {
await saveProfile()
await viewModel.saveProfile(profile, environments: environments)
}
} label: {
Image("save", bundle: ApplicationLibrary.bundle, label: Text("Save"))
}
.disabled(isLoading || !isChanged)
.disabled(viewModel.isLoading || !viewModel.isChanged)
}
}
#elseif os(iOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
isLoading = true
viewModel.isLoading = true
Task {
await saveProfile()
await viewModel.saveProfile(profile, environments: environments)
}
}.disabled(!isChanged)
}.disabled(!viewModel.isChanged)
}
}
#endif
.alertBinding($alert)
.alertBinding($viewModel.alert)
.navigationTitle("Edit Profile")
}
private func updateProfile() async {
defer {
isLoading = false
}
do {
try await Task.sleep(nanoseconds: UInt64(100 * Double(NSEC_PER_MSEC)))
try await profile.updateRemoteProfile()
environments.profileUpdate.send()
} catch {
alert = Alert(error)
}
}
private func deleteProfile() async {
do {
try await ProfileManager.delete(profile)
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
}
private func saveProfile() async {
do {
_ = try await ProfileManager.update(profile)
#if os(iOS) || os(tvOS)
try UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
try await profile.onProfileUpdated()
} catch {
alert = Alert(error)
return
}
isChanged = false
isLoading = false
environments.profileUpdate.send()
}
}
@@ -0,0 +1,60 @@
import Libbox
import Library
import SwiftUI
@MainActor
public final class EditProfileViewModel: ObservableObject {
@Published public var isLoading = false
@Published public var isChanged = false
@Published public var alert: Alert?
@Published public var shareLinkPresented = false
@Published public var shareLinkText: String?
public init() {}
public func markAsChanged() {
isChanged = true
}
public func updateProfile(_ profile: Profile, environments: ExtensionEnvironments) async {
defer {
isLoading = false
}
do {
try await Task.sleep(nanoseconds: UInt64(100 * Double(NSEC_PER_MSEC)))
try await profile.updateRemoteProfile()
environments.profileUpdate.send()
} catch {
alert = Alert(error)
}
}
public func deleteProfile(_ profile: Profile, environments: ExtensionEnvironments, dismiss: DismissAction) async {
do {
try await ProfileManager.delete(profile)
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
}
public func saveProfile(_ profile: Profile, environments: ExtensionEnvironments) async {
do {
_ = try await ProfileManager.update(profile)
#if os(iOS) || os(tvOS)
try UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
try await profile.onProfileUpdated()
} catch {
alert = Alert(error)
return
}
isChanged = false
isLoading = false
environments.profileUpdate.send()
}
}
@@ -9,19 +9,12 @@
public struct ImportProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@State private var isLoading = false
@State private var selected = false
@State private var alert: Alert?
@State private var connection: NWConnection?
@State private var socket: NWSocket?
@State private var profiles: [LibboxProfilePreview]?
@State private var isImporting = false
@StateObject private var viewModel = ImportProfileViewModel()
public init() {}
public var body: some View {
VStack(alignment: .center) {
if !selected {
if !viewModel.selected {
Form {
Section {
EmptyView()
@@ -32,9 +25,9 @@
DevicePicker(
.applicationService(name: "sing-box:profile"))
{ endpoint in
selected = true
viewModel.selected = true
Task {
await handleEndpoint(endpoint)
await viewModel.handleEndpoint(endpoint, environments: environments, dismiss: dismiss)
}
} label: {
Text("Select Device")
@@ -44,7 +37,7 @@
.applicationService
}
}
} else if let profiles {
} else if let profiles = viewModel.profiles {
Form {
Section {
EmptyView()
@@ -53,12 +46,12 @@
}
ForEach(profiles, id: \.profileID) { profile in
Button(profile.name) {
isLoading = true
viewModel.isLoading = true
Task {
selectProfile(profileID: profile.profileID)
isLoading = false
viewModel.selectProfile(profileID: profile.profileID)
viewModel.isLoading = false
}
}.disabled(isLoading || isImporting)
}.disabled(viewModel.isLoading || viewModel.isImporting)
}
}
} else {
@@ -66,145 +59,9 @@
}
}
.focusSection()
.alertBinding($alert)
.alertBinding($viewModel.alert)
.navigationTitle("Import Profile")
}
private func reset() {
if let connection {
connection.stateUpdateHandler = nil
connection.cancel()
self.connection = nil
}
if let socket {
socket.cancel()
self.socket = nil
}
selected = false
profiles = nil
}
private func handleEndpoint(_ endpoint: NWEndpoint) async {
let connection = NWConnection(to: endpoint, using: NWParameters.applicationService)
self.connection = connection
socket = NWSocket(connection)
connection.stateUpdateHandler = { state in
switch state {
case let .failed(error):
DispatchQueue.main.async { [self] in
reset()
alert = Alert(error)
}
default: break
}
}
connection.start(queue: .global())
do {
try await loopMessages()
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func loopMessages() async throws {
guard let socket = await socket else {
return
}
var message: Data
while true {
do {
message = try socket.read()
} catch {
throw NSError(domain: "read from connection: \(error.localizedDescription)", code: 0)
}
var error: NSError?
switch Int64(message[0]) {
case LibboxMessageTypeError:
let message = LibboxDecodeErrorMessage(message, &error)
if let error {
throw error
}
if let message {
throw NSError(domain: "remote error: \(message.message)", code: 0)
}
case LibboxMessageTypeProfileList:
let decoder = LibboxProfileDecoder()
try decoder.decode(message)
let iterator = decoder.iterator()!
var profiles = [LibboxProfilePreview]()
while iterator.hasNext() {
let profile = iterator.next()!
if profile.type == LibboxProfileTypeiCloud {
// not supported on tvOS
continue
}
profiles.append(profile)
}
await MainActor.run { [self, profiles] in
self.profiles = profiles
isImporting = false
}
case LibboxMessageTypeProfileContent:
let content = LibboxDecodeProfileContent(message, &error)
if let error {
throw error
}
try await importProfile(content!)
return
default:
throw NSError(domain: "unknown message type \(message[0])", code: 0)
}
}
}
private func selectProfile(profileID: Int64) {
guard let connection else {
return
}
guard let socket else {
return
}
connection.stateUpdateHandler = nil
let request = LibboxProfileContentRequest()
request.profileID = profileID
do {
try socket.write(request.encode())
isImporting = true
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func importProfile(_ content: LibboxProfileContent) async throws {
var type: ProfileType = .local
switch content.type {
case LibboxProfileTypeLocal:
type = .local
case LibboxProfileTypeiCloud:
type = .icloud
case LibboxProfileTypeRemote:
type = .remote
default:
break
}
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")
try content.config.write(to: profileConfig, atomically: true, encoding: .utf8)
var lastUpdated: Date?
if content.lastUpdated > 0 {
lastUpdated = Date(timeIntervalSince1970: Double(content.lastUpdated))
}
try await ProfileManager.create(Profile(name: content.name, type: type, path: profileConfig.relativePath, remoteURL: content.remotePath, autoUpdate: content.autoUpdate, lastUpdated: lastUpdated))
await reset()
await MainActor.run {
environments.profileUpdate.send()
dismiss()
}
}
}
#endif
@@ -0,0 +1,157 @@
#if os(tvOS)
import DeviceDiscoveryUI
import Libbox
import Library
import Network
import SwiftUI
@MainActor
public final class ImportProfileViewModel: ObservableObject {
@Published public var isLoading = false
@Published public var selected = false
@Published public var alert: Alert?
@Published public var connection: NWConnection?
@Published public var socket: NWSocket?
@Published public var profiles: [LibboxProfilePreview]?
@Published public var isImporting = false
public init() {}
public func reset() {
if let connection {
connection.stateUpdateHandler = nil
connection.cancel()
self.connection = nil
}
if let socket {
socket.cancel()
self.socket = nil
}
selected = false
profiles = nil
}
public func handleEndpoint(_ endpoint: NWEndpoint, environments: ExtensionEnvironments, dismiss: DismissAction) async {
let connection = NWConnection(to: endpoint, using: NWParameters.applicationService)
self.connection = connection
socket = NWSocket(connection)
connection.stateUpdateHandler = { state in
switch state {
case let .failed(error):
DispatchQueue.main.async { [self] in
reset()
alert = Alert(error)
}
default: break
}
}
connection.start(queue: .global())
do {
try await loopMessages(environments: environments, dismiss: dismiss)
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func loopMessages(environments: ExtensionEnvironments, dismiss: DismissAction) async throws {
guard let socket = await socket else {
return
}
var message: Data
while true {
do {
message = try socket.read()
} catch {
throw NSError(domain: "read from connection: \(error.localizedDescription)", code: 0)
}
var error: NSError?
switch Int64(message[0]) {
case LibboxMessageTypeError:
let message = LibboxDecodeErrorMessage(message, &error)
if let error {
throw error
}
if let message {
throw NSError(domain: "remote error: \(message.message)", code: 0)
}
case LibboxMessageTypeProfileList:
let decoder = LibboxProfileDecoder()
try decoder.decode(message)
let iterator = decoder.iterator()!
var profiles = [LibboxProfilePreview]()
while iterator.hasNext() {
let profile = iterator.next()!
if profile.type == LibboxProfileTypeiCloud {
continue
}
profiles.append(profile)
}
await MainActor.run { [self, profiles] in
self.profiles = profiles
isImporting = false
}
case LibboxMessageTypeProfileContent:
let content = LibboxDecodeProfileContent(message, &error)
if let error {
throw error
}
try await importProfile(content!, environments: environments, dismiss: dismiss)
return
default:
throw NSError(domain: "unknown message type \(message[0])", code: 0)
}
}
}
public func selectProfile(profileID: Int64) {
guard let connection else {
return
}
guard let socket else {
return
}
connection.stateUpdateHandler = nil
let request = LibboxProfileContentRequest()
request.profileID = profileID
do {
try socket.write(request.encode())
isImporting = true
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func importProfile(_ content: LibboxProfileContent, environments: ExtensionEnvironments, dismiss: DismissAction) async throws {
var type: ProfileType = .local
switch content.type {
case LibboxProfileTypeLocal:
type = .local
case LibboxProfileTypeiCloud:
type = .icloud
case LibboxProfileTypeRemote:
type = .remote
default:
break
}
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")
try content.config.write(to: profileConfig, atomically: true, encoding: .utf8)
var lastUpdated: Date?
if content.lastUpdated > 0 {
lastUpdated = Date(timeIntervalSince1970: Double(content.lastUpdated))
}
try await ProfileManager.create(Profile(name: content.name, type: type, path: profileConfig.relativePath, remoteURL: content.remotePath, autoUpdate: content.autoUpdate, lastUpdated: lastUpdated))
await reset()
await MainActor.run {
environments.profileUpdate.send()
dismiss()
}
}
}
#endif
@@ -7,21 +7,7 @@ import SwiftUI
public struct NewProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@State private var isSaving = false
@State private var profileName = ""
#if !os(tvOS)
@State private var profileType = ProfileType.local
#else
@State private var profileType = ProfileType.remote
#endif
@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?
@StateObject private var viewModel: NewProfileViewModel
public struct ImportRequest: Codable, Hashable {
public let name: String
@@ -29,20 +15,16 @@ public struct NewProfileView: View {
}
public init(_ importRequest: ImportRequest? = nil) {
if let importRequest {
_profileName = .init(initialValue: importRequest.name)
_profileType = .init(initialValue: .remote)
_remotePath = .init(initialValue: importRequest.url)
}
_viewModel = StateObject(wrappedValue: NewProfileViewModel(importRequest: importRequest))
}
public var body: some View {
FormView {
FormItem(String(localized: "Name")) {
TextField("Name", text: $profileName, prompt: Text("Required"))
TextField("Name", text: $viewModel.profileName, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
Picker(selection: $profileType) {
Picker(selection: $viewModel.profileType) {
#if !os(tvOS)
Text("Local").tag(ProfileType.local)
Text("iCloud").tag(ProfileType.icloud)
@@ -51,8 +33,8 @@ public struct NewProfileView: View {
} label: {
Text("Type")
}
if profileType == .local {
Picker(selection: $fileImport) {
if viewModel.profileType == .local {
Picker(selection: $viewModel.fileImport) {
Text("Create New").tag(false)
Text("Import").tag(true)
} label: {
@@ -62,42 +44,42 @@ public struct NewProfileView: View {
.disabled(true)
#endif
viewBuilder {
if fileImport {
if viewModel.fileImport {
HStack {
Text("File Path")
Spacer()
Spacer()
if let fileURL {
if let fileURL = viewModel.fileURL {
Button(fileURL.fileName) {
pickerPresented = true
viewModel.pickerPresented = true
}
} else {
Button("Choose") {
pickerPresented = true
viewModel.pickerPresented = true
}
}
}
}
}
} else if profileType == .icloud {
} else if viewModel.profileType == .icloud {
FormItem(String(localized: "Path")) {
TextField("Path", text: $remotePath, prompt: Text("Required"))
TextField("Path", text: $viewModel.remotePath, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
#if !os(macOS)
.keyboardType(.asciiCapableNumberPad)
#endif
}
} else if profileType == .remote {
} else if viewModel.profileType == .remote {
FormItem(String(localized: "URL")) {
TextField("URL", text: $remotePath, prompt: Text("Required"))
TextField("URL", text: $viewModel.remotePath, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
#if !os(macOS)
.keyboardType(.URL)
#endif
}
Toggle("Auto Update", isOn: $autoUpdate)
Toggle("Auto Update", isOn: $viewModel.autoUpdate)
FormItem(String(localized: "Auto Update Interval")) {
TextField("Auto Update Interval", text: $autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
TextField("Auto Update Interval", text: $viewModel.autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
.multilineTextAlignment(.trailing)
#if !os(macOS)
.keyboardType(.numberPad)
@@ -105,11 +87,11 @@ public struct NewProfileView: View {
}
}
Section {
if !isSaving {
if !viewModel.isSaving {
FormButton {
isSaving = true
viewModel.isSaving = true
Task {
await createProfile()
await viewModel.createProfile(environments: environments, dismiss: dismiss)
}
} label: {
Label("Create", systemImage: "doc.fill.badge.plus")
@@ -120,143 +102,23 @@ public struct NewProfileView: View {
}
}
.navigationTitle("New Profile")
.alertBinding($alert)
.alertBinding($viewModel.alert)
#if os(iOS) || os(macOS)
.fileImporter(
isPresented: $pickerPresented,
isPresented: $viewModel.pickerPresented,
allowedContentTypes: [.json],
allowsMultipleSelection: false
) { result in
do {
let urls = try result.get()
if !urls.isEmpty {
fileURL = urls[0]
viewModel.fileURL = urls[0]
}
} catch {
alert = Alert(error)
viewModel.alert = Alert(error)
return
}
}
#endif
}
private func createProfile() async {
defer {
isSaving = false
}
if profileName.isEmpty {
alert = Alert(errorMessage: String(localized: "Missing profile name"))
return
}
if remotePath.isEmpty {
if profileType == .icloud {
alert = Alert(errorMessage: String(localized: "Missing path"))
return
} else if profileType == .remote {
alert = Alert(errorMessage: String(localized: "Missing URL"))
return
}
}
do {
try await createProfileBackground()
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
#if os(macOS)
resetFields()
#endif
}
private func resetFields() {
profileName = ""
profileType = .local
fileImport = false
fileURL = nil
remotePath = ""
}
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 {
throw NSError(domain: "Missing file", code: 0)
}
if !fileURL.startAccessingSecurityScopedResource() {
throw NSError(domain: "Missing access to selected file", code: 0)
}
defer {
fileURL.stopAccessingSecurityScopedResource()
}
try String(contentsOf: fileURL).write(to: profileConfig, atomically: true, encoding: .utf8)
} else {
try "{}".write(to: profileConfig, atomically: true, encoding: .utf8)
}
savePath = profileConfig.relativePath
} else if profileType == .icloud {
if !FileManager.default.fileExists(atPath: FilePath.iCloudDirectory.path) {
try FileManager.default.createDirectory(at: FilePath.iCloudDirectory, withIntermediateDirectories: true)
}
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(remotePath, isDirectory: false)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
do {
_ = try String(contentsOf: saveURL)
} catch {
try "{}".write(to: saveURL, atomically: true, encoding: .utf8)
}
savePath = remotePath
} else if profileType == .remote {
let remoteContent = try HTTPClient().getString(remotePath)
var error: NSError?
LibboxCheckConfig(remoteContent, &error)
if let error {
throw error
}
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
try remoteContent.write(to: profileConfig, atomically: true, encoding: .utf8)
savePath = profileConfig.relativePath
remoteURL = remotePath
lastUpdated = .now
}
try await ProfileManager.create(Profile(
name: profileName,
type: profileType,
path: savePath,
remoteURL: remoteURL,
autoUpdate: autoUpdate,
autoUpdateInterval: autoUpdateInterval,
lastUpdated: lastUpdated
))
if profileType == .remote {
#if os(iOS) || os(tvOS)
try UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
}
}
}
@@ -0,0 +1,150 @@
import Foundation
import Libbox
import Library
import SwiftUI
@MainActor
public final class NewProfileViewModel: ObservableObject {
@Published public var isSaving = false
@Published public var profileName = ""
#if !os(tvOS)
@Published public var profileType = ProfileType.local
#else
@Published public var profileType = ProfileType.remote
#endif
@Published public var fileImport = false
@Published public var fileURL: URL?
@Published public var remotePath = ""
@Published public var autoUpdate = true
@Published public var autoUpdateInterval: Int32 = 60
@Published public var pickerPresented = false
@Published public var alert: Alert?
public init(importRequest: NewProfileView.ImportRequest? = nil) {
if let importRequest {
profileName = importRequest.name
profileType = .remote
remotePath = importRequest.url
}
}
public func resetFields() {
profileName = ""
profileType = .local
fileImport = false
fileURL = nil
remotePath = ""
}
public func createProfile(environments: ExtensionEnvironments, dismiss: DismissAction) async {
defer {
isSaving = false
}
if profileName.isEmpty {
alert = Alert(errorMessage: String(localized: "Missing profile name"))
return
}
if remotePath.isEmpty {
if profileType == .icloud {
alert = Alert(errorMessage: String(localized: "Missing path"))
return
} else if profileType == .remote {
alert = Alert(errorMessage: String(localized: "Missing URL"))
return
}
}
do {
try await createProfileBackground()
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
#if os(macOS)
resetFields()
#endif
}
private nonisolated func createProfileBackground() async throws {
let nextProfileID = try await ProfileManager.nextID()
var savePath = ""
var remoteURL: String?
var lastUpdated: Date?
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 {
throw NSError(domain: "Missing file", code: 0)
}
if !fileURL.startAccessingSecurityScopedResource() {
throw NSError(domain: "Missing access to selected file", code: 0)
}
defer {
fileURL.stopAccessingSecurityScopedResource()
}
try String(contentsOf: fileURL).write(to: profileConfig, atomically: true, encoding: .utf8)
} else {
try "{}".write(to: profileConfig, atomically: true, encoding: .utf8)
}
savePath = profileConfig.relativePath
} else if profileType == .icloud {
if !FileManager.default.fileExists(atPath: FilePath.iCloudDirectory.path) {
try FileManager.default.createDirectory(at: FilePath.iCloudDirectory, withIntermediateDirectories: true)
}
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(remotePath, isDirectory: false)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
do {
_ = try String(contentsOf: saveURL)
} catch {
try "{}".write(to: saveURL, atomically: true, encoding: .utf8)
}
savePath = remotePath
} else if profileType == .remote {
let remoteContent = try HTTPClient().getString(remotePath)
var error: NSError?
LibboxCheckConfig(remoteContent, &error)
if let error {
throw error
}
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
try remoteContent.write(to: profileConfig, atomically: true, encoding: .utf8)
savePath = profileConfig.relativePath
remoteURL = remotePath
lastUpdated = .now
}
try await ProfileManager.create(Profile(
name: profileName,
type: profileType,
path: savePath,
remoteURL: remoteURL,
autoUpdate: autoUpdate,
autoUpdateInterval: autoUpdateInterval,
lastUpdated: lastUpdated
))
if profileType == .remote {
#if os(iOS) || os(tvOS)
try UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
}
}
}
@@ -10,18 +10,7 @@ public struct ProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.importProfile) private var importProfile
@Environment(\.importRemoteProfile) private var importRemoteProfile
@State private var importRemoteProfileRequest: NewProfileView.ImportRequest?
@State private var importRemoteProfilePresented = false
@State private var isLoading = true
@State private var isUpdating = false
@State private var alert: Alert?
@State private var profileList: [ProfilePreview] = []
#if os(iOS) || os(tvOS)
@State private var editMode = EditMode.inactive
#endif
@StateObject private var viewModel = ProfileViewModel()
#if os(tvOS)
@Environment(\.devicePickerSupports) private var devicePickerSupports
@@ -30,16 +19,17 @@ public struct ProfileView: View {
public init() {}
public var body: some View {
VStack {
if isLoading {
if viewModel.isLoading {
ProgressView().onAppear {
viewModel.setEnvironments(environments)
Task {
await doReload()
await viewModel.doReload()
}
}
} else {
ZStack {
if let importRemoteProfileRequest {
NavigationDestinationCompat(isPresented: $importRemoteProfilePresented) {
if let importRemoteProfileRequest = viewModel.importRemoteProfileRequest {
NavigationDestinationCompat(isPresented: $viewModel.importRemoteProfilePresented) {
NewProfileView(importRemoteProfileRequest)
}
}
@@ -50,7 +40,7 @@ public struct ProfileView: View {
} label: {
Text("New Profile").foregroundColor(.accentColor)
}
.disabled(editMode.isEditing)
.disabled(viewModel.editMode.isEditing)
#elseif os(macOS)
FormNavigationLink {
NewProfileView()
@@ -73,20 +63,20 @@ public struct ProfileView: View {
}
}
#endif
if profileList.isEmpty {
if viewModel.profileList.isEmpty {
Text("Empty profiles")
} else {
List {
ForEach(profileList, id: \.id) { profile in
ForEach(viewModel.profileList, id: \.id) { profile in
viewBuilder {
#if os(iOS) || os(tvOS)
if editMode.isEditing == true {
if viewModel.editMode.isEditing == true {
Text(profile.name)
} else {
ProfileItem(self, profile)
ProfileItem(viewModel, profile)
}
#else
ProfileItem(self, profile)
ProfileItem(viewModel, profile)
#endif
}
}
@@ -98,55 +88,55 @@ public struct ProfileView: View {
}
}
}
.disabled(isUpdating)
.alertBinding($alert, $isLoading)
.disabled(viewModel.isUpdating)
.alertBinding($viewModel.alert, $viewModel.isLoading)
.onAppear {
if let profile = importProfile.wrappedValue {
importProfile.wrappedValue = nil
createImportProfileDialog(profile)
viewModel.createImportProfileDialog(profile)
}
if let remoteProfile = importRemoteProfile.wrappedValue {
importRemoteProfile.wrappedValue = nil
createImportRemoteProfileDialog(remoteProfile)
viewModel.createImportRemoteProfileDialog(remoteProfile)
}
}
.onChangeCompat(of: importProfile.wrappedValue) { newValue in
if let newValue {
importProfile.wrappedValue = nil
createImportProfileDialog(newValue)
viewModel.createImportProfileDialog(newValue)
}
}
.onChangeCompat(of: importRemoteProfile.wrappedValue) { newValue in
if let newValue {
importRemoteProfile.wrappedValue = nil
createImportRemoteProfileDialog(newValue)
viewModel.createImportRemoteProfileDialog(newValue)
}
}
.onReceive(environments.profileUpdate) { _ in
Task {
await doReload()
await viewModel.doReload()
}
}
#if os(iOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton().disabled(profileList.isEmpty && !editMode.isEditing)
EditButton().disabled(viewModel.profileList.isEmpty && !viewModel.editMode.isEditing)
}
}
#elseif os(tvOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if editMode == .inactive {
if viewModel.editMode == .inactive {
Button(action: {
editMode = .active
viewModel.editMode = .active
}) {
Image(systemName: "square.and.pencil")
}
.tint(.accentColor)
.disabled(profileList.isEmpty)
.disabled(viewModel.profileList.isEmpty)
} else {
Button(action: {
editMode = .inactive
viewModel.editMode = .inactive
}) {
Image(systemName: "checkmark.square.fill")
}
@@ -156,126 +146,27 @@ public struct ProfileView: View {
}
#endif
#if os(iOS) || os(tvOS)
.environment(\.editMode, $editMode)
.environment(\.editMode, $viewModel.editMode)
#endif
}
private func createImportProfileDialog(_ profile: LibboxProfileContent) {
alert = Alert(
title: Text("Import Profile"),
message: Text("Are you sure to import profile \(profile.name)?"),
primaryButton: .default(Text("Import")) {
Task {
do {
try await profile.importProfile()
} catch {
alert = Alert(error)
return
}
await doReload()
}
},
secondaryButton: .cancel()
)
}
private func createImportRemoteProfileDialog(_ newValue: LibboxImportRemoteProfile) {
importRemoteProfileRequest = .init(name: newValue.name, url: newValue.url)
alert = Alert(
title: Text("Import Remote Profile"),
message: Text("Are you sure to import remote profile \(newValue.name)? You will connect to \(newValue.host) to download the configuration."),
primaryButton: .default(Text("Import")) {
importRemoteProfilePresented = true
},
secondaryButton: .cancel()
)
}
private func doReload() async {
defer {
isLoading = false
}
if ApplicationLibrary.inPreview {
profileList = [
ProfilePreview(Profile(id: 0, name: "profile local", type: .local, path: "")),
ProfilePreview(Profile(id: 1, name: "profile remote", type: .remote, path: "", lastUpdated: Date(timeIntervalSince1970: 0))),
]
} else {
do {
profileList = try await ProfileManager.list().map { ProfilePreview($0) }
} catch {
alert = Alert(error)
return
}
}
environments.emptyProfiles = profileList.isEmpty
}
private func updateProfile(_ profile: Profile) async {
await updateProfileBackground(profile)
isUpdating = false
}
private nonisolated func updateProfileBackground(_ profile: Profile) async {
do {
_ = 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
}
environments.profileUpdate.send()
}
private func moveProfile(from source: IndexSet, to destination: Int) {
profileList.move(fromOffsets: source, toOffset: destination)
for (index, profile) in profileList.enumerated() {
profileList[index].order = UInt32(index)
profile.origin.order = UInt32(index)
}
Task {
do {
try await ProfileManager.update(profileList.map(\.origin))
} catch {
alert = Alert(error)
}
environments.profileUpdate.send()
}
viewModel.moveProfile(from: source, to: destination)
}
private func deleteProfile(where profileIndex: IndexSet) {
let profileToDelete = profileIndex.map { index in
profileList[index].origin
}
profileList.remove(atOffsets: profileIndex)
environments.emptyProfiles = profileList.isEmpty
Task {
do {
_ = try await ProfileManager.delete(profileToDelete)
} catch {
alert = Alert(error)
}
environments.profileUpdate.send()
}
viewModel.deleteProfile(where: profileIndex)
}
@MainActor
public struct ProfileItem: View {
private let parent: ProfileView
@EnvironmentObject private var environments: ExtensionEnvironments
@ObservedObject private var viewModel: ProfileViewModel
@State private var profile: ProfilePreview
@State private var shareLinkPresented = false
public init(_ parent: ProfileView, _ profile: ProfilePreview) {
self.parent = parent
public init(_ viewModel: ProfileViewModel, _ profile: ProfilePreview) {
self.viewModel = viewModel
_profile = State(initialValue: profile)
}
@@ -303,7 +194,7 @@ public struct ProfileView: View {
shareLinkView.padding()
}
.contextMenu {
ProfileShareButton(parent.$alert, profile.origin) {
ProfileShareButton($viewModel.alert, profile.origin) {
Label("Share", systemImage: "square.and.arrow.up.fill")
}
@@ -314,9 +205,9 @@ public struct ProfileView: View {
Label("Share URL as QR Code", systemImage: "qrcode")
}
Button {
parent.isUpdating = true
viewModel.isUpdating = true
Task {
await parent.updateProfile(profile.origin)
await viewModel.updateProfile(profile.origin)
profile = ProfilePreview(profile.origin)
}
} label: {
@@ -325,7 +216,7 @@ public struct ProfileView: View {
}
Button(role: .destructive) {
Task {
await parent.deleteProfile(profile.origin)
await viewModel.deleteProfile(profile.origin)
}
} label: {
Label("Delete", systemImage: "trash.fill")
@@ -346,9 +237,9 @@ public struct ProfileView: View {
HStack {
if profile.type == .remote {
Button {
parent.isUpdating = true
viewModel.isUpdating = true
Task {
await parent.updateProfile(profile.origin)
await viewModel.updateProfile(profile.origin)
profile = ProfilePreview(profile.origin)
}
} label: {
@@ -366,13 +257,13 @@ public struct ProfileView: View {
shareLinkView
}
}
ProfileShareButton(parent.$alert, profile.origin) {
ProfileShareButton($viewModel.alert, profile.origin) {
Image(systemName: "square.and.arrow.up.fill")
}
.padding(.leading, 4)
Button {
Task {
await parent.deleteProfile(profile.origin)
await viewModel.deleteProfile(profile.origin)
}
} label: {
Image(systemName: "trash.fill")
@@ -0,0 +1,135 @@
import Foundation
import Libbox
import Library
import SwiftUI
@MainActor
public class ProfileViewModel: ObservableObject {
@Published public var importRemoteProfileRequest: NewProfileView.ImportRequest?
@Published public var importRemoteProfilePresented = false
@Published public var isLoading = true
@Published public var isUpdating = false
@Published public var alert: Alert?
@Published public var profileList: [ProfilePreview] = []
#if os(iOS) || os(tvOS)
@Published public var editMode = EditMode.inactive
#endif
private weak var environments: ExtensionEnvironments?
public init() {}
public func setEnvironments(_ environments: ExtensionEnvironments) {
self.environments = environments
}
public func createImportProfileDialog(_ profile: LibboxProfileContent) {
alert = Alert(
title: Text("Import Profile"),
message: Text("Are you sure to import profile \(profile.name)?"),
primaryButton: .default(Text("Import")) {
Task {
do {
try await profile.importProfile()
} catch {
self.alert = Alert(error)
return
}
await self.doReload()
self.environments?.emptyProfiles = self.profileList.isEmpty
}
},
secondaryButton: .cancel()
)
}
public func createImportRemoteProfileDialog(_ newValue: LibboxImportRemoteProfile) {
importRemoteProfileRequest = .init(name: newValue.name, url: newValue.url)
alert = Alert(
title: Text("Import Remote Profile"),
message: Text("Are you sure to import remote profile \(newValue.name)? You will connect to \(newValue.host) to download the configuration."),
primaryButton: .default(Text("Import")) {
self.importRemoteProfilePresented = true
},
secondaryButton: .cancel()
)
}
public func doReload() async {
defer {
isLoading = false
}
if ApplicationLibrary.inPreview {
profileList = [
ProfilePreview(Profile(id: 0, name: "profile local", type: .local, path: "")),
ProfilePreview(Profile(id: 1, name: "profile remote", type: .remote, path: "", lastUpdated: Date(timeIntervalSince1970: 0))),
]
} else {
do {
profileList = try await ProfileManager.list().map { ProfilePreview($0) }
} catch {
alert = Alert(error)
return
}
}
environments?.emptyProfiles = profileList.isEmpty
}
public func updateProfile(_ profile: Profile) async {
await updateProfileBackground(profile)
isUpdating = false
}
private nonisolated func updateProfileBackground(_ profile: Profile) async {
do {
_ = try await profile.updateRemoteProfile()
} catch {
await MainActor.run {
alert = Alert(error)
}
}
}
public func deleteProfile(_ profile: Profile) async {
do {
_ = try await ProfileManager.delete(profile)
environments?.profileUpdate.send()
environments?.emptyProfiles = profileList.isEmpty
} catch {
alert = Alert(error)
}
}
public func moveProfile(from source: IndexSet, to destination: Int) {
profileList.move(fromOffsets: source, toOffset: destination)
for (index, profile) in profileList.enumerated() {
profileList[index].order = UInt32(index)
profile.origin.order = UInt32(index)
}
Task {
do {
try await ProfileManager.update(profileList.map(\.origin))
environments?.profileUpdate.send()
} catch {
alert = Alert(error)
}
}
}
public func deleteProfile(where profileIndex: IndexSet) {
let profileToDelete = profileIndex.map { index in
profileList[index].origin
}
profileList.remove(atOffsets: profileIndex)
Task {
do {
_ = try await ProfileManager.delete(profileToDelete)
environments?.emptyProfiles = profileList.isEmpty
environments?.profileUpdate.send()
} catch {
alert = Alert(error)
}
}
}
}