import CottonFaces import CottonKit import SwiftUI /// Native commands may request these OS effects; only the platform performs /// them. The core does not report a permission it cannot grant. public enum RecordPlatformAction: Decodable, Hashable, Sendable { case shareFile(URL) case requestNotifications, openNotificationSettings case pickFile(RecordFilePick) case openFlow(RecordKeptFlow) /// "Re-key this device" (`DeviceRekey`): the app mints the successor key. case rekeyDevice /// A book's read act (`reader.open`): the reader opens it, at `at` when /// the act names a place. case openReader(ReaderOpening) /// A list's Set picture from Photos (`open_picker`, picker `photos`): /// the photo picker opens and the picture picked is the list's own /// (`ListPicture`). case pickListPicture(group: String) /// Keep everything turned on (`keep_songs`): every song not on this phone /// comes down (`SongKeeper`), and what the act said is said. case keepSongs(said: String?) /// An album's Find details (`find_details`): the phone's lookups /// (`MusicLookup`). case findDetails(table: String, id: String) /// A song's, an album's or an artist's Play, Shuffle, Play next and Add /// to queue, a film's or a series' episode's Play (`shell.player`): the /// instrument of the kind playing plays what the core answered /// (`Players`). case play(PlayerAnswer) /// Cotton Cinemas' Keep everything turned on (`keep_films`): every film /// and episode not on this phone comes down (`FilmKeeper`), and what the /// act said is said. case keepFilms(said: String?) /// A library's Export library (`export_open`): the open bundle of `kit` /// laid, zipped and handed to the share sheet (`LibraryExport`), named /// after its tool (`name`). case exportOpen(kit: String, name: String) /// A scene's Write (`open_writer`): Cotton Story writes its scenes in /// its own screens (`Story/Ink`), so nothing outside them opens one. case openWriter(scene: String) private enum Name: String, Decodable { case shareFile = "share_file" case requestNotifications = "request_notifications" case openNotificationSettings = "open_notification_settings" case pickFile = "pick_file" case openFlow = "open_flow" case rekeyDevice = "rekey_device" case openReader = "open_reader" case openPicker = "open_picker" case keepSongs = "keep_songs" case findDetails = "find_details" case play case keepFilms = "keep_films" case exportOpen = "export_open" case openWriter = "open_writer" } public init(from decoder: Decoder) throws { self = try Self.action(Name(from: decoder), decoder: decoder) } static func fromAnswer(_ decoder: Decoder) throws -> Self? { struct Platform: Decodable { let platform_action: Name? } guard let name = try Platform(from: decoder).platform_action else { return nil } return try action(name, decoder: decoder) } private static func action(_ name: Name, decoder: Decoder) throws -> Self { switch name { case .shareFile: struct File: Decodable { let path: String } return .shareFile(URL(fileURLWithPath: try File(from: decoder).path)) case .requestNotifications: return .requestNotifications case .openNotificationSettings: return .openNotificationSettings case .pickFile: return .pickFile(try RecordFilePick(from: decoder)) case .openFlow: return .openFlow(try RecordKeptFlow(from: decoder)) case .rekeyDevice: return .rekeyDevice case .openReader: struct Opening: Decodable { let id: String; let at: String?; let table: String? } let opening = try Opening(from: decoder) return .openReader(ReaderOpening(id: opening.id, at: opening.at, table: opening.table ?? "book")) case .openPicker: struct Picker: Decodable { let picker: String; let group: String? } let picker = try Picker(from: decoder) guard picker.picker == "photos", let group = picker.group else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "open_picker opens a list's photo picker alone, not \(picker.picker)")) } return .pickListPicture(group: group) case .keepSongs: struct Said: Decodable { let said: String? } return .keepSongs(said: try Said(from: decoder).said) case .findDetails: struct Named: Decodable { let table: String; let id: String } let named = try Named(from: decoder) return .findDetails(table: named.table, id: named.id) case .play: return .play(try PlayerAnswer(from: decoder)) case .keepFilms: struct Said: Decodable { let said: String? } return .keepFilms(said: try Said(from: decoder).said) case .exportOpen: struct Library: Decodable { let kit: String; let name: String } let library = try Library(from: decoder) return .exportOpen(kit: library.kit, name: library.name) case .openWriter: struct Scene: Decodable { let scene: String } return .openWriter(scene: try Scene(from: decoder).scene) } } } @MainActor enum RecordPlatformEffects { @discardableResult static func perform(_ action: RecordPlatformAction, authority: any NotificationSettingsAuthority = SystemNotificationSettingsAuthority(), nativeFlow: (@MainActor (RecordKeptFlow) async -> Bool)? = nil, rekey: (@MainActor () async -> Bool)? = nil, reader: ReaderPresenter? = nil) async -> Bool { switch action { case .openReader(let opening): guard let reader else { return false } reader.open(opening) case .shareFile(let url): ShareSheet.present(url) case .pickListPicture(let group): await ListPicture.shared.pick(for: group) case .keepSongs(let said): #if os(iOS) await SongKeeper.shared.keepEverything(said: said) #endif case .findDetails(let table, let id): await MusicLookup.shared.findDetails(table: table, id: id) case .play(let answer): #if os(iOS) Players.took(answer) #else return false #endif case .keepFilms(let said): #if os(iOS) await FilmKeeper.shared.keepEverything(said: said) #else return false #endif case .exportOpen(let kit, let name): await LibraryExport.shared.export(kit: kit, name: name) case .openWriter: return false case .rekeyDevice: guard let rekey else { return false } return await rekey() case .openFlow(let flow): guard let nativeFlow else { return false } return await nativeFlow(flow) case .pickFile: return false // Requires a captured native continuation. case .requestNotifications: if await authority.read() == .undetermined { _ = await authority.ask() } // The existing permission-change listener registers and reports // the actual OS answer through the device push path. case .openNotificationSettings: authority.openSystemSettings() } return true } } /// A native flow requests platform work, never claims an engine change. public struct RecordKeptFlow: Decodable, Hashable, Sendable { public enum Flow: String, Decodable, Hashable, Sendable { case leaveDatabase, reportProblem, vaultUnlock /// This device's own Sign in, Sign out and Erase (`device.json`): the /// personal object's session, which the app's root runs /// (`PersonalSessionFlows`) wherever the device's card is opened. case signIn, signOut, eraseThisDevice /// This device's Share ink: the ink the phone kept (`InkCapture`), /// handed to the share sheet by the app's root. case shareInk /// A film's, a season's and an episode's Keep on phone and Remove /// download (`film.json`, `film_season.json`, `film_episode.json`): /// their files come down or go (`FilmKeeper`), the root's to run /// wherever the card is opened. case keepFilm, removeFilmDownload /// A podcast episode's Keep on phone and Remove download /// (`episode.json`): its audio file comes down or goes /// (`EpisodeKeeper`), the root's to run wherever the card is opened. case keepEpisode, removeEpisodeDownload /// A book's Keep on phone and Remove download (`book.json`): its /// file comes down into the media store or this copy goes /// (`BookKeeper`), the root's to run wherever the card is opened. case keepBook, removeBookDownload /// A book's Add file (`book.json`): the document picker for its EPUB /// or PDF, which the root raises and hands to the intake. case addBookFile /// A song's and an album's Keep on phone and Remove download /// (`song.json`, `music_album.json`): their files come down or go /// (`SongKeeper`), the root's to run wherever the card is opened. case keepSong, removeSongDownload, keepAlbum, removeAlbumDownload var kept: KeptFlow { KeptFlow(rawValue: rawValue)! } /// This device's own acts, the app's root's to run wherever its card /// is opened. var session: Bool { [.signIn, .signOut, .eraseThisDevice, .shareInk].contains(self) } /// A film's own acts, the root's too. var film: Bool { [.keepFilm, .removeFilmDownload, .keepEpisode, .removeEpisodeDownload, .keepBook, .removeBookDownload, .addBookFile, .keepSong, .removeSongDownload, .keepAlbum, .removeAlbumDownload].contains(self) } } public struct Origin: Decodable, Hashable, Sendable { public let table: String public let id: String } public let flow: Flow public let origin: Origin public let database: String? func matches(table: String?, id: String?) -> Bool { origin.table == table && origin.id == (id ?? "new") } } extension EnvironmentValues { @Entry var nativeKeptFlow: (@MainActor (RecordKeptFlow) async -> Bool)? = nil /// The app's "Re-key this device" (`DeviceRekey.start`), set once at the root. @Entry var rekeyThisDevice: (@MainActor () async -> Bool)? = nil }