another.im-ios/ConversationsClassic/AppData/Store/AttachmentsStore.swift

186 lines
6.6 KiB
Swift
Raw Normal View History

2024-08-17 12:11:11 +00:00
import Combine
import Foundation
import Photos
2024-08-17 13:54:54 +00:00
import SwiftUI
2024-08-17 12:11:11 +00:00
@MainActor
2024-08-17 16:15:05 +00:00
final class AttachmentsStore: ObservableObject {
2024-08-18 09:17:58 +00:00
@Published private(set) var cameraAccessGranted = false
@Published private(set) var galleryAccessGranted = false
@Published private(set) var galleryItems: [GalleryItem] = []
2024-08-17 12:11:11 +00:00
2024-08-18 09:05:43 +00:00
private let client: Client
private let roster: Roster
init(roster: Roster, client: Client) {
self.client = client
self.roster = roster
}
2024-08-17 12:11:11 +00:00
}
2024-08-18 09:17:58 +00:00
// MARK: - Camera and Gallery access
2024-08-17 16:15:05 +00:00
extension AttachmentsStore {
2024-08-17 12:11:11 +00:00
func checkCameraAuthorization() async {
let status = AVCaptureDevice.authorizationStatus(for: .video)
var isAuthorized = status == .authorized
if status == .notDetermined {
isAuthorized = await AVCaptureDevice.requestAccess(for: .video)
}
cameraAccessGranted = isAuthorized
}
func checkGalleryAuthorization() async {
let status = PHPhotoLibrary.authorizationStatus()
var isAuthorized = status == .authorized
if status == .notDetermined {
let req = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
isAuthorized = (req == .authorized) || (req == .limited)
}
galleryAccessGranted = isAuthorized
}
2024-08-17 13:54:54 +00:00
func fetchGalleryItems() async {
guard galleryAccessGranted else { return }
galleryItems = await GalleryItem.fetchAll()
}
2024-08-17 12:11:11 +00:00
}
2024-08-18 09:17:58 +00:00
// MARK: - Save outgoing attachments for future uploadings
extension AttachmentsStore {
func sendMedia(_ items: [GalleryItem]) async {
galleryItems = []
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()
}
}
}
}
func sendCaptured(_ data: Data, _ type: GalleryMediaType) async {
galleryItems = []
// 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
}
}
func sendDocuments(_ data: [Data], _ extensions: [String]) async {
galleryItems = []
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()
} catch {
print("FileProcessing: Error saving document: \(error)")
}
}
}
}
}