-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathSystemManager.swift
More file actions
251 lines (228 loc) · 8.76 KB
/
SystemManager.swift
File metadata and controls
251 lines (228 loc) · 8.76 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import Foundation
import PowerSync
func getAttachmentsDirectoryPath() throws -> String {
guard let documentsURL = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first else {
throw PowerSyncAttachmentError.invalidPath("Could not determine attachments directory path")
}
return documentsURL.appendingPathComponent("attachments").path
}
let logTag = "SystemManager"
@MainActor
@Observable
class SystemManager {
let connector = SupabaseConnector()
let schema = AppSchema
let db: PowerSyncDatabaseProtocol
var attachments: AttachmentQueue?
init() {
db = PowerSyncDatabase(
schema: schema,
dbFilename: "powersync-swift.sqlite"
)
attachments = Self.createAttachmentQueue(
db: db,
connector: connector
)
}
/// Creates an AttachmentQueue if a Supabase Storage bucket has been specified in the config
private static func createAttachmentQueue(
db: PowerSyncDatabaseProtocol,
connector: SupabaseConnector
) -> AttachmentQueue? {
guard let bucket = connector.getStorageBucket() else {
db.logger.info("No Supabase Storage bucket specified. Skipping attachment queue setup.", tag: logTag)
return nil
}
do {
let attachmentsDir = try getAttachmentsDirectoryPath()
return AttachmentQueue(
db: db,
remoteStorage: SupabaseRemoteStorage(storage: bucket),
attachmentsDirectory: attachmentsDir,
watchAttachments: { try db.watch(
options: WatchOptions(
sql: "SELECT photo_id FROM \(TODOS_TABLE) WHERE photo_id IS NOT NULL",
parameters: [],
mapper: { cursor in
try WatchedAttachmentItem(
id: cursor.getString(name: "photo_id"),
fileExtension: "jpg"
)
}
)
) }
)
} catch {
db.logger.error("Failed to initialize attachments queue: \(error)", tag: logTag)
return nil
}
}
func connect() async {
do {
try await db.connect(
connector: connector,
options: ConnectOptions(
clientConfiguration: SyncClientConfiguration(
requestLogger: SyncRequestLoggerConfiguration(
requestLevel: .headers
) { message in
self.db.logger.debug(message, tag: "SyncRequest")
}
)
)
)
try await attachments?.startSync()
} catch {
print("Unexpected error: \(error.localizedDescription)") // Catches any other error
}
}
func version() async -> String {
do {
return try await db.getPowerSyncVersion()
} catch {
return error.localizedDescription
}
}
func signOut() async throws {
try await db.disconnectAndClear()
try await connector.client.auth.signOut()
try await attachments?.stopSyncing()
try await attachments?.clearQueue()
}
func watchLists(_ callback: @escaping (_ lists: [ListContent]) -> Void) async {
do {
for try await lists in try db.watch(
options: WatchOptions(
sql: "SELECT * FROM \(LISTS_TABLE)",
mapper: { cursor in
try ListContent(
id: cursor.getString(name: "id"),
name: cursor.getString(name: "name"),
createdAt: cursor.getString(name: "created_at"),
ownerId: cursor.getString(name: "owner_id")
)
}
)
) {
callback(lists)
}
} catch {
print("Error in watch: \(error)")
}
}
func insertList(_ list: NewListContent) async throws {
_ = try await db.execute(
sql: "INSERT INTO \(LISTS_TABLE) (id, created_at, name, owner_id) VALUES (uuid(), datetime(), ?, ?)",
parameters: [list.name, connector.currentUserID]
)
}
func deleteList(id: String) async throws {
let attachmentIds = try await db.writeTransaction(callback: { transaction in
let attachmentIDs = try transaction.getAll(
sql: "SELECT photo_id FROM \(TODOS_TABLE) WHERE list_id = ? AND photo_id IS NOT NULL",
parameters: [id]
) { cursor in
try cursor.getString(index: 0)
}
_ = try transaction.execute(
sql: "DELETE FROM \(LISTS_TABLE) WHERE id = ?",
parameters: [id]
)
_ = try transaction.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE list_id = ?",
parameters: [id]
)
return attachmentIDs
})
if let attachments {
for id in attachmentIds {
try await attachments.deleteFile(
attachmentId: id
) { _, _ in }
}
}
}
func watchTodos(_ listId: String, _ callback: @escaping (_ todos: [Todo]) -> Void) async {
do {
for try await todos in try db.watch(
sql: """
SELECT
t.*, a.local_uri
FROM
\(TODOS_TABLE) t
LEFT JOIN attachments a ON t.photo_id = a.id
WHERE
t.list_id = ?
ORDER BY t.id;
""",
parameters: [listId],
mapper: { cursor in
try Todo(
id: cursor.getString(name: "id"),
listId: cursor.getString(name: "list_id"),
photoId: cursor.getStringOptional(name: "photo_id"),
description: cursor.getString(name: "description"),
isComplete: cursor.getBoolean(name: "completed"),
createdAt: cursor.getString(name: "created_at"),
completedAt: cursor.getStringOptional(name: "completed_at"),
createdBy: cursor.getStringOptional(name: "created_by"),
completedBy: cursor.getStringOptional(name: "completed_by"),
photoUri: cursor.getStringOptional(name: "local_uri")
)
}
) {
callback(todos)
}
} catch {
print("Error in watch: \(error)")
}
}
func insertTodo(_ todo: NewTodo, _ listId: String) async throws {
_ = try await db.execute(
sql: "INSERT INTO \(TODOS_TABLE) (id, created_at, created_by, description, list_id, completed) VALUES (uuid(), datetime(), ?, ?, ?, ?)",
parameters: [connector.currentUserID, todo.description, listId, todo.isComplete]
)
}
func updateTodo(_ todo: Todo) async throws {
// Do this to avoid needing to handle date time from Swift to Kotlin
if todo.isComplete {
_ = try await db.execute(
sql: "UPDATE \(TODOS_TABLE) SET description = ?, completed = ?, completed_at = datetime(), completed_by = ? WHERE id = ?",
parameters: [todo.description, todo.isComplete, connector.currentUserID, todo.id]
)
} else {
_ = try await db.execute(
sql: "UPDATE \(TODOS_TABLE) SET description = ?, completed = ?, completed_at = NULL, completed_by = NULL WHERE id = ?",
parameters: [todo.description, todo.isComplete, todo.id]
)
}
}
func deleteTodo(todo: Todo) async throws {
if let attachments, let photoId = todo.photoId {
try await attachments.deleteFile(
attachmentId: photoId
) { transaction, _ in
try self.deleteTodoInTX(
id: todo.id,
tx: transaction
)
}
} else {
try await db.writeTransaction { transaction in
try self.deleteTodoInTX(
id: todo.id,
tx: transaction
)
}
}
}
private nonisolated func deleteTodoInTX(id: String, tx: ConnectionContext) throws {
_ = try tx.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE id = ?",
parameters: [id]
)
}
}