This commit is contained in:
fmodf 2024-08-17 23:33:14 +02:00
parent e0c2146a6d
commit dcd275b279
3 changed files with 55 additions and 31 deletions

View file

@ -99,7 +99,10 @@ extension Client {
try await chat.send(message: msg)
}
func uploadFile(_ localPath: URL) async throws -> String {
func uploadFile(_ localPath: String) async throws -> String {
guard let localPath = URL(string: localPath) else {
throw ClientStoreError.invalidPath
}
guard let data = try? Data(contentsOf: localPath) else {
throw ClientStoreError.noData
}

View file

@ -6,4 +6,7 @@ enum ClientStoreError: Error {
case fileStoreError
case noData
case fileTooBig
case invalidContentType
case invalidPath
case invalidLocalName
}

View file

@ -68,8 +68,16 @@ extension ConversationStore {
func sendCaptured(_ data: Data, _ type: GalleryMediaType) async {
// save locally and make message
let messageId = UUID().uuidString
let localName: String
let msgType: AttachmentType
do {
let (localName, msgType) = try await FileStore.shared.storeCaptured(messageId: messageId, data, type)
(localName, msgType) = try await FileStore.shared.storeCaptured(messageId: messageId, data, type)
} catch {
logIt(.error, "Can't save file for uploading: \(error)")
return
}
// save message
let message = Message(
id: UUID().uuidString,
type: .chat,
@ -90,13 +98,15 @@ extension ConversationStore {
thread: nil,
oobUrl: nil
)
do {
try await message.save()
} catch {
logIt(.error, "Can't save file for uploading: \(error)")
logIt(.error, "Can't save message: \(error)")
return
}
// upload and save
upload(message: message)
await upload(message)
}
func sendDocuments(_ data: [Data], _ extensions: [String]) async {
@ -123,22 +133,30 @@ extension ConversationStore {
await sendMessage("geo:\(lat),\(lon)")
}
private func upload(message: Message) async {
let remotePath: String
private func upload(_ message: Message) async {
do {
remotePath = try await client.uploadFile(localPath)
try await message.setStatus(.pending)
var message = message
guard case .attachment(let attachment) = message.contentType else {
throw ClientStoreError.invalidContentType
}
guard let localName = attachment.localName else {
throw ClientStoreError.invalidLocalName
}
let remotePath = try await client.uploadFile(localName)
message.contentType = .attachment(
Attachment(
type: msgType,
localName: localName,
type: attachment.type,
localName: attachment.localName,
thumbnailName: nil,
remotePath: remotePath
)
)
try await message.save()
try await client.sendMessage(message)
try await message.setStatus(.sent)
} catch {
message.status = .error
try? await message.save()
try? await message.setStatus(.error)
}
}
}