Yokan / rebuild
Course 1 8624561

DetailViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModel.kt

implementation611 lines
1package eu.friedcutlet.yokan.ui.screens.detail23import kotlinx.coroutines.CoroutineDispatcher4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import eu.friedcutlet.yokan.data.LibraryIndex7import eu.friedcutlet.yokan.data.LibraryIndexStore8import eu.friedcutlet.yokan.data.SettingsStore9import eu.friedcutlet.yokan.data.YokanRepository10import eu.friedcutlet.yokan.data.observe11import eu.friedcutlet.yokan.data.toDb12import eu.friedcutlet.yokan.database.chapterReleasePreference13import eu.friedcutlet.yokan.database.withChapterReleasePreference14import eu.friedcutlet.yokan.database.withoutChapterReleaseOverride15import eu.friedcutlet.yokan.database.movedScanlator16import eu.friedcutlet.yokan.domain.equivalentReleaseIds17import eu.friedcutlet.yokan.domain.normalizeScanlator18import eu.friedcutlet.yokan.domain.selectChapterReleases19import kotlinx.coroutines.flow.distinctUntilChanged20import kotlinx.coroutines.flow.map21import eu.friedcutlet.yokan.database.DbSettings22import eu.friedcutlet.yokan.database.DbTrackSearch23import eu.friedcutlet.yokan.database.YokanDatabase24import eu.friedcutlet.yokan.domain.Category25import eu.friedcutlet.yokan.domain.Chapter26import eu.friedcutlet.yokan.domain.ChapterRecognition27import eu.friedcutlet.yokan.domain.ItemType28import eu.friedcutlet.yokan.domain.Manga29import eu.friedcutlet.yokan.domain.Source30import eu.friedcutlet.yokan.domain.Track31import eu.friedcutlet.yokan.domain.meanChapterUpdateDays32import eu.friedcutlet.yokan.services.catchingNonCancellation33import eu.friedcutlet.yokan.services.download.ChapterDownloads34import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory35import eu.friedcutlet.yokan.services.extensions.withSourceRuntime36import eu.friedcutlet.yokan.services.files.LocalFileService37import eu.friedcutlet.yokan.services.extensions.ExtensionLogger38import eu.friedcutlet.yokan.services.metadata.MetadataApplyResult39import eu.friedcutlet.yokan.services.metadata.MetadataService40import eu.friedcutlet.yokan.services.system.openSystemBrowser41import eu.friedcutlet.yokan.services.together.RoomState42import eu.friedcutlet.yokan.services.together.ProfileTogetherSession43import eu.friedcutlet.yokan.services.http.HttpService44import eu.friedcutlet.yokan.services.tracking.EnhancedTracker45import eu.friedcutlet.yokan.services.tracking.TrackerService46import eu.friedcutlet.yokan.services.tracking.trackerSearchId47import eu.friedcutlet.yokan.ui.screens.together.TogetherActions48import kotlinx.coroutines.Dispatchers49import kotlinx.coroutines.Job50import kotlinx.coroutines.channels.Channel51import kotlinx.coroutines.flow.Flow52import kotlinx.coroutines.flow.receiveAsFlow53import kotlinx.coroutines.flow.MutableStateFlow54import kotlinx.coroutines.flow.StateFlow55import kotlinx.coroutines.flow.asStateFlow56import kotlinx.coroutines.flow.combine57import kotlinx.coroutines.flow.filter58import kotlinx.coroutines.flow.filterNotNull59import kotlinx.coroutines.flow.first60import kotlinx.coroutines.flow.flowOn61import kotlinx.coroutines.flow.launchIn62import kotlinx.coroutines.flow.onEach63import kotlinx.coroutines.flow.update64import kotlinx.coroutines.launch65import kotlinx.coroutines.withContext66import eu.friedcutlet.yokan.services.library.ChapterFilterKind67import eu.friedcutlet.yokan.services.library.filterChapters68import eu.friedcutlet.yokan.services.library.scanlatorFilter69import eu.friedcutlet.yokan.services.library.sortedChapters70import eu.friedcutlet.yokan.services.library.withChapterFilterCycled71import eu.friedcutlet.yokan.services.library.withChapterListDefaultFrom72import eu.friedcutlet.yokan.services.library.withChapterSortToggled73import eu.friedcutlet.yokan.services.library.withScanlatorToggled7475/** What the detail screen shows about the title, rebuilt off the main thread when its data changes. */76internal data class DetailContent(77    val manga: Manga,78    val settings: DbSettings,79    val source: Source? = null,80    /** The title's chapters after its filters, in its sort order. */81    val chapters: List<Chapter> = emptyList(),82    /** First unread selected release in sort order, ignoring status filters; null when none are available. */83    val continueChapter: Chapter? = null,84    val scanlators: List<String> = emptyList(),85    val automaticUpdateDays: Int? = null,86    val missingChapterCount: Int = 0,87    val unnumberedChapterCount: Int = 0,88    val tracks: List<Track> = emptyList(),89    val categories: List<Category> = emptyList(),90    /** Installed, active sources of the title's type, its own source first. */91    val genreSources: List<Source> = emptyList(),92    /** False until the chapters were read once. */93    val loaded: Boolean = false,94    val seasons: List<Int> = emptyList(),95    /** Null selects all episodes, including episodes without a recognized season. */96    val selectedSeason: Int? = null,97    /** Season records of an Animetail Seasons-type title, in season order. */98    val seasonTitles: List<DetailSeasonTitle> = emptyList(),99)100101/** One season record with its own progress; [continueChapter] is its first unwatched episode. */102internal data class DetailSeasonTitle(103    val title: Manga,104    val episodeCount: Int,105    val watchedCount: Int,106    val continueChapter: Chapter?,107)108109internal data class TrackerSearchState(110    val loading: Boolean = false,111    val error: String? = null,112    val results: List<DbTrackSearch> = emptyList(),113)114115internal data class DetailState(116    val content: DetailContent,117    val trackerNames: List<String> = emptyList(),118    val selection: ChapterSelectionState = ChapterSelectionState(),119    val showAllReleases: Boolean = false,120    /** A detail or metadata refresh is running. */121    val loading: Boolean = false,122    val error: String? = null,123    val trackerSearch: TrackerSearchState = TrackerSearchState(),124    /** Null means closed; the draft is committed only by SaveNote. */125    val noteDraft: String? = null,126    /** The Together room the user is in, if any. */127    val togetherRoom: RoomState? = null,128    val selectedSeason: Int? = null,129)130131internal sealed interface DetailEvent {132    data object Refresh : DetailEvent133    data object RefreshMetadata : DetailEvent134    data object Share : DetailEvent135    data object ExportMetadata : DetailEvent136    data object EditNote : DetailEvent137    data class ChangeNote(val text: String) : DetailEvent138    data object SaveNote : DetailEvent139    data object CancelNote : DetailEvent140    data class SetFavorite(val favorite: Boolean) : DetailEvent141    /** Saves the title's categories, then favourites it when [favorite]. */142    data class SetCategories(val categoryIds: List<Long>, val favorite: Boolean) : DetailEvent143    data class SetDisplayTitle(val title: String) : DetailEvent144    class SetCustomCover(val bytes: ByteArray) : DetailEvent145    data class SetSmartUpdateDays(val days: Int?) : DetailEvent146    data class SetRead(val chapterIds: Set<Long>, val read: Boolean) : DetailEvent147    data class SetBookmarked(val chapterIds: Set<Long>, val bookmarked: Boolean) : DetailEvent148    /** Unbookmarks the selected bookmarked chapters, bookmarks the rest, and clears the selection. */149    data object ToggleSelectedBookmarks : DetailEvent150    /** Marks the selected read chapters unread, the rest read, and clears the selection. */151    data object ToggleSelectedRead : DetailEvent152    /** Manual filler mark; null clears it so the source value applies again. */153    data class SetFiller(val chapterIds: Set<Long>, val filler: Boolean?) : DetailEvent154    /** A null [destinationRoot] means the download folder selected in settings. */155    data class Download(val chapter: Chapter, val destinationRoot: String?) : DetailEvent156    data class DownloadAll(val chapters: List<Chapter>, val option: DetailDownloadOption, val destinationRoot: String?) : DetailEvent157    /** Deletes the selected chapters' downloads, or the local chapters; [removeEntry] removes the local title. */158    data class DeleteSelected(val removeEntry: Boolean) : DetailEvent159    data class ToggleSort(val index: Int) : DetailEvent160    data class CycleFilter(val kind: ChapterFilterKind) : DetailEvent161    /** Makes this title's sort and filters its media type's default; [applyToLibrary] resets library titles to it. */162    data class SetChapterListDefault(val applyToLibrary: Boolean) : DetailEvent163    data class ToggleScanlator(val scanlator: String) : DetailEvent164    data class SetSkipDuplicates(val enabled: Boolean) : DetailEvent165    data class MoveScanlator(val scanlator: String, val direction: Int) : DetailEvent166    data object ResetReleaseOverride : DetailEvent167    data class ShowAllReleases(val enabled: Boolean) : DetailEvent168    data class SelectSeason(val season: Int?) : DetailEvent169    data class Select(val option: ChapterSelectionOption) : DetailEvent170    data class ToggleSelection(val chapterId: Long) : DetailEvent171    data class SelectRangeTo(val chapterId: Long) : DetailEvent172    data class SelectRange(val first: Int, val last: Int) : DetailEvent173    data object ClearSelection : DetailEvent174    data class SearchTracker(val trackerIndex: Int, val query: String) : DetailEvent175    data class BindTrack(val trackerIndex: Int, val search: DbTrackSearch) : DetailEvent176    data object CloseTrackerSearch : DetailEvent177    /** Adds the title to the current Together room, or starts a room and emits [DetailEffect.OpenTogetherSettings]. */178    data object Together : DetailEvent179}180181internal sealed interface DetailEffect {182    data class ShowMessage(val text: String) : DetailEffect183    data object OpenTogetherSettings : DetailEffect184}185186/** State and actions of one title's detail page. */187internal class DetailViewModel(188    private val mangaId: Long,189    private val repository: YokanRepository,190    private val settings: SettingsStore,191    libraryIndex: LibraryIndexStore,192    private val downloads: ChapterDownloads,193    private val metadata: MetadataService,194    private val runtimeFactory: ExtensionRuntimeFactory,195    private val database: YokanDatabase,196    allTrackers: List<TrackerService>,197    private val files: LocalFileService,198    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,199    private val together: ProfileTogetherSession? = null,200    private val togetherHttp: HttpService? = null,201) : ViewModel() {202    /** Trackers for this title's media type; [TrackerSearchState] indexes refer to this list. */203    private val trackers = repository.manga(mangaId)?.itemType.let { type ->204        allTrackers.filter { it.supports(isManga = type != ItemType.Anime) }205    }206    private val trackerNames = trackers.map { it.name }207    private val _state = MutableStateFlow(208        repository.manga(mangaId)?.let { DetailState(DetailContent(it, settings.db.value), trackerNames) },209    )210211    /** Null when the title does not exist (any more). */212    val state: StateFlow<DetailState?> = _state.asStateFlow()213214    private val _effects = Channel<DetailEffect>(capacity = Channel.BUFFERED)215    val effects: Flow<DetailEffect> = _effects.receiveAsFlow()216217    private var trackerSearchJob: Job? = null218219    init {220        val title = repository.observe({ listOf(it.mangas, it.sources, it.categories, it.tracks) }, workDispatcher) { titleData(mangaId) }221        // The empty placeholder index would briefly show a title without chapters.222        combine(title, libraryIndex.index.filter { it !== LibraryIndex.Empty }, settings.db,223            _state.map { (it?.showAllReleases ?: false) to it?.selectedSeason }.distinctUntilChanged()) { data, index, db, options ->224            data?.let { detailContent(it, index, db, options.first, options.second) }225        }226            .flowOn(workDispatcher)227            .onEach { content ->228                _state.update { current ->229                    content ?: return@update null230                    current?.copy(231                        content = content,232                        selection = current.selection.retainVisible(content.chapters),233                        noteDraft = current.noteDraft.takeIf { content.manga.favorite },234                        selectedSeason = current.selectedSeason?.takeIf { it in content.seasons },235                    )236                        ?: DetailState(content, trackerNames)237                }238            }239            .launchIn(viewModelScope)240        together?.state241            ?.onEach { room -> _state.update { it?.copy(togetherRoom = room) } }242            ?.launchIn(viewModelScope)243        // Remote trackers report progress made elsewhere; server (enhanced) trackers sync it both ways.244        repository.refreshTracks(mangaId)245246        _state.value?.content?.manga?.let { autoRefreshMetadata(it) }247        viewModelScope.launch {248            // Titles opened from a source listing have no chapters until their detail is fetched.249            val first = _state.filterNotNull().first { it.content.loaded }.content250            if (first.continueChapter == null && first.seasonTitles.isEmpty() && first.source != null) refresh()251        }252    }253254    fun onEvent(event: DetailEvent) {255        val content = _state.value?.content ?: return256        val manga = content.manga257        when (event) {258            DetailEvent.Refresh -> refresh()259            DetailEvent.RefreshMetadata -> refreshMetadata(manga)260            DetailEvent.Share -> showMessage(261                if (openSystemBrowser(shareUrl(manga, content.source))) "Opened share URL." else "Could not open share URL.",262            )263            DetailEvent.ExportMetadata -> exportMetadata(manga)264            DetailEvent.EditNote -> {265                val saved = repository.manga(mangaId)?.takeIf { it.favorite } ?: return266                _state.update { it?.copy(noteDraft = saved.privateNote) }267            }268            is DetailEvent.ChangeNote -> _state.update { current ->269                current?.takeIf { it.noteDraft != null }?.copy(noteDraft = event.text) ?: current270            }271            DetailEvent.CancelNote -> _state.update { it?.copy(noteDraft = null) }272            DetailEvent.SaveNote -> {273                val draft = _state.value?.noteDraft ?: return274                repository.setMangaPrivateNote(mangaId, draft)275                _state.update { it?.copy(noteDraft = null) }276            }277            is DetailEvent.SetFavorite -> repository.setMangaFavorite(mangaId, event.favorite)278            is DetailEvent.SetCategories -> {279                // Explicit selections, including Uncategorized, always override an automatic default.280                repository.setMangaCategories(mangaId, event.categoryIds, favorite = event.favorite)281            }282            is DetailEvent.SetDisplayTitle -> repository.setMangaDisplayTitle(mangaId, event.title)283            is DetailEvent.SetCustomCover -> repository.setMangaCustomCover(mangaId, event.bytes)284            is DetailEvent.SetSmartUpdateDays -> repository.setMangaSmartUpdateDays(mangaId, event.days)285            is DetailEvent.SetRead -> if (event.chapterIds.isNotEmpty()) repository.setChaptersRead(releaseActionIds(event.chapterIds), event.read)286            is DetailEvent.SetBookmarked -> if (event.chapterIds.isNotEmpty()) repository.setChaptersBookmarked(releaseActionIds(event.chapterIds), event.bookmarked)287            DetailEvent.ToggleSelectedBookmarks -> toggleSelected(content, Chapter::isBookmarked) { ids, on -> repository.setChaptersBookmarked(ids, on) }288            DetailEvent.ToggleSelectedRead -> toggleSelected(content, Chapter::isRead) { ids, on -> repository.setChaptersRead(ids, on) }289            is DetailEvent.SetFiller -> if (event.chapterIds.isNotEmpty()) repository.setChaptersFillerOverride(releaseActionIds(event.chapterIds), event.filler)290            is DetailEvent.Download -> {291                downloads.enqueue(manga, event.chapter, event.destinationRoot)292                showMessage("Enqueued ${event.chapter.name}.")293            }294            is DetailEvent.DownloadAll -> downloadAll(content, event)295            is DetailEvent.DeleteSelected -> deleteSelected(event.removeEntry)296            is DetailEvent.ToggleSort -> settings.updateDb { it.withChapterSortToggled(manga, event.index) }297            is DetailEvent.CycleFilter -> settings.updateDb { it.withChapterFilterCycled(manga, event.kind) }298            is DetailEvent.SetChapterListDefault -> {299                val library = if (event.applyToLibrary) repository.library(manga.itemType) else emptyList()300                settings.updateDb { it.withChapterListDefaultFrom(manga, library) }301            }302            is DetailEvent.ToggleScanlator -> settings.updateDb { it.withScanlatorToggled(mangaId, event.scanlator) }303            is DetailEvent.SetSkipDuplicates -> settings.updateDb { db ->304                db.withChapterReleasePreference(db.chapterReleasePreference(mangaId).copy(skipDuplicateReleases = event.enabled))305            }306            is DetailEvent.MoveScanlator -> settings.updateDb { db ->307                val current = db.chapterReleasePreference(mangaId)308                db.withChapterReleasePreference(current.copy(scanlatorPriority = movedScanlator(current.scanlatorPriority,309                    content.scanlators, event.scanlator, event.direction)))310            }311            DetailEvent.ResetReleaseOverride -> settings.updateDb { it.withoutChapterReleaseOverride(mangaId) }312            is DetailEvent.ShowAllReleases -> _state.update { it?.copy(showAllReleases = event.enabled) }313            is DetailEvent.SelectSeason -> if (event.season == null || event.season in content.seasons) {314                _state.update { it?.copy(selectedSeason = event.season) }315            }316            is DetailEvent.Select -> updateSelection { it.select(content.chapters, event.option) }317            is DetailEvent.ToggleSelection -> updateSelection { it.toggle(event.chapterId) }318            is DetailEvent.SelectRangeTo -> updateSelection { it.rangeTo(content.chapters, event.chapterId) }319            is DetailEvent.SelectRange -> updateSelection { it.selectRange(content.chapters, event.first, event.last) }320            DetailEvent.ClearSelection -> updateSelection { ChapterSelectionState() }321            is DetailEvent.SearchTracker -> searchTracker(manga, event)322            is DetailEvent.BindTrack -> {323                val tracker = trackers.getOrNull(event.trackerIndex) ?: return324                repository.bindTrack(mangaId, event.search.copy(syncId = tracker.syncId), manga.itemType)325            }326            DetailEvent.CloseTrackerSearch -> {327                trackerSearchJob?.cancel()328                _state.update { it?.copy(trackerSearch = TrackerSearchState()) }329            }330            DetailEvent.Together -> together(content)331        }332    }333334    private fun refresh() {335        val content = _state.value?.content ?: return336        val source = content.source ?: return337        val manga = content.manga338        if (manga.link.isBlank()) return339        viewModelScope.launch {340            _state.update { it?.copy(loading = true, error = null) }341            catchingNonCancellation {342                val detail = runtimeFactory.withSourceRuntime(343                    database = database,344                    sourceId = source.id,345                    onFallback = { ExtensionLogger.error(source.name, "detail", it) },346                ) { it.detail(manga.link) }347                withContext(workDispatcher) { repository.upsertRemoteDetail(source, detail, favorite = manga.favorite) }348            }.onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } }349            _state.update { it?.copy(loading = false) }350        }351    }352353    private fun refreshMetadata(manga: Manga) {354        viewModelScope.launch {355            _state.update { it?.copy(loading = true, error = null) }356            catchingNonCancellation { applyMetadata(manga) }357                .onSuccess { result ->358                    showMessage(359                        if (result.applied && result.media != null) {360                            "Metadata updated from ${result.media.source.ifBlank { "server" }}."361                        } else {362                            result.message ?: "No metadata match found."363                        },364                    )365                }366                .onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } }367            _state.update { it?.copy(loading = false) }368        }369    }370371    // Opening a title with incomplete metadata fetches it once, silently, when a metadata server is on.372    private fun autoRefreshMetadata(manga: Manga) {373        if (!settings.db.value.metadataServerEnabled) return374        if (manga.metadataUpdatedAt > 0L && manga.alternativeTitles.size > 1 && manga.genres.isNotEmpty()) return375        viewModelScope.launch { catchingNonCancellation { applyMetadata(manga) } }376    }377378    private suspend fun applyMetadata(manga: Manga): MetadataApplyResult {379        val baseUrl = settings.db.value.metadataServerUrl.trim()380        if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {381            return MetadataApplyResult(manga.id, matched = false, message = "Metadata server URL must start with http:// or https://.")382        }383        val match = metadata.bestMatch(baseUrl, manga.name, manga.itemType.toDb())384            ?: return MetadataApplyResult(manga.id, matched = false, message = "No metadata match found.")385        withContext(workDispatcher) { repository.applyMetadata(manga.id, match) }386            ?: return MetadataApplyResult(manga.id, matched = true, media = match, message = "Title no longer exists.")387        return MetadataApplyResult(manga.id, matched = true, media = match, applied = true)388    }389390    private fun releaseActionIds(ids: Set<Long>): Set<Long> {391        val current = _state.value ?: return ids392        if (current.showAllReleases || !settings.db.value.chapterReleasePreference(mangaId).skipDuplicateReleases) return ids393        return equivalentReleaseIds(current.content.manga.name, repository.chapters(mangaId), ids)394    }395396    private fun downloadAll(content: DetailContent, event: DetailEvent.DownloadAll) {397        val itemType = content.manga.itemType398        val label = chapterLabel(itemType).lowercase()399        val visibleIds = content.chapters.mapTo(HashSet()) { it.id }400        val queueable = event.chapters.distinctBy { it.id }.filter { it.id in visibleIds && it.downloadSize == null && it.archivePath.isBlank() }401        if (queueable.isEmpty()) return showMessage("No $label to download.")402        queueable.forEach { downloads.enqueue(content.manga, it, event.destinationRoot) }403        showMessage("Enqueued ${queueable.size} $label for ${downloadOptionLabel(event.option, itemType).lowercase()}.")404    }405406    // Synchronous on purpose: the local-title path is followed by leaving the screen, which cancels407    // the scope, and must not stop between deleting the files and removing the entry.408    private fun deleteSelected(removeEntry: Boolean) {409        val current = _state.value ?: return410        val content = current.content411        val ids = current.selection.ids412        val label = chapterLabel(content.manga.itemType).lowercase()413        if (content.manga.isLocalArchive) {414            content.chapters415                .filter { it.id in ids && it.archivePath.isNotBlank() }416                .forEach { files.deleteRecursively(it.archivePath) }417            if (removeEntry) {418                repository.removeLibraryEntries(setOf(mangaId))419            } else {420                repository.deleteChapters(ids)421                showMessage("Deleted ${ids.size} $label.")422            }423        } else {424            viewModelScope.launch {425                val removed = downloads.deleteForChaptersAwait(ids)426                showMessage(427                    if (removed > 0) {428                        "Removed downloads for $removed $label" + if (removed == 1) "." else "s."429                    } else {430                        "No downloads removed. Check storage access if files remain."431                    },432                )433            }434        }435        updateSelection { ChapterSelectionState() }436    }437438    private fun exportMetadata(manga: Manga) {439        val path = "${files.downloadRoot.trimEnd('/')}/metadata/${manga.name.safeFileSegment()}/metadata.json"440        viewModelScope.launch {441            catchingNonCancellation {442                withContext(workDispatcher) { files.writeBytes(path, manga.toMetadataJson().encodeToByteArray()) }443            }444                .onSuccess { showMessage("Exported metadata to $path") }445                .onFailure { showMessage("Export metadata failed: ${it.displayMessage()}") }446        }447    }448449    private fun searchTracker(manga: Manga, event: DetailEvent.SearchTracker) {450        val tracker = trackers.getOrNull(event.trackerIndex) ?: return451        if (_state.value?.trackerSearch?.loading == true || event.query.isBlank()) return452        _state.update { it?.copy(trackerSearch = it.trackerSearch.copy(loading = true, error = null)) }453        trackerSearchJob = viewModelScope.launch {454            val result = catchingNonCancellation {455                val dbManga = database.manga(mangaId)456                if (tracker is EnhancedTracker && trackerSearchId(event.query) == null) {457                    // Server trackers are not searched: they resolve this title's own source entry.458                    listOfNotNull(dbManga?.let { tracker.match(it) })459                } else {460                    tracker.search(event.query, isManga = manga.itemType != ItemType.Anime)461                }462            }463            _state.update { current ->464                current?.copy(465                    trackerSearch = current.trackerSearch.copy(466                        loading = false,467                        results = result.getOrDefault(current.trackerSearch.results),468                        error = result.exceptionOrNull()?.let { it.message ?: "Search failed" },469                    ),470                )471            }472        }473    }474475    private fun together(content: DetailContent) {476        val controller = together ?: return477        val room = _state.value?.togetherRoom478        val client = controller.client.value479        if (room != null && client != null) {480            showMessage(TogetherActions.addToRoom(content.manga, content.continueChapter, room, client))481        } else {482            viewModelScope.launch {483                val http = togetherHttp ?: return@launch484                showMessage(TogetherActions.startRoom(controller, http, content.manga, content.continueChapter) {485                    _effects.trySend(DetailEffect.OpenTogetherSettings)486                })487            }488        }489    }490491    /** Turns the flag off for the selected chapters that have it and on for the rest. */492    private fun toggleSelected(content: DetailContent, flag: (Chapter) -> Boolean, apply: (Set<Long>, Boolean) -> Unit) {493        val ids = _state.value?.selection?.ids ?: return494        val (on, off) = content.chapters.filter { it.id in ids }.partition(flag)495        if (on.isNotEmpty()) apply(releaseActionIds(on.mapTo(HashSet()) { it.id }), false)496        if (off.isNotEmpty()) apply(releaseActionIds(off.mapTo(HashSet()) { it.id }), true)497        updateSelection { ChapterSelectionState() }498    }499500    private fun updateSelection(transform: (ChapterSelectionState) -> ChapterSelectionState) =501        _state.update { it?.copy(selection = transform(it.selection)) }502503    private fun showMessage(text: String) {504        _effects.trySend(DetailEffect.ShowMessage(text))505    }506}507508private class TitleData(509    val manga: Manga,510    val source: Source?,511    val genreSources: List<Source>,512    val categories: List<Category>,513    val tracks: List<Track>,514    val seasonTitles: List<Manga>,515)516517private fun YokanRepository.titleData(mangaId: Long): TitleData? {518    val manga = manga(mangaId) ?: return null519    val titleSource = if (manga.isLocalArchive) null else manga.sourceId?.let { this.source(it) }520    return TitleData(521        manga = manga,522        source = titleSource,523        genreSources = sources(manga.itemType)524            .filter { it.isAdded && it.isActive }525            .sortedWith(compareBy<Source> { it.id != titleSource?.id }.thenBy { it.name.lowercase() }.thenBy { it.lang }),526        categories = categories(manga.itemType),527        tracks = tracks().filter { it.mangaId == mangaId },528        // Only Seasons-type titles own season records; skip the full title scan for everything else.529        seasonTitles = if (!manga.fetchesSeasons) emptyList() else allTitles(manga.itemType)530            .filter { it.parentId == mangaId }531            .sortedWith(compareBy<Manga>({ it.seasonNumber ?: Double.MAX_VALUE }, { it.name.lowercase() })),532    )533}534535private fun detailContent(title: TitleData, index: LibraryIndex, db: DbSettings, showAllReleases: Boolean, selectedSeason: Int?): DetailContent {536    val manga = title.manga537    val all = sortedChapters(manga, index.chapters(manga.id), db)538    val seasons = if (manga.itemType == eu.friedcutlet.yokan.domain.ItemType.Anime) all.mapNotNull { it.detailSeason() }.distinct().sorted() else emptyList()539    val effectiveSeason = selectedSeason?.takeIf { it in seasons }540    val seasonChapters = if (effectiveSeason == null) all else all.filter { it.detailSeason() == effectiveSeason }541    val visible = filterChapters(manga, seasonChapters, db, index.downloadedChapterIds, showAllReleases)542    val winners = sortedChapters(manga, selectChapterReleases(manga.name, seasonChapters, db.chapterReleasePreference(manga.id).toPolicy(),543        db.scanlatorFilter(manga.id), index.downloadedChapterIds, offlineOnly = db.downloadedOnlyMode), db)544    return DetailContent(545        manga = manga,546        settings = db,547        source = title.source,548        chapters = visible,549        continueChapter = winners.firstOrNull { !it.isRead } ?: winners.firstOrNull(),550        scanlators = all.map { it.scanlator }.distinctBy(::normalizeScanlator).sortedBy(::normalizeScanlator),551        automaticUpdateDays = meanChapterUpdateDays(all.map { it.dateUpload }),552        missingChapterCount = ChapterRecognition.missingChapterCount(manga.name, visible),553        unnumberedChapterCount = ChapterRecognition.unrecognizedChapterNumberCount(manga.name, visible),554        tracks = title.tracks,555        categories = title.categories,556        genreSources = title.genreSources,557        loaded = true,558        seasons = seasons,559        selectedSeason = effectiveSeason,560        seasonTitles = title.seasonTitles.map { season ->561            val episodes = sortedChapters(season, index.chapters(season.id), db)562            DetailSeasonTitle(season, episodes.size, episodes.count { it.isRead }, episodes.firstOrNull { !it.isRead })563        },564    )565}566567private fun Chapter.detailSeason(): Int? = season?.takeIf { it >= 0 }568    ?: ChapterRecognition.parseSeasonNumber(numberingName?.takeIf(String::isNotBlank) ?: name)569570private fun Throwable.displayMessage(): String = message.orEmpty().ifBlank { this::class.simpleName.orEmpty() }571572private fun shareUrl(manga: Manga, source: Source?): String {573    if (manga.link.startsWith("http", ignoreCase = true)) return manga.link574    val base = source?.baseUrl?.takeIf { it.isNotBlank() } ?: return manga.link575    return "${base.trimEnd('/')}/${manga.link.trimStart('/')}"576}577578private fun Manga.toMetadataJson(): String =579    buildString {580        appendLine("{")581        appendLine("  \"name\": \"${name.jsonEscaped()}\",")582        appendLine("  \"description\": \"${description.jsonEscaped()}\",")583        appendLine("  \"artist\": ${artist.jsonStringOrNull()},")584        appendLine("  \"author\": ${author.jsonStringOrNull()},")585        appendLine("  \"genre\": [${genres.joinToString(", ") { "\"${it.jsonEscaped()}\"" }}],")586        appendLine("  \"cast\": ${eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(kotlinx.serialization.builtins.ListSerializer(eu.friedcutlet.yokan.domain.TitleCredit.serializer()), cast)},")587        appendLine("  \"status\": \"${status.name.jsonEscaped()}\"")588        appendLine("}")589    }590591private fun String?.jsonStringOrNull(): String =592    this?.let { "\"${it.jsonEscaped()}\"" } ?: "null"593594private fun String.jsonEscaped(): String = buildString {595    this@jsonEscaped.forEach { char ->596        when (char) {597            '\\' -> append("\\\\")598            '"' -> append("\\\"")599            '\n' -> append("\\n")600            '\r' -> append("\\r")601            '\t' -> append("\\t")602            else -> append(char)603        }604    }605}606607private fun String.safeFileSegment(): String =608    replace(Regex("""[\\/:*?"<>|]+"""), "_")609        .trim()610        .take(80)611        .ifBlank { "metadata" }612

Search chapters, reference and source filenames.