// Bringing a recording in from Files — the picker's types, the copy, and the // one call. // // The act is three steps and the middle one is the reason this is not two lines // inside a screen body: // // 1. the picked URL is SECURITY-SCOPED and stops being readable the moment the // scope closes, which is before any `await` finishes; // 2. so the bytes are copied into this app's own container first // (`MeetingFiles`), keeping the extension, because the crate takes a // meeting's container off the FILE's name; // 3. and `meetings.create` copies that into the store, after which this copy // has done its job. // // **The copy is dropped whatever happens, and that is a different rule from the // share sheet's.** A share's staged copy is kept on a refusal because the // sharing app has already let go of the original and nobody else is holding // those bytes. A file picked from Files is still in Files: the person can pick // it again, and keeping a second copy in the app group for ever would be this // app hoarding against a failure it did not have. import CottonKit import Foundation import UniformTypeIdentifiers /// What a picked recording does. @MainActor enum MeetingImport { /// What the file picker offers. /// /// `.audio` is the family and covers everything the system has a type for. /// The two Xiph types are declared BY THIS APP (`project.yml`'s /// `UTImportedTypeDeclarations`) because iOS ships no type for either — a /// WhatsApp voice note is `.opus` in an Ogg container and is the recording /// this owner shares in most often, and without a declared type it reaches /// the picker as `public.data` and cannot be chosen at all. /// /// **`.mp4` is deliberately not offered**, although the crate accepts one: /// the system's type for it is `public.mpeg-4`, a MOVIE, and adding it here /// would fill a recordings picker with every video on the phone. An /// audio-only mp4 still arrives fine through the share sheet, which is /// where one actually comes from. static var pickerTypes: [UTType] { var types: [UTType] = [.audio] for name in MeetingAudioFormats.extensions.sorted() where name != "mp4" { guard let system = UTType(filenameExtension: name) else { continue } guard !types.contains(system) else { continue } types.append(system) } for declared in [ogg, opus] where !types.contains(declared) { types.append(declared) } return types } /// Xiph's own identifiers, written once. /// /// They are the STRINGS and not `UTType.identifier`, because the answer to /// `identifier` is the system's: a Mac already knows `org.xiph.ogg` and /// hands back its own `org.xiph.ogg-audio` for it, while an iPhone knows /// neither and hands back exactly what this app declared. The declaration /// in `project.yml` has to match what is ASKED for, which is this. static let oggIdentifier = "org.xiph.ogg" static let opusIdentifier = "org.xiph.opus" static let ogg = UTType(importedAs: oggIdentifier, conformingTo: .audio) static let opus = UTType(importedAs: opusIdentifier, conformingTo: .audio) /// Copy the picked file into this app's own container and answer where it /// landed, with the act id that owns the directory. /// /// Synchronous and outside any `await`: the security scope has to still be /// open, and `startAccessingSecurityScopedResource` is balanced in the same /// call rather than across a suspension point. static func stage( _ url: URL, into files: any MeetingAudioStore = AppGroupMeetingAudioStore() ) throws -> (act: String, path: String) { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let act = MeetingFiles.newActId() // The NAME is kept, extension and all: it is what the crate reads the // container off, and it is what the meeting is titled after. let target = try files.open(act: act, named: url.lastPathComponent) do { try FileManager.default.copyItem(at: url, to: target) } catch { files.discard(act: act) throw MeetingFilesFailure.couldNotCopy } return (act, target.path(percentEncoded: false)) } /// The whole act: stage the file, create the meeting, drop the copy. /// /// Throws the crate's own `CottonCallError` on a refusal, so the screen /// shows the crate's sentence — "a `.txt` is not a recording this database /// can transcribe", "this recording is over the ceiling" — rather than a /// sentence of its own about a rule it does not own. static func bring( _ url: URL, through writer: ScreenWriter, into files: any MeetingAudioStore = AppGroupMeetingAudioStore() ) async throws -> MeetingCreated { let name = url.lastPathComponent // Refused HERE rather than after a copy: a picker can be talked past // (a type the system mapped wrongly, a file renamed by hand), and // copying a file this phone has already decided it cannot send is work // done to reach a refusal. guard MeetingAudioFormats.accepts(fileName: name) else { throw MeetingImportFailure.notARecording(MeetingAudioFormats.fileExtension(ofFileName: name)) } let staged = try stage(url, into: files) defer { files.discard(act: staged.act) } return try await writer.call( CottonMethod.meetingsCreate, MeetingCreateRequest( path: staged.path, source: .import, title: MeetingAudioFormats.titleFromFileName(name), mime: MeetingAudioFormats.mime(forFileName: name) ), as: MeetingCreated.self ) } /// **The path the stack is left in once an import has landed.** /// /// `/meetings?import=1` is an INTENT — the `+` fan asking for the picker — /// and an intent is spent the first time it is acted on. As a route entry /// it is not: the Meetings screen raises the picker in its `.task`, and a /// `.task` runs again every time the screen comes back. So pushing the /// meeting over that entry and taking Back re-fired the importer over the /// list the person had just come back to (the walk of 15 Sep 2026). /// /// The landing REPLACES it. `/meetings/record` is the same kind of entry — /// the list with the recorder sheet up — and Stop spends it the same way: /// going back to a finished recorder would be going back to a microphone /// that is no longer open. What either is replaced WITH is the plain list, /// with the meeting pushed over that: the person filed a recording and /// Back belongs on the list it is now in, not on whatever was under the fan. /// /// Pure, and one assignment at the call site, so the whole change lands in /// a single SwiftUI transaction — a replace and a push as two statements /// would rebuild this screen in between. /// /// Any other top — the plus circle raises the same picker from a plain /// `/meetings` — is a push and nothing else: there is no intent there to /// spend, and replacing the list would leave the person with no list to go /// back to. static func landed(_ landing: Route, over path: [Route]) -> [Route] { var out = spent(path) out.append(landing) return out } /// The path with a Meetings INTENT on top — the picker or the recorder /// asked for — spent: the plain list in its place. Any other top is left. /// What closing the recorder sheet leaves, and the first half of a landing. static func spent(_ path: [Route]) -> [Route] { var out = path if out.last == .meetings(importing: true) || out.last == .meetingsRecord { out[out.count - 1] = .meetings(importing: false) } return out } } /// Why a picked file did not become a meeting, in words the picker's own rules /// explain. enum MeetingImportFailure: Error, Equatable, LocalizedError { case notARecording(String) var errorDescription: String? { switch self { case .notARecording(let found): let named = found.isEmpty ? ShellLines.line("capture", "meeting.import_that_file") : ShellLines.line("capture", "meeting.import_a_file", ["extension": found]) return ShellLines.line("capture", "meeting.import_not_a_recording", ["named": named]) } } }