284 lines · 12.9 KB · SwiftRaw
// RECORDING IN COMMS (CONTRACT.md "Recordings": Recording, Import): Calls' Record starts Meetings' own engine// (`MeetingsEngine`, `meetings.record.*`: the file written as it goes, marks kept beside it, ticks, recovery at the next// launch), and the recording screen stands over Calls with the core's words (`chat.recording.live`): the time running,// Pause or Resume, Mark, a large Stop, Discard asked first, and the space left when it runs low. Stop files it and opens// its page. Bring in a recording hands an audio file from Files to `meetings.import`.#if os(iOS)import AVFoundationimport CottonKitimport SwiftUIimport UniformTypeIdentifiers/// `chat.recording.live`'s answer.struct ChatRecordingLive: Codable, Equatable, Sendable { struct Space: Codable, Equatable, Sendable { var line: String var stop: Bool } var title: String var time: String var stop: String var pause: String var resume: String var mark: String var discard: String var discardAsk: String? var space: Space?}@MainActor@Observablefinal class ChatRecorder { static let shared = ChatRecorder() /// What the recording screen draws while a recording is in hand. struct Live: Equatable { var words: ChatRecordingLive? var paused: Bool var elapsedMs: Double var level: Double } /// Any of the audio Comms brings in (CONTRACT.md "Import"). static let audioTypes: [UTType] = [.audio, .mpeg4Audio, .mp3, .wav, .aiff, UTType("public.aac-audio"), UTType("com.apple.coreaudio-format"), UTType("org.xiph.ogg-audio"), UTType("org.xiph.opus"), UTType("org.xiph.flac"), UTType("org.3gpp.adaptive-multi-rate-audio"), UTType("public.3gpp")].compactMap { $0 } /// Whether an opened file is audio Comms takes in (Comms' own build). static func opens(_ url: URL) -> Bool { guard url.isFileURL, ChatRoot.applies, let type = UTType(filenameExtension: url.pathExtension.lowercased()) else { return false } return type.conforms(to: .audio) || audioTypes.contains(type) } let engine = MeetingsEngine.shared /// The recording's page to open, once Stop has filed it. var saved: String? @ObservationIgnored private var words: ChatRecordingLive? @ObservationIgnored private var core: (any CottonCalling)? @ObservationIgnored private var asking: Task<Void, Never>? @ObservationIgnored private var seenFiled = 0 /// The recording screen's state, nil when nothing is in hand. var live: Live? { guard engine.isBusy else { return nil } let paused: Bool if case .paused = engine.state.stage { paused = true } else { paused = false } return Live(words: liveWords, paused: paused, elapsedMs: engine.elapsedMs, level: engine.meter.last ?? 0) } private(set) var liveWords: ChatRecordingLive? /// Comms' core, for the engine and the screen's words; recovery of a recording the app was closed on. func attach(_ core: any CottonCalling) async { self.core = core let held = core engine.attach { held } await engine.recoverAtLaunch() await hear() } /// The words of what waits, made on this phone where the core says it may take one (CONTRACT.md "Recordings": /// after Stop or an import, and while Comms is open). func hear() async { guard let core else { return } await MeetingsPhoneStep.shared.drain(core: core) heard += 1 } /// Bumped each time the phone's step ends, words made or refused: Calls and an open page ask the core again (a /// row said "Turning into words" until Calls was opened again, seen on dev, 23 Nov 2026). private(set) var heard = 0 /// Starts a room recording; the words of a refusal, or nil when it records. func start(core: (any CottonCalling)?, blocked: String?) async -> String? { if let core, self.core == nil { await attach(core) } seenFiled = engine.filed switch await engine.start(.meeting) { case .recording: follow() return nil case .blocked: return blocked ?? "" case .failed(let why): return why } } func pause() { engine.pause() } func resume() { engine.resume() } func mark() { engine.mark() } func stop() { engine.stop() } func discard() { engine.discard() } /// Asks the core for the screen's words about every second while a recording is in hand; Stop's filing opens the page. private func follow() { asking?.cancel() asking = Task { [weak self] in while let self, !Task.isCancelled { if self.engine.isBusy { await self.askWords() } else { if self.engine.filed != self.seenFiled, let meeting = self.engine.lastMeetingId { self.saved = meeting Task { await self.hear() } } self.liveWords = nil return } try? await Task.sleep(for: .seconds(1)) } } } private func askWords() async { guard let core else { return } struct Ask: Encodable, Sendable { let meeting: String; let kind: String; let duration_ms: Int; let free_bytes: Int64? } let free = (try? URL(fileURLWithPath: NSHomeDirectory()).resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))? .volumeAvailableCapacityForImportantUsage let ask = Ask(meeting: engine.act, kind: engine.kind.rawValue, duration_ms: Int(engine.elapsedMs), free_bytes: free) guard let answer = try? await core.call(ChatRecordingMethod.live, ask, as: ChatRecordingLive.self) else { return } liveWords = answer // Under the last few megabytes: stop and keep what it has (CONTRACT.md "Recording"). if answer.space?.stop == true { engine.stop() } } /// An audio file from Files into a recording: copied out of its folder, then `meetings.import`. func bring(_ url: URL, core: (any CottonCalling)?) async -> (meeting: String?, said: String?, refused: String?) { guard let core else { return (nil, nil, nil) } let opened = url.startAccessingSecurityScopedResource() defer { if opened { url.stopAccessingSecurityScopedResource() } } let held = FileManager.default.temporaryDirectory.appendingPathComponent("comms-import-\(UUID().uuidString)", isDirectory: true) let copy = held.appendingPathComponent(url.lastPathComponent) do { try FileManager.default.createDirectory(at: held, withIntermediateDirectories: true) try FileManager.default.copyItem(at: url, to: copy) } catch { return (nil, nil, ActionRefused.words(for: error)) } // The file's own facts, the core choosing its date from them (`recording_time::taken_at`, android-finish, // Comms 28 fixes 2): the audio's own creation time, and its last change. struct Ask: Encodable, Sendable { let path: String; let name: String; let mime: String?; let duration_ms: Int?; let recorded: String?; let modified_ms: Int64? } struct Answer: Decodable, Sendable { let meeting: String; let said: String? } let seconds = try? await AVURLAsset(url: copy).load(.duration).seconds let recorded = await Self.recorded(copy).map(ChatRecordingDate.string) let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate let ask = Ask(path: copy.path, name: url.lastPathComponent, mime: UTType(filenameExtension: url.pathExtension)?.preferredMIMEType, duration_ms: seconds.flatMap { $0.isFinite ? Int($0 * 1000) : nil }, recorded: recorded, modified_ms: modified.map { Int64($0.timeIntervalSince1970 * 1000) }) do { let answer = try await core.call(ChatRecordingMethod.importFile, ask, as: Answer.self) if self.core == nil { await attach(core) } else { Task { await hear() } } return (answer.meeting, answer.said, nil) } catch { return (nil, nil, ActionRefused.words(for: error)) } }}extension ChatRecorder { /// The audio's own creation time, when it carries one (a Voice Memo does, and keeps it through a share's copy). nonisolated static func recorded(_ copy: URL) async -> Date? { guard let item = try? await AVURLAsset(url: copy).load(.creationDate) else { return nil } return try? await item.load(.dateValue) }}/// Record, right of Calls' title: a red dot and the word, on the accent.struct ChatRecordButton: View { let label: String let tap: () -> Void @Environment(\.chatLook) private var look var body: some View { Button(action: tap) { HStack(spacing: 7) { Circle().fill(look.colours.onAccent).frame(width: 9, height: 9).accessibilityHidden(true) Text(verbatim: label).font(look.font(15, .semibold)) } .foregroundStyle(look.colours.onAccent) .padding(.horizontal, 16) .frame(minHeight: 40) .background(Capsule().fill(look.colours.accent)) .contentShape(Capsule()) } .buttonStyle(.plain) .accessibilityIdentifier("calls-record") }}/// The recording screen over Calls: the time running, a level, Pause or Resume and Mark, a large Stop; Discard asked.struct ChatRecordingLiveView: View { let live: ChatRecorder.Live let recorder: ChatRecorder @Environment(\.chatLook) private var look @State private var discarding = false private var time: String { if let words = live.words { return words.time } let seconds = Int(live.elapsedMs / 1000) return String(format: "%d:%02d", seconds / 60, seconds % 60) } var body: some View { VStack(spacing: 0) { Spacer() Text(verbatim: live.words?.title ?? "") .font(look.font(17, .semibold)) .foregroundStyle(look.colours.dim) .accessibilityAddTraits(.isHeader) Text(verbatim: time) .font(look.font(64, .bold).monospacedDigit()) .foregroundStyle(look.colours.text) .padding(.top, 8) .accessibilityIdentifier("recording-time") Capsule() .fill(look.colours.accent) .frame(width: 40 + 200 * min(max(live.level, 0), 1), height: 6) .animation(.easeOut(duration: 0.1), value: live.level) .padding(.top, 18) .accessibilityHidden(true) if let space = live.words?.space { Text(verbatim: space.line).font(look.font(15)).foregroundStyle(look.colours.danger) .multilineTextAlignment(.center) .padding(.top, 16) .accessibilityIdentifier("recording-space") } Spacer() HStack(spacing: 28) { WarmRound(symbol: live.paused ? "play.fill" : "pause.fill", label: (live.paused ? live.words?.resume : live.words?.pause) ?? "", id: "recording-pause") { live.paused ? recorder.resume() : recorder.pause() } Button(action: recorder.stop) { RoundedRectangle(cornerRadius: 8, style: .continuous) .fill(look.colours.onAccent) .frame(width: 28, height: 28) .frame(width: 84, height: 84) .background(Circle().fill(look.colours.accent)) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: live.words?.stop ?? "")) .accessibilityIdentifier("recording-stop") WarmRound(symbol: "flag", label: live.words?.mark ?? "", id: "recording-mark") { recorder.mark() } } Button { discarding = true } label: { Text(verbatim: live.words?.discard ?? "").font(look.font(15, .medium)).foregroundStyle(look.colours.dim) .frame(minHeight: 44) } .buttonStyle(.plain) .padding(.top, 18) .padding(.bottom, 40) .accessibilityIdentifier("recording-discard") } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(look.colours.ground.ignoresSafeArea()) .accessibilityElement(children: .contain) .accessibilityIdentifier("recording-live") .lookAsk(isPresented: $discarding, style: look.panel, font: look.font(17, .semibold), message: live.words?.discardAsk, messageColour: look.colours.text, choices: [LookChoice(id: "recording-discard", label: live.words?.discard ?? "", colour: look.colours.danger) { recorder.discard() }]) }}#endif