NovelReaderViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.novel23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.LibraryIndexStore6import eu.friedcutlet.yokan.data.SettingsStore7import eu.friedcutlet.yokan.data.YokanRepository8import eu.friedcutlet.yokan.database.DbSettings9import eu.friedcutlet.yokan.database.isIncognitoFor10import eu.friedcutlet.yokan.domain.Chapter11import eu.friedcutlet.yokan.domain.Manga12import eu.friedcutlet.yokan.domain.Source13import eu.friedcutlet.yokan.services.catchingNonCancellation14import eu.friedcutlet.yokan.services.extensions.webViewUserAgent15import eu.friedcutlet.yokan.services.library.readingChapterSequence16import eu.friedcutlet.yokan.services.tts.ProfileSpeechService17import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest18import eu.friedcutlet.yokan.ui.screens.ReadingSessionClock19import eu.friedcutlet.yokan.ui.screens.reader.autoScrollSettings20import eu.friedcutlet.yokan.ui.screens.reader.withAutoScrollSettings21import kotlinx.coroutines.CoroutineDispatcher22import kotlinx.coroutines.Dispatchers23import kotlinx.coroutines.flow.MutableStateFlow24import kotlinx.coroutines.flow.StateFlow25import kotlinx.coroutines.flow.asStateFlow26import kotlinx.coroutines.flow.combine27import kotlinx.coroutines.flow.distinctUntilChanged28import kotlinx.coroutines.flow.flowOn29import kotlinx.coroutines.flow.map30import kotlinx.coroutines.flow.update31import kotlinx.coroutines.launch32import kotlinx.coroutines.withContext3334/**35 * One novel chapter: library reads/writes, content loading, reading time, auto-scroll preferences36 * and text-to-speech. Scroll position and layout stay in the screen.37 */38internal class NovelReaderViewModel(39 private val manga: Manga,40 chapter: Chapter,41 private val repository: YokanRepository,42 private val settings: SettingsStore,43 libraryIndex: LibraryIndexStore,44 speech: ProfileSpeechService,45 loadHeaders: suspend (Source) -> Map<String, String>,46 loadDocument: suspend (Source?, Chapter) -> NovelDocument,47 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,48) : ViewModel() {4950 private val _state = MutableStateFlow(51 settings.db.value.autoScrollSettings(manga.id).let { autoScroll ->52 NovelReaderState(53 chapter = chapter,54 source = manga.sourceId?.let(repository::source),55 autoScrollEnabled = autoScroll.autoScroll,56 autoScrollPlaying = autoScroll.autoScroll,57 autoScrollOffset = autoScroll.pageOffset.toFloat(),58 )59 },60 )61 val state: StateFlow<NovelReaderState> = _state.asStateFlow()6263 private val clock = ReadingSessionClock()64 private val speechReader = speech.reader()65 private val tts = NovelTtsController(speechReader, viewModelScope) { speechReader.isAvailable }6667 init {68 repository.chapterOpened(chapter.id)69 viewModelScope.launch {70 combine(libraryIndex.index, settings.db) { index, db ->71 readingChapterSequence(manga, chapter.id, index.chapters(manga.id), db, index.downloadedChapterIds)72 }73 .flowOn(workDispatcher)74 .collect { all ->75 val position = all.indexOfFirst { it.id == chapter.id }76 _state.update {77 it.copy(78 previousChapter = if (position > 0) all[position - 1] else null,79 nextChapter = if (position >= 0) all.getOrNull(position + 1) else null,80 )81 }82 }83 }84 viewModelScope.launch { load(loadHeaders, loadDocument) }85 viewModelScope.launch { tts.state.collect { speech -> _state.update { it.copy(tts = speech) } } }86 // Voice/rate changes apply to the utterance in progress.87 viewModelScope.launch {88 settings.db.map { it.ttsRequest() }.distinctUntilChanged().collect { request ->89 if (tts.state.value.playback != NovelTtsPlaybackState.Stopped) tts.updateRequest(request)90 }91 }92 }9394 override fun onCleared() {95 tts.retire()96 speechReader.retire()97 repository.chapterClosed(state.value.chapter.id)98 super.onCleared()99 }100101 fun onEvent(event: NovelReaderEvent) {102 when (event) {103 NovelReaderEvent.ToggleBookmark -> toggleBookmark()104 NovelReaderEvent.ReadingPaused -> clock.pause()105 NovelReaderEvent.ReadingResumed -> clock.resume()106 is NovelReaderEvent.SaveProgress -> {107 clock.pause()108 saveProgress(event.ratio, clock.takeSeconds())109 }110 is NovelReaderEvent.SetAutoScrollEnabled -> {111 _state.update { it.copy(autoScrollEnabled = event.enabled, autoScrollPlaying = event.enabled) }112 val offset = state.value.autoScrollOffset.toDouble()113 settings.updateDb { it.withAutoScrollSettings(manga.id, event.enabled, offset) }114 }115 is NovelReaderEvent.SetAutoScrollOffset -> {116 _state.update { it.copy(autoScrollOffset = event.offset) }117 settings.updateDb { it.withAutoScrollSettings(manga.id, true, event.offset.toDouble()) }118 }119 NovelReaderEvent.ToggleAutoScrollPlaying -> _state.update { it.copy(autoScrollPlaying = !it.autoScrollPlaying) }120 is NovelReaderEvent.StartTts -> viewModelScope.launch {121 tts.start(event.paragraphs, settings.db.value.ttsRequest())122 }123 NovelReaderEvent.ToggleTtsPlayback -> viewModelScope.launch {124 if (tts.state.value.playback == NovelTtsPlaybackState.Playing) tts.pause() else tts.resume()125 }126 NovelReaderEvent.SkipNextTts -> viewModelScope.launch { tts.skipNext() }127 NovelReaderEvent.SkipPreviousTts -> viewModelScope.launch { tts.skipPrevious() }128 NovelReaderEvent.StopTts -> viewModelScope.launch { tts.stop() }129 }130 }131132 private suspend fun load(133 loadHeaders: suspend (Source) -> Map<String, String>,134 loadDocument: suspend (Source?, Chapter) -> NovelDocument,135 ) {136 val chapter = state.value.chapter137 val source = state.value.source138 val headers = source?.let { current ->139 val loaded = catchingNonCancellation { withContext(workDispatcher) { loadHeaders(current) } }140 .getOrDefault(emptyMap())141 val userAgent = settings.db.value.webViewUserAgent(current)142 if (userAgent.isBlank() || loaded.keys.any { it.equals("User-Agent", ignoreCase = true) }) loaded143 else loaded + ("User-Agent" to userAgent)144 }.orEmpty()145 var error: String? = null146 val document = catchingNonCancellation { withContext(workDispatcher) { loadDocument(source, chapter) } }147 .getOrElse { throwable ->148 error = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }149 NovelDocument(chapter.description ?: manga.description)150 }151 _state.update { it.copy(document = document, imageHeaders = headers, loading = false, error = error) }152 }153154 private fun toggleBookmark() {155 val chapter = state.value.chapter156 repository.setChaptersBookmarked(setOf(chapter.id), !chapter.isBookmarked)157 _state.update { it.copy(chapter = it.chapter.copy(isBookmarked = !chapter.isBookmarked)) }158 }159160 /** Saves the scroll ratio; incognito sessions leave no trace. */161 private fun saveProgress(ratio: Double, readingTimeSeconds: Int) {162 if (settings.db.value.isIncognitoFor(manga.sourceId)) return163 val chapterId = state.value.chapter.id164 repository.setChaptersRead(165 chapterIds = setOf(chapterId),166 isRead = novelProgressIsRead(ratio),167 lastPageRead = ratio.toString(),168 readingTimeSeconds = readingTimeSeconds,169 )170 if (novelProgressIsRead(ratio)) repository.recordChapterConsumption(setOf(chapterId))171 }172}173174private fun DbSettings.ttsRequest() = TextToSpeechRequest(175 language = ttsLanguage,176 voice = ttsVoice,177 speechRate = ttsSpeechRate,178 pitch = ttsPitch,179)180