// What Cotton Chat's screens ask of the core: `chat.list`, `chat.thread`, // `chat.compose`, `chat.act` (chat-new-core, on main since 5d2753a3f) and // `chat.picture`, `chat.themes` and Settings' `chat.theme`, `chat.text` // and `chat.ground`; what `chat.act` queues is sent by the chat engine, // which holds this phone's chat key. #if os(iOS) import CottonKit import Foundation import Observation import UIKit protocol ChatBook: Sendable { func list(_ ask: ChatListAsk) async throws -> ChatListAnswer func thread(_ ask: ChatThreadAsk) async throws -> ChatThreadAnswer func compose(_ ask: ChatComposeAsk) async throws -> ChatComposeAnswer func act(_ ask: ChatActAsk) async throws -> ChatActAnswer /// Accept, block or refuse a stranger's request (`chat.accept` …). func decide(_ thread: String, _ method: String) async throws func themes() async throws -> ChatThemesAnswer func choose(theme: String, dark: Bool) async throws -> ChatThemesAnswer func setText(_ id: String) async throws -> ChatThemesAnswer func setGround(_ ground: String) async throws -> ChatThemesAnswer /// The Calls tile, newest first, 80 a page (`chat.calls {after?}`). func calls(after: String?) async throws -> ChatCallsAnswer /// Sends what an act queued, off the main thread (`ActAnswer.flush`). func flush() async /// A message's attachment by `message` and `index`, as a file on the /// phone; or a photo by its key where `photosByKey` is false. func picture(media: String?, message: String?, index: Int?) async -> URL? /// Any attachment of a message as a file on the phone, under its own /// extension (`chat.file`). Refused `file_gone` or `file_offline` in the /// kit's words, which are said as they are. func file(message: String, index: Int) async throws -> ChatFileAnswer /// Whether a person's photo key is drawn by Cotton's own picture store /// (`RecordPicture`) rather than through `picture(media:)`. var photosByKey: Bool { get } /// Changes that came in, each naming the one row or bubble it touches. func changes() -> AsyncStream /// A message's picture asked once (`chat.picture`): its file, gone in the core's word, or not yet. func findPicture(message: String, index: Int) async -> ChatPictureFound // Pictures at once (ChatPicturesAhead.swift). func ahead(thread: String, messages: [String]) async func warm(constrained: Bool) async -> Int func previewsWanted() async -> [ChatPreviewWanted] func setPreviews(_ made: [ChatPreviewMade]) async // The voice player (ChatVoice.swift). func voiceSpeed() async -> Double func setVoiceSpeed(_ speed: Double) async func waveformsWanted() async -> [ChatPreviewWanted] func setWaveforms(_ made: [ChatWaveformMade]) async // Link previews (ChatLinkFetch.swift, CONTRACT.md "Link previews"). /// The page this phone fetched from `url`, read by the core as its card (`chat.linkCard`); nil when none goes. func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? } extension ChatBook { /// The open chat shows these messages (`chat.ahead`): their pictures, and those on each side, come onto the phone. func ahead(thread: String, messages: [String]) async {} /// The chat list's warm (`chat.warm`): answers how many pictures it fetched, 0 when there was nothing left. func warm(constrained: Bool) async -> Int { 0 } /// Pictures on this phone with no preview yet (`chat.previews`). func previewsWanted() async -> [ChatPreviewWanted] { [] } /// Previews made here, written into their messages (`chat.preview`). func setPreviews(_ made: [ChatPreviewMade]) async {} /// One speed for every voice message, the person's (`chat.settings` voiceSpeed): 1 until chosen. func voiceSpeed() async -> Double { 1 } func setVoiceSpeed(_ speed: Double) async {} func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? { nil } /// Voice messages on this phone with no waveform yet (`chat.waveforms`). func waveformsWanted() async -> [ChatPreviewWanted] { [] } /// Waveforms read here, written into their messages (`chat.waveform`). func setWaveforms(_ made: [ChatWaveformMade]) async {} /// A book that says only file or nothing: nothing is "not yet", never gone; gone is the core's word. func findPicture(message: String, index: Int) async -> ChatPictureFound { if let url = await picture(media: nil, message: message, index: index) { return .file(url) } return .notYet } } /// What one ask for a message's picture found. enum ChatPictureFound: Equatable, Sendable { case file(URL) /// The core said so: the store does not hold it and the message is past its first minutes /// (`not_found`), or its bytes did not open (`unreadable`). case gone /// On its way (`not_yet`: still going up, or new and not landed yet), or no answer (no connection): /// asked again soon, never drawn as gone. case notYet static func of(code: String) -> ChatPictureFound { ["not_found", "unreadable"].contains(code) ? .gone : .notYet } var url: URL? { if case .file(let url) = self { return url } return nil } } /// One thing that changed: a list row, or a thread's bubbles. enum ChatChange: Sendable, Equatable { case row(ChatListRow) case bubble(thread: String, ChatBubble) /// Messages arrived below what a thread holds: its newest page is stale. case arrived(thread: String) /// A chat was read on another of the person's phones (`chat.incoming`'s `read`). case read(thread: String) } enum ChatBooks { @MainActor static var shared: (any ChatBook)? /// The fan the core last answered with a list (`chat.list`'s `fan`). @MainActor static var fanTiles: [ChatFanTile] = [] @MainActor static func make(core: (any CottonCalling)?, chat: (any CottonChatting)? = nil) -> any ChatBook { if let shared { return shared } #if COTTON_DEV if ChatWarmSeed.asked, let seeded = ChatWarmSeedBook(long: ChatWarmSeed.long) { shared = seeded return seeded } #endif guard let core else { return CoreChatBook(core: UnreachableCore(), chat: nil) } let book = CoreChatBook(core: core, chat: chat) shared = book return book } /// Whether this app is Cotton Chat (the Messages flavour or its Dev twin). static var isChat: Bool { FlavourManifest.current?.flavour.hasPrefix("messages") == true } /// Reads the core's fan once before the board's fan is dealt, so Chat's /// cards stand from the first draw. @MainActor static func prime(core: (any CottonCalling)?) async { guard isChat, fanTiles.isEmpty, let core else { return } if let answer = try? await core.call(ChatMethod.list, ChatListAsk(filter: "all"), as: ChatListAnswer.self) { fanTiles = answer.fan } } /// The board's cards from the core's fan, in its order: a card per /// filter and source, then Account as the tile's aside. static func cards(_ fan: [ChatFanTile]) -> [ToolView] { fan.compactMap { tile in var card: [String: Any] = ["id": "chat:\(tile.id)", "label": tile.label, "default": tile.id == "all", "read": ["table": "thread", "where": [String: String]()]] if tile.id == "account" { card["id"] = "account" card["aside"] = true } else { card["chat"] = tile.id } if let count = tile.count { card["count"] = count } guard let data = try? JSONSerialization.data(withJSONObject: card) else { return nil } return try? JSONDecoder().decode(ToolView.self, from: data) } } /// The fan as the core answered it, with Chat's own cards on the tile /// whose face was the old stream of chats: All, People, Groups, Unread, /// Archived, a card per source, then Account, in `chat.list`'s order. /// Until the core's `shell.fan` deals these itself, they are dealt here /// from the core's own `chat.list` fan. @MainActor static func fan(_ answer: FanAnswer) -> FanAnswer { guard isChat, let stream = answer.stream else { return answer } let cards = cards(fanTiles) guard !cards.isEmpty else { return answer } var answer = answer answer.stream = nil for index in answer.tiles.indices where answer.tiles[index].key == stream.tool || answer.tiles[index].tool == stream.tool { answer.tiles[index].views = cards answer.tiles[index].ringed = true answer.tiles[index].poster = false answer.tiles[index].viewsTable = stream.table if let current = answer.tiles[index].current, cards.contains(where: { $0.id == current }) { continue } answer.tiles[index].current = cards.first?.id } return answer } } /// A core that is not there: every ask is refused, never answered from /// made-up data. struct UnreachableCore: CottonCalling { struct Unreachable: Error {} func callRaw(_ method: String, requestJSON: String) async throws -> String { throw Unreachable() } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} } /// The core's own answers. struct CoreChatBook: ChatBook, @unchecked Sendable { let core: any CottonCalling /// The chat engine: it holds the chat key `chat.flush` needs. weak var chat: (any CottonChatting)? init(core: any CottonCalling, chat: (any CottonChatting)?) { self.core = core self.chat = chat } private struct Thread: Encodable { let thread: String } private struct Theme: Encodable { let theme: String; let dark: Bool } private struct Value: Encodable { let value: String } private struct Ground: Encodable { let ground: String } private struct After: Encodable { let after: String? } private struct Picture: Encodable { let message: String; let index: Int; let dir: String } private struct Path: Decodable { let path: String } private struct Opened: Decodable { let path: String; let previewWanted: Bool? } private struct Ahead: Encodable { let thread: String; let messages: [String] } private struct Warm: Encodable { let constrained: Bool } private struct Warmed: Decodable { let fetched: Int? } private struct Wanted: Decodable { let items: [ChatPreviewWanted] } private struct Made: Encodable { let items: [ChatPreviewMade] } private struct Anything: Decodable {} private struct VoiceSettings: Decodable { let voiceSpeed: Double? } private struct VoiceSpeed: Encodable { let voiceSpeed: Double } private struct Waves: Encodable { let items: [ChatWaveformMade] } private struct LinkPage: Encodable { let thread: String; let url: String; let page: String } var photosByKey: Bool { true } func list(_ ask: ChatListAsk) async throws -> ChatListAnswer { let answer = try await core.call(ChatMethod.list, ask, as: ChatListAnswer.self) await MainActor.run { ChatBooks.fanTiles = answer.fan } return answer } func thread(_ ask: ChatThreadAsk) async throws -> ChatThreadAnswer { try await core.call(ChatMethod.thread, ask, as: ChatThreadAnswer.self) } func compose(_ ask: ChatComposeAsk) async throws -> ChatComposeAnswer { try await core.call(ChatMethod.compose, ask, as: ChatComposeAnswer.self) } func act(_ ask: ChatActAsk) async throws -> ChatActAnswer { try await core.call(ChatMethod.act, ask, as: ChatActAnswer.self) } func decide(_ thread: String, _ method: String) async throws { _ = try await core.call(method, Thread(thread: thread), as: Anything.self) } func themes() async throws -> ChatThemesAnswer { try await core.call(ChatMethod.themes, [String: String](), as: ChatThemesAnswer.self) } func choose(theme: String, dark: Bool) async throws -> ChatThemesAnswer { try await core.call(ChatSettingsMethod.theme, Theme(theme: theme, dark: dark), as: ChatThemesAnswer.self) } func setText(_ id: String) async throws -> ChatThemesAnswer { try await core.call(ChatSettingsMethod.text, Value(value: id), as: ChatThemesAnswer.self) } func setGround(_ ground: String) async throws -> ChatThemesAnswer { try await core.call(ChatSettingsMethod.ground, Ground(ground: ground), as: ChatThemesAnswer.self) } func calls(after: String?) async throws -> ChatCallsAnswer { try await core.call(ChatMethod.calls, After(after: after), as: ChatCallsAnswer.self) } func flush() async { await chat?.flush() } func picture(media: String?, message: String?, index: Int?) async -> URL? { guard let message else { return nil } let dir = FileManager.default.temporaryDirectory.appendingPathComponent("chat-pictures", isDirectory: true).path guard let path = try? await core.call(ChatMethod.picture, Picture(message: message, index: index ?? 0, dir: dir), as: Path.self).path else { return nil } return URL(fileURLWithPath: path) } func findPicture(message: String, index: Int) async -> ChatPictureFound { let dir = FileManager.default.temporaryDirectory.appendingPathComponent("chat-pictures", isDirectory: true).path do { let opened = try await core.call(ChatMethod.picture, Picture(message: message, index: index, dir: dir), as: Opened.self) let url = URL(fileURLWithPath: opened.path) // A picture with no preview yet (sent before previews, or imported) gets its own from this file. if opened.previewWanted == true { await ChatAhead.shared.preview(message: message, index: index, file: url, book: self) } return .file(url) } catch let refusal as CottonCallError { return .of(code: refusal.code) } catch { return .notYet } } func ahead(thread: String, messages: [String]) async { _ = try? await core.call(ChatMethod.ahead, Ahead(thread: thread, messages: messages), as: Anything.self) } func warm(constrained: Bool) async -> Int { (try? await core.call(ChatMethod.warm, Warm(constrained: constrained), as: Warmed.self))?.fetched ?? 0 } func previewsWanted() async -> [ChatPreviewWanted] { (try? await core.call(ChatMethod.previews, [String: String](), as: Wanted.self))?.items ?? [] } func setPreviews(_ made: [ChatPreviewMade]) async { _ = try? await core.call(ChatMethod.preview, Made(items: made), as: Anything.self) } func voiceSpeed() async -> Double { (try? await core.call(ChatMethod.settings, [String: String](), as: VoiceSettings.self))?.voiceSpeed ?? 1 } func setVoiceSpeed(_ speed: Double) async { _ = try? await core.call(ChatMethod.settings, VoiceSpeed(voiceSpeed: speed), as: Anything.self) } func waveformsWanted() async -> [ChatPreviewWanted] { (try? await core.call(ChatMethod.waveforms, [String: String](), as: Wanted.self))?.items ?? [] } func setWaveforms(_ made: [ChatWaveformMade]) async { _ = try? await core.call(ChatMethod.waveform, Waves(items: made), as: Anything.self) } func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? { (try? await core.call(ChatMethod.linkCard, LinkPage(thread: thread, url: url, page: page), as: ChatLinkCardAnswer.self)) .flatMap { $0.title == nil ? nil : $0 } } func file(message: String, index: Int) async throws -> ChatFileAnswer { // A caches folder: the system may take it back, and `chat.file` writes it again. let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("chat-files", isDirectory: true).path return try await core.call(ChatMethod.file, Picture(message: message, index: index, dir: dir), as: ChatFileAnswer.self) } func changes() -> AsyncStream { AsyncStream { continuation in let token = NotificationCenter.default.addObserver(forName: .cottonChatLanded, object: nil, queue: nil) { note in if let thread = note.userInfo?["thread"] as? String { continuation.yield(.arrived(thread: thread)) } } // A read here answers its row; one from another phone names only its thread. let read = NotificationCenter.default.addObserver(forName: .cottonChatRead, object: nil, queue: nil) { note in if let row = note.userInfo?["row"] as? ChatListRow { continuation.yield(.row(row)) } else if let thread = note.userInfo?["thread"] as? String { continuation.yield(.read(thread: thread)) } } let box = ObserverBox(token) let readBox = ObserverBox(read) continuation.onTermination = { _ in NotificationCenter.default.removeObserver(box.token) NotificationCenter.default.removeObserver(readBox.token) } } } private final class ObserverBox: @unchecked Sendable { let token: any NSObjectProtocol init(_ token: any NSObjectProtocol) { self.token = token } } } /// A message's picture asked of the book once at a time, and never again /// in a storm. Gone is the core's word only: the store said it does not hold /// the file and the message is past its first minutes (`ChatMediaPart.gone`, /// or `chat.picture` refused `not_found`), or its bytes did not open; it is /// then not asked again for 30 seconds, then 2, 10 and 60 minutes, however /// often it is drawn. A picture on its way (still going up, new and not /// landed yet, no connection) is never drawn as gone: it is asked again after /// 2, 5, 15, 30 seconds, then each minute, while its tile stands. A tile /// drawn again while one try is out waits for that try. @MainActor @Observable final class ChatPictureTries { static let shared = ChatPictureTries() /// The pictures the core said are gone, or whose bytes did not open: drawn as not available. private(set) var gone: Set = [] private struct Wait { var tries: Int; var until: ContinuousClock.Instant; var gone: Bool } @ObservationIgnored private var waits: [String: Wait] = [:] @ObservationIgnored private var out: [String: Task] = [:] static let backoff: [Duration] = [.seconds(30), .seconds(120), .seconds(600), .seconds(3_600)] static var soon: [Duration] = [.seconds(2), .seconds(5), .seconds(15), .seconds(30), .seconds(60)] static func key(_ message: String, _ index: Int) -> String { "\(message)#\(index)" } /// One try, or what the last one found while its wait runs. func find(message: String, index: Int, book: any ChatBook) async -> ChatPictureFound { let key = Self.key(message, index) if let running = out[key] { return await running.value } if let wait = waits[key], ContinuousClock.now < wait.until { return wait.gone ? .gone : .notYet } let running = Task { await book.findPicture(message: message, index: index) } out[key] = running let found = await running.value out[key] = nil switch found { case .file: waits[key] = nil; gone.remove(key) case .gone: failed(key) case .notYet: later(key) } return found } /// The picture's file, from one try, or nil while its wait runs. func url(message: String, index: Int, book: any ChatBook) async -> URL? { await find(message: message, index: index, book: book).url } /// The picture's file, asked again after each wait while it is on its way; nil once it is gone /// or the asking task ends (its tile went). func file(message: String, index: Int, book: any ChatBook) async -> URL? { while !Task.isCancelled { switch await find(message: message, index: index, book: book) { case .file(let url): return url case .gone: return nil case .notYet: let until = waits[Self.key(message, index)]?.until ?? ContinuousClock.now + Self.soon[0] try? await Task.sleep(until: max(until, ContinuousClock.now + .milliseconds(200)), clock: .continuous) } } return nil } /// The file came but did not open as a picture: not available, as a missing one. func unopened(message: String, index: Int) { failed(Self.key(message, index)) } private func failed(_ key: String) { let tries = (waits[key].map { $0.gone ? $0.tries : 0 } ?? 0) + 1 waits[key] = Wait(tries: tries, until: ContinuousClock.now + Self.backoff[min(tries, Self.backoff.count) - 1], gone: true) gone.insert(key) } private func later(_ key: String) { let tries = (waits[key].map { $0.gone ? 0 : $0.tries } ?? 0) + 1 waits[key] = Wait(tries: tries, until: ContinuousClock.now + Self.soon[min(tries, Self.soon.count) - 1], gone: false) gone.remove(key) } } /// Pictures decoded off the main thread at the size they are drawn, kept /// while the app runs. actor ChatPictures { static let shared = ChatPictures() private let cache = NSCache() /// Each message's picture as last drawn, by message, index and side: read on the drawing thread, so a cell drawn /// again (or the chat opened again) shows it on its first frame. NSCache is safe from any thread. nonisolated(unsafe) private static let drawnCache: NSCache = { let cache = NSCache() cache.countLimit = 300 return cache }() nonisolated static func drawn(_ key: String, side: CGFloat) -> UIImage? { drawnCache.object(forKey: "\(key)#\(Int(side))" as NSString) } nonisolated static func remember(_ key: String, side: CGFloat, _ image: UIImage) { drawnCache.setObject(image, forKey: "\(key)#\(Int(side))" as NSString) } func image(_ url: URL, side: CGFloat) async -> UIImage? { let key = "\(url.path)#\(Int(side))" as NSString if let hit = cache.object(forKey: key) { return hit } let image: UIImage? = await Task.detached(priority: .userInitiated) { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil } let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: max(1, Int(side * 3))] guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } return UIImage(cgImage: cg).preparingForDisplay() }.value if let image { cache.setObject(image, forKey: key) } return image } /// A tiny base64 preview, decoded once. func preview(_ base64: String) -> UIImage? { let key = "p:\(base64.hashValue)" as NSString if let hit = cache.object(forKey: key) { return hit } guard let data = Data(base64Encoded: base64), let image = UIImage(data: data) else { return nil } cache.setObject(image, forKey: key) return image } } #endif