-
Notifications
You must be signed in to change notification settings - Fork 0
/
AccountsView.swift
203 lines (182 loc) · 6.95 KB
/
AccountsView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//
// AccountsView.swift
// rasman
//
// Created by Lucas J. Chumley on 8/14/24.
//
import SwiftUI
import Combine
import SwiftData
struct AccountsView: View {
@Environment(\.modelContext) private var modelContext
@Query private var settings: [ServerSettings]
@State private var users: [User] = []
@State private var isLoading: Bool = false
@State private var errorMessage: String?
@State private var cancellable: AnyCancellable?
@State private var isAddUserPresented: Bool = false
@State private var isChangePasswordPresented: Bool = false
@State private var selectedUser: User?
@State private var isDeleteConfirmationPresented: Bool = false
@Binding var shouldRefreshAccounts: Bool
var body: some View {
VStack(alignment: .leading, spacing: 20) {
Text("Users")
.font(.largeTitle)
.padding(.bottom, 20)
if settings.isEmpty {
Text("Server settings must be configured to continue.")
.font(.headline)
.foregroundColor(.red)
} else {
if let errorMessage = errorMessage {
Text(errorMessage)
.font(.headline)
.foregroundColor(.red)
.padding()
}
if isLoading {
ProgressView("Loading Users...")
.padding()
} else {
List {
ForEach(users) { user in
HStack {
Text(user.screenName)
Spacer()
Button("Change Password") {
changePassword(user: user)
}
.buttonStyle(.bordered)
Button("Delete", role: .destructive) {
selectedUser = user
isDeleteConfirmationPresented.toggle()
}
}
.contextMenu {
Button("Delete", action: { deleteUser(user: user) })
}
}
}
.padding(.bottom, 20)
}
}
}
.padding()
.onAppear(perform: loadUsers)
.onChange(of: shouldRefreshAccounts) { newValue in
if newValue {
loadUsers()
shouldRefreshAccounts = false
}
}
.toolbar {
ToolbarItem(placement: .automatic) {
Button(action: {
isAddUserPresented.toggle()
}) {
Label("Add User", systemImage: "plus")
}
}
}
.sheet(isPresented: $isAddUserPresented) {
AddUserView(baseURL: settings.first?.baseURL ?? "", port: settings.first?.port ?? "", shouldRefreshAccounts: $shouldRefreshAccounts)
}
.sheet(isPresented: $isChangePasswordPresented) {
if let selectedUser = selectedUser {
ChangePasswordView(baseURL: settings.first?.baseURL ?? "", port: settings.first?.port ?? "", screenName: selectedUser.screenName)
}
}
.alert(isPresented: $isDeleteConfirmationPresented) {
Alert(
title: Text("Delete User"),
message: Text("Are you sure you want to delete the user \(selectedUser?.screenName ?? "")?"),
primaryButton: .destructive(Text("Delete")) {
if let user = selectedUser {
deleteUser(user: user)
}
},
secondaryButton: .cancel()
)
}
}
private func loadUsers() {
guard let settings = settings.first else { return }
let urlString = "\(settings.baseURL):\(settings.port)/user"
guard let url = URL(string: urlString) else {
errorMessage = "Invalid server URL."
return
}
isLoading = true
errorMessage = nil
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.tryMap { output in
guard let response = output.response as? HTTPURLResponse, response.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return output.data
}
.decode(type: [User].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { completion in
isLoading = false
switch completion {
case .finished:
break
case .failure(let error):
errorMessage = "Failed to load users: \(error.localizedDescription)"
}
}, receiveValue: { users in
self.users = users
})
}
private func deleteUser(user: User) {
guard let settings = settings.first else { return }
let urlString = "\(settings.baseURL):\(settings.port)/user"
guard let url = URL(string: urlString) else {
errorMessage = "Invalid server URL."
return
}
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONEncoder().encode(["screen_name": user.screenName])
cancellable = URLSession.shared.dataTaskPublisher(for: request)
.tryMap { output in
guard let response = output.response as? HTTPURLResponse, response.statusCode == 204 else {
throw URLError(.badServerResponse)
}
return output.data
}
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
loadUsers()
case .failure(let error):
errorMessage = "Failed to delete user: \(error.localizedDescription)"
}
}, receiveValue: { _ in })
}
private func deleteAllUsers() {
for user in users {
deleteUser(user: user)
}
}
private func changePassword(user: User) {
selectedUser = user
isChangePasswordPresented.toggle()
}
}
struct User: Identifiable, Codable {
var id: String
var screenName: String
enum CodingKeys: String, CodingKey {
case id
case screenName = "screen_name"
}
}
#Preview {
AccountsView(shouldRefreshAccounts: .constant(false))
.modelContainer(for: ServerSettings.self, inMemory: true)
}