oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import Observation
3import EquipoShareCore
4
5@MainActor @Observable public final class AttachmentDraft {
6 public struct Item: Identifiable, Sendable {
7 public enum State: Sendable { case uploading(Double), ready(MessageAttachment), failed(String) }
8 public let id: UUID
9 public let name: String
10 public var state: State
11 public var file: AttachmentFile?
12 var generation = UUID()
13 var source: Source
14 public var failure: String? { if case .failed(let words) = state { return words }; return nil }
15 }
16 enum Source: Sendable { case data(Data), file(URL), load(@Sendable () async throws -> Data) }
17 public private(set) var items: [Item] = []
18 public private(set) var notice: String?
19 @ObservationIgnored private var uploads: [UUID: (generation: UUID, task: Task<Void, Never>)] = [:]
20 @ObservationIgnored private var stagedDirectories: [UUID: URL] = [:]
21 deinit { for directory in stagedDirectories.values { try? FileManager.default.removeItem(at: directory) } }
22 @ObservationIgnored var fileAccess: any AttachmentFileAccess = SystemAttachmentFileAccess()
23 var client: EquipoClient
24 public init(client: EquipoClient) { self.client = client }
25
26 public var readyAttachments: [MessageAttachment] { items.compactMap { if case .ready(let value) = $0.state { return value }; return nil } }
27 public func canSend(text: String) -> Bool {
28 items.allSatisfy { if case .ready = $0.state { return true }; return false } && (!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !items.isEmpty)
29 }
30 public func add(data: Data, name: String) async { await add(.data(data), name: name) }
31 public func add(name: String, load: @escaping @Sendable () async throws -> Data) async { await add(.load(load), name: name) }
32 public func refuseFile() { notice = AttachmentFailure.type.words }
33 public func add(url: URL) async {
34 do { try AttachmentFile.checkRegularFile(url, access: fileAccess) }
35 catch { refuseFile(); return }
36 await add(.file(url), name: url.lastPathComponent)
37 }
38 /// Takes ownership of this private staging directory, including on refusal.
39 public func add(staged file: FileAttachment, directory: URL) async {
40 await add(.file(file.url), name: file.name, ownedDirectory: directory)
41 }
42 private func add(_ source: Source, name: String, ownedDirectory: URL? = nil) async {
43 guard items.count < AttachmentLimits.maxCount else {
44 if let ownedDirectory { try? FileManager.default.removeItem(at: ownedDirectory) }
45 notice = EquipoStrings.text("chat.attach.too_many"); return
46 }
47 notice = nil
48 let id = UUID()
49 stagedDirectories[id] = ownedDirectory
50 items.append(Item(id: id, name: name, state: .uploading(0), source: source))
51 await upload(id)
52 }
53 public func remove(_ id: UUID) { uploads.removeValue(forKey: id)?.task.cancel(); items.removeAll { $0.id == id }; cleanStaged(id); notice = nil }
54 public func clear() { for upload in uploads.values { upload.task.cancel() }; uploads = [:]; items = []; for id in Array(stagedDirectories.keys) { cleanStaged(id) }; notice = nil }
55 private func cleanStaged(_ id: UUID) { if let directory = stagedDirectories.removeValue(forKey: id) { try? FileManager.default.removeItem(at: directory) } }
56 public func retry(_ id: UUID) async {
57 guard let i = items.firstIndex(where: { $0.id == id }), items[i].failure != nil else { return }
58 items[i].generation = UUID(); items[i].state = .uploading(0)
59 await upload(id)
60 }
61 private func upload(_ id: UUID) async {
62 guard let generation = items.first(where: { $0.id == id })?.generation else { return }
63 let task = Task { await performUpload(id) }
64 uploads[id] = (generation, task)
65 await withTaskCancellationHandler { await task.value } onCancel: { task.cancel() }
66 if uploads[id]?.generation == generation { uploads[id] = nil }
67 }
68 private func performUpload(_ id: UUID) async {
69 guard let item = items.first(where: { $0.id == id }) else { return }
70 do {
71 let file = try await Task.detached {
72 let bytes: Data
73 switch item.source { case .data(let data): bytes = data; case .file(let url): bytes = try AttachmentFile.read(url); case .load(let load): bytes = try await load() }
74 return try AttachmentFile.prepare(bytes, name: item.name)
75 }.value
76 try Task.checkCancellation()
77 guard let i = index(id, item.generation) else { return }
78 items[i].file = file
79 let attachment = try await client.upload(file) { [weak self] fraction in
80 Task { @MainActor [weak self] in
81 guard let self, let i = self.index(id, item.generation), case .uploading = self.items[i].state else { return }
82 self.items[i].state = .uploading(fraction)
83 }
84 }
85 guard let i = index(id, item.generation) else { return }
86 items[i].state = .ready(attachment)
87 } catch {
88 guard let i = index(id, item.generation) else { return }
89 let words: String
90 if let failure = error as? AttachmentFailure { words = failure.words }
91 else if let error = error as? EquipoAPIError, let code = error.code,
92 ["attachment_too_large", "attachment_pixels", "attachment_type", "attachment_heic", "attachment_limit"].contains(code) {
93 words = EquipoStrings.text(String.LocalizationValue("api." + code))
94 }
95 else { words = EquipoStrings.text("chat.attach.failed") }
96 items[i].state = .failed(words)
97 }
98 }
99 private func index(_ id: UUID, _ generation: UUID) -> Int? { items.firstIndex { $0.id == id && $0.generation == generation } }
100}
101