Cotton code
222 lines · 13.4 KB · KotlinRaw
package com.cottondb.androidimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.day.todos.TodoRepositoryimport com.cottondb.android.day.notes.NotesJournalRepositoryimport com.cottondb.android.day.notes.NoteEditorModelimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport com.cottondb.android.day.mood.MoodRepositoryimport com.cottondb.android.day.thoughts.ThoughtRepositoryimport com.cottondb.android.day.calendar.CalendarRepositoryimport com.cottondb.android.day.calendar.CalendarEditorModelimport com.cottondb.android.day.goals.GoalsRepositoryimport com.cottondb.android.day.goals.GoalCreationModelimport com.cottondb.android.day.goals.GoalDetailModelimport com.cottondb.android.day.alarms.Alarmimport com.cottondb.android.day.alarms.AlarmEditorModelimport com.cottondb.android.day.alarms.AlarmsRepositoryimport com.cottondb.android.capture.CaptureModelimport com.cottondb.android.capture.CaptureRepositoryimport com.cottondb.android.capture.CaptureVoiceimport com.cottondb.android.core.CottonEventimport com.cottondb.android.media.MediaSourceimport com.cottondb.android.traffic.calls.CallsRepositoryimport com.cottondb.android.traffic.calls.CallHistoryModelimport com.cottondb.android.traffic.calls.CallDetailModelimport com.cottondb.android.traffic.messages.MessagesRepositoryimport com.cottondb.android.traffic.messages.MessageThreadModelimport com.cottondb.android.traffic.messages.MessageSearchModelimport com.cottondb.android.traffic.messages.MessageArchiveModelimport com.cottondb.android.traffic.messages.ThreadActionsModelimport com.cottondb.android.traffic.messages.MessageStarModelimport com.cottondb.android.traffic.email.EmailRepositoryimport com.cottondb.android.traffic.email.EmailMailboxModelimport com.cottondb.android.traffic.email.EmailDetailModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport java.time.Clockimport java.time.LocalDate/** Screen models share one core; no screen creates a native handle or subscribes to it. */class FeatureModels(private val core: CottonCalling, val clock: Clock, val writerScope: CoroutineScope, val media: MediaSource, private val importStager: com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager, val passwords: PasswordModels, private val searchRecents: com.cottondb.android.search.SearchRecentsStore, private val documentStager: com.cottondb.android.ui.imports.AndroidSafFileStager, val keyboard: com.cottondb.android.keyboard.KeyboardModel? = null) {    val takes = TakeModels(core, writerScope, writerScope, android.os.SystemClock::elapsedRealtime, keyboard)    val photos = PhotosModels(core, writerScope)    val locations = LocationsModels(core, writerScope)    val meetings = MeetingsModels(core, writerScope)    private var meetingRecordingSession: com.cottondb.android.ui.meetings.recording.MeetingRecordingSession? = null    private var meetingsRetired = false    private val meetingImports = mutableMapOf<String, com.cottondb.android.ui.work.meetings.MeetingsImportCoordinator>()    fun meetingRecording(context: android.content.Context, workspaceId: String): com.cottondb.android.ui.meetings.recording.MeetingRecordingSession {        check(!meetingsRetired) { "This database is closing." }        val existing = meetingRecordingSession        if (existing != null) {            check(existing.workspaceId == workspaceId) { "The recording belongs to another database." }            return existing        }        return com.cottondb.android.ui.meetings.recording.MeetingRecordingSession(context, workspaceId, core, writerScope, clock)            .also { meetingRecordingSession = it }    }    fun meetingImport(context: android.content.Context, visit: String): com.cottondb.android.ui.work.meetings.MeetingsImportCoordinator {        check(!meetingsRetired) { "This database is closing." }        return meetingImports.getOrPut(visit) {            com.cottondb.android.ui.work.meetings.MeetingsImportCoordinator(                com.cottondb.android.ui.work.meetings.meetingsImportStager(context),                com.cottondb.android.work.meetings.MeetingCreateRepository(core), writerScope,            )        }    }    fun releaseMeetingImport(visit: String) {        val coordinator = meetingImports[visit] ?: return        writerScope.launch {            coordinator.retire()            if (meetingImports[visit] === coordinator) meetingImports.remove(visit)        }    }    /** File receipts settle before the workspace's native handle or model scope closes. */    suspend fun retireMeetings() {        meetingsRetired = true        kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {            meetings.retain(emptyList())            meetingRecordingSession?.retire()            meetingImports.values.toList().forEach { it.retire() }            meetingImports.clear()            meetingRecordingSession = null        }    }    val briefing = BriefingModels(core, writerScope)    val activityBin = ActivityBinModels(core, writerScope)    val money = MoneyModels(core, clock, clock.zone, writerScope)    val memory = MemoryModels(core, writerScope)    val reader = ReaderModels(core, writerScope)    val documents = DocumentsModels(core, writerScope, media)    val documentImport = com.cottondb.android.ui.work.documents.DocumentsImportCoordinator(        documentStager, com.cottondb.android.work.documents.DocumentWriteRepository(core), writerScope,    )    private var searchModel: com.cottondb.android.search.SearchModel? = null    fun search() = searchModel ?: com.cottondb.android.search.SearchModel(        com.cottondb.android.search.SearchRepository(core), writerScope,        com.cottondb.android.search.CoroutineSearchScheduler(writerScope), searchRecents,    ).also { searchModel = it }    fun releaseSearch() { searchModel?.close(); searchModel = null }    private val settingsPages = mutableMapOf<String, com.cottondb.android.settings.SettingsModel>()    fun settingsFor(key: String, boot: com.cottondb.android.boot.BootRead) = settingsPages.getOrPut(key) {        com.cottondb.android.settings.SettingsModel(core, writerScope, boot)    }    private val devicePages = mutableMapOf<String, com.cottondb.android.settings.devices.DevicesModel>()    fun devicesFor(key: String) = devicePages.getOrPut(key) {        com.cottondb.android.settings.devices.DevicesModel(com.cottondb.android.settings.devices.DevicesRepository(core))    }    private val peopleDirectories = mutableMapOf<String, com.cottondb.android.day.people.PeopleRepository>()    private val personPages = mutableMapOf<String, com.cottondb.android.day.people.PersonDetailModel>()    fun peopleFor(key: String) = peopleDirectories.getOrPut(key) { com.cottondb.android.day.people.PeopleRepository(core) }    fun personFor(key: String, id: String) = personPages.getOrPut(key) {        com.cottondb.android.day.people.PersonDetailModel(com.cottondb.android.day.people.PeopleRepository(core), id)    }    private val contactImports = mutableMapOf<String, com.cottondb.android.day.people.ContactsImportModel>()    fun contactsFor(key: String, source: () -> com.cottondb.android.day.people.ContactsSource) = contactImports.getOrPut(key) {        com.cottondb.android.day.people.ContactsImportModel(com.cottondb.android.day.people.ContactsImportRepository(core), source())    }    private val projectPages = mutableMapOf<String, ProjectPageModels>()    fun projectsFor(key: String, slug: String? = null) = projectPages.getOrPut(key) {        val repository = com.cottondb.android.work.projects.ProjectsRepository(core)        ProjectPageModels(repository, com.cottondb.android.work.projects.ProjectCreationModel(repository),            slug?.let { com.cottondb.android.work.projects.ProjectEditorModel(repository, it) })    }    private val mailboxes = mutableMapOf<String, EmailMailboxModel>()    private val emailReaders = mutableMapOf<String, EmailDetailModel>()    fun emailFor(key: String) = mailboxes.getOrPut(key) { EmailMailboxModel(EmailRepository(core)) }    fun emailThreadFor(key: String, threadId: String) = emailReaders.getOrPut(key) {        EmailDetailModel(threadId, EmailRepository(core))    }    private val messageImports = mutableMapOf<String, com.cottondb.android.ui.traffic.messages.WhatsAppImportCoordinator>()    fun messageImportFor(key: String) = messageImports.getOrPut(key) {        com.cottondb.android.ui.traffic.messages.WhatsAppImportCoordinator(            com.cottondb.android.traffic.messages.WhatsAppImportModel(                com.cottondb.android.traffic.messages.WhatsAppImportRepository(core)), importStager, writerScope)    }    private val threadDetails = mutableMapOf<String, ThreadDetailPageModels>()    fun threadDetailsFor(key: String, threadId: String) = threadDetails.getOrPut(key) {        val repository = com.cottondb.android.traffic.messages.ThreadDetailsRepository(core)        ThreadDetailPageModels(repository,            com.cottondb.android.traffic.messages.ThreadDetailsMutationModel(                com.cottondb.android.traffic.messages.RepositoryThreadDetailActionGateway(repository, threadId)),            com.cottondb.android.traffic.messages.ThreadPrivateFieldsModel(                com.cottondb.android.traffic.messages.RepositoryThreadPrivateFieldsGateway(repository, threadId)))    }    private val messagePages = mutableMapOf<String, MessagePageModels>()    fun messagesFor(key: String, threadId: String? = null) = messagePages.getOrPut(key) {        val repository = MessagesRepository(core)        MessagePageModels(repository, MessageArchiveModel(repository), ThreadActionsModel(repository), MessageSearchModel(repository), MessageStarModel(repository),            threadId?.let { MessageThreadModel(repository, it) })    }    fun callHistory(personId: String?) = CallHistoryModel(CallsRepository(core), personId)    fun callDetail(id: String) = CallDetailModel(CallsRepository(core), id)    private val noteEditors = mutableMapOf<String, NoteEditorModel>()    private val calendarEditors = mutableMapOf<String, CalendarEditorModel>()    private val goalCreations = mutableMapOf<String, GoalCreationModel>()    private val goalDetails = mutableMapOf<String, GoalDetailModel>()    private val goalLists = mutableMapOf<String, GoalsRepository>()    private val captures = mutableMapOf<String, CaptureModel>()    private val alarmLists = mutableMapOf<String, AlarmsRepository>()    private val alarmEditors = mutableMapOf<String, AlarmEditorModel>()    fun alarmsFor(key: String) = alarmLists.getOrPut(key) { AlarmsRepository(core) }    fun alarmEditor(key: String, initial: Alarm?, repository: AlarmsRepository) =        alarmEditors.getOrPut(key) { AlarmEditorModel(repository, initial) }    fun capture(key: String, voice: () -> CaptureVoice): CaptureModel =        captures.getOrPut(key) { CaptureModel(CaptureRepository(core), voice()) }    fun releaseCapture(key: String) { captures.remove(key)?.dispose() }    fun pauseCapture() { captures.values.forEach { it.dispose() } }    fun goals() = GoalsRepository(core)    fun goalsFor(key: String) = goalLists.getOrPut(key) { goals() }    fun goalCreation(key: String, repository: GoalsRepository) =        goalCreations.getOrPut(key) { GoalCreationModel(repository) }    fun goalDetail(key: String, id: String) =        goalDetails.getOrPut(key) { GoalDetailModel(goals(), id) }    fun calendarEditor(key: String, id: String?, occurrenceAt: String?, day: LocalDate, zone: java.time.ZoneId): CalendarEditorModel =        calendarEditors.getOrPut(key) { CalendarEditorModel(calendar(), id, occurrenceAt, day, zone) }    fun noteEditor(key: String, journalDate: String?, id: String?): NoteEditorModel =        noteEditors.getOrPut(key) { NoteEditorModel(notes(), journalDate = journalDate, id = id) }    /** Start writes while the process still has foreground time; each retained editor owns its result. */    fun flushNotes() = noteEditors.values.mapNotNull { it.flushPending(writerScope) }    fun flushGoals() = goalDetails.values.mapNotNull { it.flushPending(writerScope) }    private val _dataRevision = MutableStateFlow(0L)    val dataRevision = _dataRevision.asStateFlow()    fun handleEvent(event: CottonEvent) {        if (event.kind == "data") _dataRevision.value += 1    }    val timezone: String get() = clock.zone.id    fun today(): LocalDate = LocalDate.now(clock)    fun todos(): TodoRepository = TodoRepository(core)    fun thoughts(): ThoughtRepository = ThoughtRepository(core)    fun mood(): MoodRepository = MoodRepository(core)    fun calendar(): CalendarRepository = CalendarRepository(core)    fun notes(): NotesJournalRepository = NotesJournalRepository(core)}data class MessagePageModels(    val repository: MessagesRepository,    val archive: MessageArchiveModel,    val actions: ThreadActionsModel,    val search: MessageSearchModel,    val stars: MessageStarModel,    val thread: MessageThreadModel?,)data class ProjectPageModels(    val repository: com.cottondb.android.work.projects.ProjectsRepository,    val creation: com.cottondb.android.work.projects.ProjectCreationModel,    val editor: com.cottondb.android.work.projects.ProjectEditorModel?,)data class ThreadDetailPageModels(    val repository: com.cottondb.android.traffic.messages.ThreadDetailsRepository,    val destructive: com.cottondb.android.traffic.messages.ThreadDetailsMutationModel,    val privateFields: com.cottondb.android.traffic.messages.ThreadPrivateFieldsModel,)