package eu.friedcutlet.yokan.ui.screens.detail import kotlinx.coroutines.CoroutineDispatcher import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.LibraryIndex import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.observe import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.database.chapterReleasePreference import eu.friedcutlet.yokan.database.withChapterReleasePreference import eu.friedcutlet.yokan.database.withoutChapterReleaseOverride import eu.friedcutlet.yokan.database.movedScanlator import eu.friedcutlet.yokan.domain.equivalentReleaseIds import eu.friedcutlet.yokan.domain.normalizeScanlator import eu.friedcutlet.yokan.domain.selectChapterReleases import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Category import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ChapterRecognition import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.domain.Track import eu.friedcutlet.yokan.domain.meanChapterUpdateDays import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.withSourceRuntime import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.extensions.ExtensionLogger import eu.friedcutlet.yokan.services.metadata.MetadataApplyResult import eu.friedcutlet.yokan.services.metadata.MetadataService import eu.friedcutlet.yokan.services.system.openSystemBrowser import eu.friedcutlet.yokan.services.together.RoomState import eu.friedcutlet.yokan.services.together.ProfileTogetherSession import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.tracking.EnhancedTracker import eu.friedcutlet.yokan.services.tracking.TrackerService import eu.friedcutlet.yokan.services.tracking.trackerSearchId import eu.friedcutlet.yokan.ui.screens.together.TogetherActions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import eu.friedcutlet.yokan.services.library.ChapterFilterKind import eu.friedcutlet.yokan.services.library.filterChapters import eu.friedcutlet.yokan.services.library.scanlatorFilter import eu.friedcutlet.yokan.services.library.sortedChapters import eu.friedcutlet.yokan.services.library.withChapterFilterCycled import eu.friedcutlet.yokan.services.library.withChapterListDefaultFrom import eu.friedcutlet.yokan.services.library.withChapterSortToggled import eu.friedcutlet.yokan.services.library.withScanlatorToggled /** What the detail screen shows about the title, rebuilt off the main thread when its data changes. */ internal data class DetailContent( val manga: Manga, val settings: DbSettings, val source: Source? = null, /** The title's chapters after its filters, in its sort order. */ val chapters: List = emptyList(), /** First unread selected release in sort order, ignoring status filters; null when none are available. */ val continueChapter: Chapter? = null, val scanlators: List = emptyList(), val automaticUpdateDays: Int? = null, val missingChapterCount: Int = 0, val unnumberedChapterCount: Int = 0, val tracks: List = emptyList(), val categories: List = emptyList(), /** Installed, active sources of the title's type, its own source first. */ val genreSources: List = emptyList(), /** False until the chapters were read once. */ val loaded: Boolean = false, val seasons: List = emptyList(), /** Null selects all episodes, including episodes without a recognized season. */ val selectedSeason: Int? = null, /** Season records of an Animetail Seasons-type title, in season order. */ val seasonTitles: List = emptyList(), ) /** One season record with its own progress; [continueChapter] is its first unwatched episode. */ internal data class DetailSeasonTitle( val title: Manga, val episodeCount: Int, val watchedCount: Int, val continueChapter: Chapter?, ) internal data class TrackerSearchState( val loading: Boolean = false, val error: String? = null, val results: List = emptyList(), ) internal data class DetailState( val content: DetailContent, val trackerNames: List = emptyList(), val selection: ChapterSelectionState = ChapterSelectionState(), val showAllReleases: Boolean = false, /** A detail or metadata refresh is running. */ val loading: Boolean = false, val error: String? = null, val trackerSearch: TrackerSearchState = TrackerSearchState(), /** Null means closed; the draft is committed only by SaveNote. */ val noteDraft: String? = null, /** The Together room the user is in, if any. */ val togetherRoom: RoomState? = null, val selectedSeason: Int? = null, ) internal sealed interface DetailEvent { data object Refresh : DetailEvent data object RefreshMetadata : DetailEvent data object Share : DetailEvent data object ExportMetadata : DetailEvent data object EditNote : DetailEvent data class ChangeNote(val text: String) : DetailEvent data object SaveNote : DetailEvent data object CancelNote : DetailEvent data class SetFavorite(val favorite: Boolean) : DetailEvent /** Saves the title's categories, then favourites it when [favorite]. */ data class SetCategories(val categoryIds: List, val favorite: Boolean) : DetailEvent data class SetDisplayTitle(val title: String) : DetailEvent class SetCustomCover(val bytes: ByteArray) : DetailEvent data class SetSmartUpdateDays(val days: Int?) : DetailEvent data class SetRead(val chapterIds: Set, val read: Boolean) : DetailEvent data class SetBookmarked(val chapterIds: Set, val bookmarked: Boolean) : DetailEvent /** Unbookmarks the selected bookmarked chapters, bookmarks the rest, and clears the selection. */ data object ToggleSelectedBookmarks : DetailEvent /** Marks the selected read chapters unread, the rest read, and clears the selection. */ data object ToggleSelectedRead : DetailEvent /** Manual filler mark; null clears it so the source value applies again. */ data class SetFiller(val chapterIds: Set, val filler: Boolean?) : DetailEvent /** A null [destinationRoot] means the download folder selected in settings. */ data class Download(val chapter: Chapter, val destinationRoot: String?) : DetailEvent data class DownloadAll(val chapters: List, val option: DetailDownloadOption, val destinationRoot: String?) : DetailEvent /** Deletes the selected chapters' downloads, or the local chapters; [removeEntry] removes the local title. */ data class DeleteSelected(val removeEntry: Boolean) : DetailEvent data class ToggleSort(val index: Int) : DetailEvent data class CycleFilter(val kind: ChapterFilterKind) : DetailEvent /** Makes this title's sort and filters its media type's default; [applyToLibrary] resets library titles to it. */ data class SetChapterListDefault(val applyToLibrary: Boolean) : DetailEvent data class ToggleScanlator(val scanlator: String) : DetailEvent data class SetSkipDuplicates(val enabled: Boolean) : DetailEvent data class MoveScanlator(val scanlator: String, val direction: Int) : DetailEvent data object ResetReleaseOverride : DetailEvent data class ShowAllReleases(val enabled: Boolean) : DetailEvent data class SelectSeason(val season: Int?) : DetailEvent data class Select(val option: ChapterSelectionOption) : DetailEvent data class ToggleSelection(val chapterId: Long) : DetailEvent data class SelectRangeTo(val chapterId: Long) : DetailEvent data class SelectRange(val first: Int, val last: Int) : DetailEvent data object ClearSelection : DetailEvent data class SearchTracker(val trackerIndex: Int, val query: String) : DetailEvent data class BindTrack(val trackerIndex: Int, val search: DbTrackSearch) : DetailEvent data object CloseTrackerSearch : DetailEvent /** Adds the title to the current Together room, or starts a room and emits [DetailEffect.OpenTogetherSettings]. */ data object Together : DetailEvent } internal sealed interface DetailEffect { data class ShowMessage(val text: String) : DetailEffect data object OpenTogetherSettings : DetailEffect } /** State and actions of one title's detail page. */ internal class DetailViewModel( private val mangaId: Long, private val repository: YokanRepository, private val settings: SettingsStore, libraryIndex: LibraryIndexStore, private val downloads: ChapterDownloads, private val metadata: MetadataService, private val runtimeFactory: ExtensionRuntimeFactory, private val database: YokanDatabase, allTrackers: List, private val files: LocalFileService, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, private val together: ProfileTogetherSession? = null, private val togetherHttp: HttpService? = null, ) : ViewModel() { /** Trackers for this title's media type; [TrackerSearchState] indexes refer to this list. */ private val trackers = repository.manga(mangaId)?.itemType.let { type -> allTrackers.filter { it.supports(isManga = type != ItemType.Anime) } } private val trackerNames = trackers.map { it.name } private val _state = MutableStateFlow( repository.manga(mangaId)?.let { DetailState(DetailContent(it, settings.db.value), trackerNames) }, ) /** Null when the title does not exist (any more). */ val state: StateFlow = _state.asStateFlow() private val _effects = Channel(capacity = Channel.BUFFERED) val effects: Flow = _effects.receiveAsFlow() private var trackerSearchJob: Job? = null init { val title = repository.observe({ listOf(it.mangas, it.sources, it.categories, it.tracks) }, workDispatcher) { titleData(mangaId) } // The empty placeholder index would briefly show a title without chapters. combine(title, libraryIndex.index.filter { it !== LibraryIndex.Empty }, settings.db, _state.map { (it?.showAllReleases ?: false) to it?.selectedSeason }.distinctUntilChanged()) { data, index, db, options -> data?.let { detailContent(it, index, db, options.first, options.second) } } .flowOn(workDispatcher) .onEach { content -> _state.update { current -> content ?: return@update null current?.copy( content = content, selection = current.selection.retainVisible(content.chapters), noteDraft = current.noteDraft.takeIf { content.manga.favorite }, selectedSeason = current.selectedSeason?.takeIf { it in content.seasons }, ) ?: DetailState(content, trackerNames) } } .launchIn(viewModelScope) together?.state ?.onEach { room -> _state.update { it?.copy(togetherRoom = room) } } ?.launchIn(viewModelScope) // Remote trackers report progress made elsewhere; server (enhanced) trackers sync it both ways. repository.refreshTracks(mangaId) _state.value?.content?.manga?.let { autoRefreshMetadata(it) } viewModelScope.launch { // Titles opened from a source listing have no chapters until their detail is fetched. val first = _state.filterNotNull().first { it.content.loaded }.content if (first.continueChapter == null && first.seasonTitles.isEmpty() && first.source != null) refresh() } } fun onEvent(event: DetailEvent) { val content = _state.value?.content ?: return val manga = content.manga when (event) { DetailEvent.Refresh -> refresh() DetailEvent.RefreshMetadata -> refreshMetadata(manga) DetailEvent.Share -> showMessage( if (openSystemBrowser(shareUrl(manga, content.source))) "Opened share URL." else "Could not open share URL.", ) DetailEvent.ExportMetadata -> exportMetadata(manga) DetailEvent.EditNote -> { val saved = repository.manga(mangaId)?.takeIf { it.favorite } ?: return _state.update { it?.copy(noteDraft = saved.privateNote) } } is DetailEvent.ChangeNote -> _state.update { current -> current?.takeIf { it.noteDraft != null }?.copy(noteDraft = event.text) ?: current } DetailEvent.CancelNote -> _state.update { it?.copy(noteDraft = null) } DetailEvent.SaveNote -> { val draft = _state.value?.noteDraft ?: return repository.setMangaPrivateNote(mangaId, draft) _state.update { it?.copy(noteDraft = null) } } is DetailEvent.SetFavorite -> repository.setMangaFavorite(mangaId, event.favorite) is DetailEvent.SetCategories -> { // Explicit selections, including Uncategorized, always override an automatic default. repository.setMangaCategories(mangaId, event.categoryIds, favorite = event.favorite) } is DetailEvent.SetDisplayTitle -> repository.setMangaDisplayTitle(mangaId, event.title) is DetailEvent.SetCustomCover -> repository.setMangaCustomCover(mangaId, event.bytes) is DetailEvent.SetSmartUpdateDays -> repository.setMangaSmartUpdateDays(mangaId, event.days) is DetailEvent.SetRead -> if (event.chapterIds.isNotEmpty()) repository.setChaptersRead(releaseActionIds(event.chapterIds), event.read) is DetailEvent.SetBookmarked -> if (event.chapterIds.isNotEmpty()) repository.setChaptersBookmarked(releaseActionIds(event.chapterIds), event.bookmarked) DetailEvent.ToggleSelectedBookmarks -> toggleSelected(content, Chapter::isBookmarked) { ids, on -> repository.setChaptersBookmarked(ids, on) } DetailEvent.ToggleSelectedRead -> toggleSelected(content, Chapter::isRead) { ids, on -> repository.setChaptersRead(ids, on) } is DetailEvent.SetFiller -> if (event.chapterIds.isNotEmpty()) repository.setChaptersFillerOverride(releaseActionIds(event.chapterIds), event.filler) is DetailEvent.Download -> { downloads.enqueue(manga, event.chapter, event.destinationRoot) showMessage("Enqueued ${event.chapter.name}.") } is DetailEvent.DownloadAll -> downloadAll(content, event) is DetailEvent.DeleteSelected -> deleteSelected(event.removeEntry) is DetailEvent.ToggleSort -> settings.updateDb { it.withChapterSortToggled(manga, event.index) } is DetailEvent.CycleFilter -> settings.updateDb { it.withChapterFilterCycled(manga, event.kind) } is DetailEvent.SetChapterListDefault -> { val library = if (event.applyToLibrary) repository.library(manga.itemType) else emptyList() settings.updateDb { it.withChapterListDefaultFrom(manga, library) } } is DetailEvent.ToggleScanlator -> settings.updateDb { it.withScanlatorToggled(mangaId, event.scanlator) } is DetailEvent.SetSkipDuplicates -> settings.updateDb { db -> db.withChapterReleasePreference(db.chapterReleasePreference(mangaId).copy(skipDuplicateReleases = event.enabled)) } is DetailEvent.MoveScanlator -> settings.updateDb { db -> val current = db.chapterReleasePreference(mangaId) db.withChapterReleasePreference(current.copy(scanlatorPriority = movedScanlator(current.scanlatorPriority, content.scanlators, event.scanlator, event.direction))) } DetailEvent.ResetReleaseOverride -> settings.updateDb { it.withoutChapterReleaseOverride(mangaId) } is DetailEvent.ShowAllReleases -> _state.update { it?.copy(showAllReleases = event.enabled) } is DetailEvent.SelectSeason -> if (event.season == null || event.season in content.seasons) { _state.update { it?.copy(selectedSeason = event.season) } } is DetailEvent.Select -> updateSelection { it.select(content.chapters, event.option) } is DetailEvent.ToggleSelection -> updateSelection { it.toggle(event.chapterId) } is DetailEvent.SelectRangeTo -> updateSelection { it.rangeTo(content.chapters, event.chapterId) } is DetailEvent.SelectRange -> updateSelection { it.selectRange(content.chapters, event.first, event.last) } DetailEvent.ClearSelection -> updateSelection { ChapterSelectionState() } is DetailEvent.SearchTracker -> searchTracker(manga, event) is DetailEvent.BindTrack -> { val tracker = trackers.getOrNull(event.trackerIndex) ?: return repository.bindTrack(mangaId, event.search.copy(syncId = tracker.syncId), manga.itemType) } DetailEvent.CloseTrackerSearch -> { trackerSearchJob?.cancel() _state.update { it?.copy(trackerSearch = TrackerSearchState()) } } DetailEvent.Together -> together(content) } } private fun refresh() { val content = _state.value?.content ?: return val source = content.source ?: return val manga = content.manga if (manga.link.isBlank()) return viewModelScope.launch { _state.update { it?.copy(loading = true, error = null) } catchingNonCancellation { val detail = runtimeFactory.withSourceRuntime( database = database, sourceId = source.id, onFallback = { ExtensionLogger.error(source.name, "detail", it) }, ) { it.detail(manga.link) } withContext(workDispatcher) { repository.upsertRemoteDetail(source, detail, favorite = manga.favorite) } }.onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } } _state.update { it?.copy(loading = false) } } } private fun refreshMetadata(manga: Manga) { viewModelScope.launch { _state.update { it?.copy(loading = true, error = null) } catchingNonCancellation { applyMetadata(manga) } .onSuccess { result -> showMessage( if (result.applied && result.media != null) { "Metadata updated from ${result.media.source.ifBlank { "server" }}." } else { result.message ?: "No metadata match found." }, ) } .onFailure { error -> _state.update { it?.copy(error = error.displayMessage()) } } _state.update { it?.copy(loading = false) } } } // Opening a title with incomplete metadata fetches it once, silently, when a metadata server is on. private fun autoRefreshMetadata(manga: Manga) { if (!settings.db.value.metadataServerEnabled) return if (manga.metadataUpdatedAt > 0L && manga.alternativeTitles.size > 1 && manga.genres.isNotEmpty()) return viewModelScope.launch { catchingNonCancellation { applyMetadata(manga) } } } private suspend fun applyMetadata(manga: Manga): MetadataApplyResult { val baseUrl = settings.db.value.metadataServerUrl.trim() if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) { return MetadataApplyResult(manga.id, matched = false, message = "Metadata server URL must start with http:// or https://.") } val match = metadata.bestMatch(baseUrl, manga.name, manga.itemType.toDb()) ?: return MetadataApplyResult(manga.id, matched = false, message = "No metadata match found.") withContext(workDispatcher) { repository.applyMetadata(manga.id, match) } ?: return MetadataApplyResult(manga.id, matched = true, media = match, message = "Title no longer exists.") return MetadataApplyResult(manga.id, matched = true, media = match, applied = true) } private fun releaseActionIds(ids: Set): Set { val current = _state.value ?: return ids if (current.showAllReleases || !settings.db.value.chapterReleasePreference(mangaId).skipDuplicateReleases) return ids return equivalentReleaseIds(current.content.manga.name, repository.chapters(mangaId), ids) } private fun downloadAll(content: DetailContent, event: DetailEvent.DownloadAll) { val itemType = content.manga.itemType val label = chapterLabel(itemType).lowercase() val visibleIds = content.chapters.mapTo(HashSet()) { it.id } val queueable = event.chapters.distinctBy { it.id }.filter { it.id in visibleIds && it.downloadSize == null && it.archivePath.isBlank() } if (queueable.isEmpty()) return showMessage("No $label to download.") queueable.forEach { downloads.enqueue(content.manga, it, event.destinationRoot) } showMessage("Enqueued ${queueable.size} $label for ${downloadOptionLabel(event.option, itemType).lowercase()}.") } // Synchronous on purpose: the local-title path is followed by leaving the screen, which cancels // the scope, and must not stop between deleting the files and removing the entry. private fun deleteSelected(removeEntry: Boolean) { val current = _state.value ?: return val content = current.content val ids = current.selection.ids val label = chapterLabel(content.manga.itemType).lowercase() if (content.manga.isLocalArchive) { content.chapters .filter { it.id in ids && it.archivePath.isNotBlank() } .forEach { files.deleteRecursively(it.archivePath) } if (removeEntry) { repository.removeLibraryEntries(setOf(mangaId)) } else { repository.deleteChapters(ids) showMessage("Deleted ${ids.size} $label.") } } else { viewModelScope.launch { val removed = downloads.deleteForChaptersAwait(ids) showMessage( if (removed > 0) { "Removed downloads for $removed $label" + if (removed == 1) "." else "s." } else { "No downloads removed. Check storage access if files remain." }, ) } } updateSelection { ChapterSelectionState() } } private fun exportMetadata(manga: Manga) { val path = "${files.downloadRoot.trimEnd('/')}/metadata/${manga.name.safeFileSegment()}/metadata.json" viewModelScope.launch { catchingNonCancellation { withContext(workDispatcher) { files.writeBytes(path, manga.toMetadataJson().encodeToByteArray()) } } .onSuccess { showMessage("Exported metadata to $path") } .onFailure { showMessage("Export metadata failed: ${it.displayMessage()}") } } } private fun searchTracker(manga: Manga, event: DetailEvent.SearchTracker) { val tracker = trackers.getOrNull(event.trackerIndex) ?: return if (_state.value?.trackerSearch?.loading == true || event.query.isBlank()) return _state.update { it?.copy(trackerSearch = it.trackerSearch.copy(loading = true, error = null)) } trackerSearchJob = viewModelScope.launch { val result = catchingNonCancellation { val dbManga = database.manga(mangaId) if (tracker is EnhancedTracker && trackerSearchId(event.query) == null) { // Server trackers are not searched: they resolve this title's own source entry. listOfNotNull(dbManga?.let { tracker.match(it) }) } else { tracker.search(event.query, isManga = manga.itemType != ItemType.Anime) } } _state.update { current -> current?.copy( trackerSearch = current.trackerSearch.copy( loading = false, results = result.getOrDefault(current.trackerSearch.results), error = result.exceptionOrNull()?.let { it.message ?: "Search failed" }, ), ) } } } private fun together(content: DetailContent) { val controller = together ?: return val room = _state.value?.togetherRoom val client = controller.client.value if (room != null && client != null) { showMessage(TogetherActions.addToRoom(content.manga, content.continueChapter, room, client)) } else { viewModelScope.launch { val http = togetherHttp ?: return@launch showMessage(TogetherActions.startRoom(controller, http, content.manga, content.continueChapter) { _effects.trySend(DetailEffect.OpenTogetherSettings) }) } } } /** Turns the flag off for the selected chapters that have it and on for the rest. */ private fun toggleSelected(content: DetailContent, flag: (Chapter) -> Boolean, apply: (Set, Boolean) -> Unit) { val ids = _state.value?.selection?.ids ?: return val (on, off) = content.chapters.filter { it.id in ids }.partition(flag) if (on.isNotEmpty()) apply(releaseActionIds(on.mapTo(HashSet()) { it.id }), false) if (off.isNotEmpty()) apply(releaseActionIds(off.mapTo(HashSet()) { it.id }), true) updateSelection { ChapterSelectionState() } } private fun updateSelection(transform: (ChapterSelectionState) -> ChapterSelectionState) = _state.update { it?.copy(selection = transform(it.selection)) } private fun showMessage(text: String) { _effects.trySend(DetailEffect.ShowMessage(text)) } } private class TitleData( val manga: Manga, val source: Source?, val genreSources: List, val categories: List, val tracks: List, val seasonTitles: List, ) private fun YokanRepository.titleData(mangaId: Long): TitleData? { val manga = manga(mangaId) ?: return null val titleSource = if (manga.isLocalArchive) null else manga.sourceId?.let { this.source(it) } return TitleData( manga = manga, source = titleSource, genreSources = sources(manga.itemType) .filter { it.isAdded && it.isActive } .sortedWith(compareBy { it.id != titleSource?.id }.thenBy { it.name.lowercase() }.thenBy { it.lang }), categories = categories(manga.itemType), tracks = tracks().filter { it.mangaId == mangaId }, // Only Seasons-type titles own season records; skip the full title scan for everything else. seasonTitles = if (!manga.fetchesSeasons) emptyList() else allTitles(manga.itemType) .filter { it.parentId == mangaId } .sortedWith(compareBy({ it.seasonNumber ?: Double.MAX_VALUE }, { it.name.lowercase() })), ) } private fun detailContent(title: TitleData, index: LibraryIndex, db: DbSettings, showAllReleases: Boolean, selectedSeason: Int?): DetailContent { val manga = title.manga val all = sortedChapters(manga, index.chapters(manga.id), db) val seasons = if (manga.itemType == eu.friedcutlet.yokan.domain.ItemType.Anime) all.mapNotNull { it.detailSeason() }.distinct().sorted() else emptyList() val effectiveSeason = selectedSeason?.takeIf { it in seasons } val seasonChapters = if (effectiveSeason == null) all else all.filter { it.detailSeason() == effectiveSeason } val visible = filterChapters(manga, seasonChapters, db, index.downloadedChapterIds, showAllReleases) val winners = sortedChapters(manga, selectChapterReleases(manga.name, seasonChapters, db.chapterReleasePreference(manga.id).toPolicy(), db.scanlatorFilter(manga.id), index.downloadedChapterIds, offlineOnly = db.downloadedOnlyMode), db) return DetailContent( manga = manga, settings = db, source = title.source, chapters = visible, continueChapter = winners.firstOrNull { !it.isRead } ?: winners.firstOrNull(), scanlators = all.map { it.scanlator }.distinctBy(::normalizeScanlator).sortedBy(::normalizeScanlator), automaticUpdateDays = meanChapterUpdateDays(all.map { it.dateUpload }), missingChapterCount = ChapterRecognition.missingChapterCount(manga.name, visible), unnumberedChapterCount = ChapterRecognition.unrecognizedChapterNumberCount(manga.name, visible), tracks = title.tracks, categories = title.categories, genreSources = title.genreSources, loaded = true, seasons = seasons, selectedSeason = effectiveSeason, seasonTitles = title.seasonTitles.map { season -> val episodes = sortedChapters(season, index.chapters(season.id), db) DetailSeasonTitle(season, episodes.size, episodes.count { it.isRead }, episodes.firstOrNull { !it.isRead }) }, ) } private fun Chapter.detailSeason(): Int? = season?.takeIf { it >= 0 } ?: ChapterRecognition.parseSeasonNumber(numberingName?.takeIf(String::isNotBlank) ?: name) private fun Throwable.displayMessage(): String = message.orEmpty().ifBlank { this::class.simpleName.orEmpty() } private fun shareUrl(manga: Manga, source: Source?): String { if (manga.link.startsWith("http", ignoreCase = true)) return manga.link val base = source?.baseUrl?.takeIf { it.isNotBlank() } ?: return manga.link return "${base.trimEnd('/')}/${manga.link.trimStart('/')}" } private fun Manga.toMetadataJson(): String = buildString { appendLine("{") appendLine(" \"name\": \"${name.jsonEscaped()}\",") appendLine(" \"description\": \"${description.jsonEscaped()}\",") appendLine(" \"artist\": ${artist.jsonStringOrNull()},") appendLine(" \"author\": ${author.jsonStringOrNull()},") appendLine(" \"genre\": [${genres.joinToString(", ") { "\"${it.jsonEscaped()}\"" }}],") appendLine(" \"cast\": ${eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(kotlinx.serialization.builtins.ListSerializer(eu.friedcutlet.yokan.domain.TitleCredit.serializer()), cast)},") appendLine(" \"status\": \"${status.name.jsonEscaped()}\"") appendLine("}") } private fun String?.jsonStringOrNull(): String = this?.let { "\"${it.jsonEscaped()}\"" } ?: "null" private fun String.jsonEscaped(): String = buildString { this@jsonEscaped.forEach { char -> when (char) { '\\' -> append("\\\\") '"' -> append("\\\"") '\n' -> append("\\n") '\r' -> append("\\r") '\t' -> append("\\t") else -> append(char) } } } private fun String.safeFileSegment(): String = replace(Regex("""[\\/:*?"<>|]+"""), "_") .trim() .take(80) .ifBlank { "metadata" }