285 lines
9.6 KiB
Swift
285 lines
9.6 KiB
Swift
import AVFoundation
|
|
import Combine
|
|
import Foundation
|
|
import GRDB
|
|
import Photos
|
|
|
|
@MainActor
|
|
final class ConversationStore: ObservableObject {
|
|
@Published private(set) var messages: [Message] = []
|
|
@Published var replyText = ""
|
|
|
|
private(set) var roster: Roster
|
|
private let client: Client
|
|
|
|
private var messagesCancellable: AnyCancellable?
|
|
|
|
init(roster: Roster, client: Client) {
|
|
self.client = client
|
|
self.roster = roster
|
|
subscribe()
|
|
}
|
|
}
|
|
|
|
extension ConversationStore {
|
|
func sendMessage(_ message: String) async {
|
|
var msg = Message.blank
|
|
msg.from = roster.bareJid
|
|
msg.to = roster.contactBareJid
|
|
msg.body = message
|
|
|
|
// store as pending on db, and send
|
|
do {
|
|
try await msg.save()
|
|
try await client.sendMessage(msg)
|
|
try await msg.setStatus(.sent)
|
|
} catch {
|
|
try? await msg.setStatus(.error)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension ConversationStore {
|
|
func sendMedia(_ items: [GalleryItem]) async {
|
|
for item in items {
|
|
Task {
|
|
var message = Message.blank
|
|
message.from = roster.bareJid
|
|
message.to = roster.contactBareJid
|
|
|
|
switch item.type {
|
|
case .photo:
|
|
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [item.id], options: nil).firstObject else { return }
|
|
guard let photo = try? await PHImageManager.default().getPhoto(for: asset) else { return }
|
|
guard let data = photo.jpegData(compressionQuality: 1.0) else { return }
|
|
let localName = "\(message.id)_\(UUID().uuidString).jpg"
|
|
let localUrl = Const.fileFolder.appendingPathComponent(localName)
|
|
try? data.write(to: localUrl)
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: .image,
|
|
localName: localName,
|
|
thumbnailName: nil,
|
|
remotePath: nil
|
|
)
|
|
)
|
|
try? await message.save()
|
|
|
|
case .video:
|
|
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [item.id], options: nil).firstObject else { return }
|
|
guard let video = try? await PHImageManager.default().getVideo(for: asset) else { return }
|
|
// swiftlint:disable:next force_cast
|
|
let assetURL = video as! AVURLAsset
|
|
let url = assetURL.url
|
|
let localName = "\(message.id)_\(UUID().uuidString).mov"
|
|
let localUrl = Const.fileFolder.appendingPathComponent(localName)
|
|
try? FileManager.default.copyItem(at: url, to: localUrl)
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: .video,
|
|
localName: localName,
|
|
thumbnailName: nil,
|
|
remotePath: nil
|
|
)
|
|
)
|
|
try? await message.save()
|
|
}
|
|
|
|
await upload(message)
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendCaptured(_ data: Data, _ type: GalleryMediaType) async {
|
|
// save locally and make message
|
|
var message = Message.blank
|
|
message.from = roster.bareJid
|
|
message.to = roster.contactBareJid
|
|
|
|
let localName: String
|
|
let msgType: AttachmentType
|
|
do {
|
|
(localName, msgType) = try await Task {
|
|
// local name
|
|
let fileId = UUID().uuidString
|
|
let localName: String
|
|
let msgType: AttachmentType
|
|
switch type {
|
|
case .photo:
|
|
localName = "\(message.id)_\(fileId).jpg"
|
|
msgType = .image
|
|
|
|
case .video:
|
|
localName = "\(message.id)_\(fileId).mov"
|
|
msgType = .video
|
|
}
|
|
|
|
// save
|
|
let localUrl = Const.fileFolder.appendingPathComponent(localName)
|
|
try data.write(to: localUrl)
|
|
return (localName, msgType)
|
|
}.value
|
|
} catch {
|
|
logIt(.error, "Can't save file for uploading: \(error)")
|
|
return
|
|
}
|
|
|
|
// save message
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: msgType,
|
|
localName: localName,
|
|
thumbnailName: nil,
|
|
remotePath: nil
|
|
)
|
|
)
|
|
do {
|
|
try await message.save()
|
|
} catch {
|
|
logIt(.error, "Can't save message: \(error)")
|
|
return
|
|
}
|
|
|
|
// upload and save
|
|
await upload(message)
|
|
}
|
|
|
|
func sendDocuments(_ data: [Data], _ extensions: [String]) async {
|
|
for (index, data) in data.enumerated() {
|
|
Task {
|
|
let newMessageId = UUID().uuidString
|
|
let fileId = UUID().uuidString
|
|
let localName = "\(newMessageId)_\(fileId).\(extensions[index])"
|
|
let localUrl = Const.fileFolder.appendingPathComponent(localName)
|
|
do {
|
|
try data.write(to: localUrl)
|
|
} catch {
|
|
print("FileProcessing: Error writing document: \(error)")
|
|
return
|
|
}
|
|
|
|
var message = Message.blank
|
|
message.from = roster.bareJid
|
|
message.to = roster.contactBareJid
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: localName.attachmentType,
|
|
localName: localName,
|
|
thumbnailName: nil,
|
|
remotePath: nil
|
|
)
|
|
)
|
|
do {
|
|
try await message.save()
|
|
await upload(message)
|
|
} catch {
|
|
print("FileProcessing: Error saving document: \(error)")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendContact(_ jidStr: String) async {
|
|
await sendMessage("contact:\(jidStr)")
|
|
}
|
|
|
|
func sendLocation(_ lat: Double, _ lon: Double) async {
|
|
await sendMessage("geo:\(lat),\(lon)")
|
|
}
|
|
|
|
private func upload(_ message: Message) async {
|
|
do {
|
|
try await message.setStatus(.pending)
|
|
var message = message
|
|
guard case .attachment(let attachment) = message.contentType else {
|
|
throw ClientStoreError.invalidContentType
|
|
}
|
|
guard let localName = attachment.localPath else {
|
|
throw ClientStoreError.invalidLocalName
|
|
}
|
|
let remotePath = try await client.uploadFile(localName)
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: attachment.type,
|
|
localName: attachment.localName,
|
|
thumbnailName: nil,
|
|
remotePath: remotePath
|
|
)
|
|
)
|
|
message.body = remotePath
|
|
message.oobUrl = remotePath
|
|
try await message.save()
|
|
try await client.sendMessage(message)
|
|
try await message.setStatus(.sent)
|
|
} catch {
|
|
try? await message.setStatus(.error)
|
|
}
|
|
}
|
|
|
|
func downloadAttachment(_ message: Message) async {
|
|
guard case .attachment(let attachment) = message.contentType else {
|
|
return
|
|
}
|
|
guard let remotePath = attachment.remotePath, let remoteUrl = URL(string: remotePath) else {
|
|
return
|
|
}
|
|
do {
|
|
let localName = "\(message.id)_\(UUID().uuidString).\(remoteUrl.lastPathComponent)"
|
|
let localUrl = Const.fileFolder.appendingPathComponent(localName)
|
|
|
|
// Download the file
|
|
let (tempUrl, _) = try await URLSession.shared.download(from: remoteUrl)
|
|
try FileManager.default.moveItem(at: tempUrl, to: localUrl)
|
|
|
|
var message = message
|
|
message.contentType = .attachment(
|
|
Attachment(
|
|
type: attachment.type,
|
|
localName: localName,
|
|
thumbnailName: attachment.thumbnailName,
|
|
remotePath: remotePath
|
|
)
|
|
)
|
|
try await message.save()
|
|
} catch {
|
|
logIt(.error, "Can't download attachment: \(error)")
|
|
}
|
|
}
|
|
}
|
|
|
|
extension ConversationStore {
|
|
var contacts: [Roster] {
|
|
get async {
|
|
do {
|
|
let rosters = try await Database.shared.dbQueue.read { db in
|
|
try Roster
|
|
.filter(Column("locallyDeleted") == false)
|
|
.fetchAll(db)
|
|
}
|
|
return rosters
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private extension ConversationStore {
|
|
func subscribe() {
|
|
messagesCancellable = ValueObservation.tracking(Message
|
|
.filter(
|
|
(Column("to") == roster.bareJid && Column("from") == roster.contactBareJid) ||
|
|
(Column("from") == roster.bareJid && Column("to") == roster.contactBareJid)
|
|
)
|
|
.order(Column("date").desc)
|
|
.fetchAll
|
|
)
|
|
.publisher(in: Database.shared.dbQueue, scheduling: .immediate)
|
|
.receive(on: DispatchQueue.main)
|
|
.sink { _ in
|
|
} receiveValue: { [weak self] messages in
|
|
self?.messages = messages
|
|
}
|
|
}
|
|
}
|