StatisticsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.statistics23import kotlinx.coroutines.CoroutineDispatcher4import androidx.compose.runtime.Immutable5import androidx.lifecycle.ViewModel6import androidx.lifecycle.viewModelScope7import eu.friedcutlet.yokan.data.LibraryIndex8import eu.friedcutlet.yokan.data.LibraryIndexStore9import eu.friedcutlet.yokan.data.SettingsStore10import eu.friedcutlet.yokan.data.YokanRepository11import eu.friedcutlet.yokan.database.configuredLocalFolders12import eu.friedcutlet.yokan.domain.Chapter13import eu.friedcutlet.yokan.domain.History14import eu.friedcutlet.yokan.domain.ItemType15import eu.friedcutlet.yokan.domain.Manga16import eu.friedcutlet.yokan.domain.Status17import eu.friedcutlet.yokan.services.catchingNonCancellation18import eu.friedcutlet.yokan.services.download.downloadStorageRootCandidates19import eu.friedcutlet.yokan.services.files.LocalFileService20import kotlinx.coroutines.Dispatchers21import kotlinx.coroutines.flow.MutableStateFlow22import kotlinx.coroutines.flow.asStateFlow23import kotlinx.coroutines.flow.collectLatest24import kotlinx.coroutines.flow.combine25import kotlinx.coroutines.flow.distinctUntilChanged26import kotlinx.coroutines.flow.filter27import kotlinx.coroutines.flow.map28import kotlinx.coroutines.flow.update29import kotlinx.coroutines.launch30import kotlinx.coroutines.withContext31import kotlinx.datetime.TimeZone32import kotlinx.datetime.isoDayNumber33import kotlinx.datetime.number34import kotlinx.datetime.toLocalDateTime35import eu.friedcutlet.yokan.util.nowMillis3637/** Weeks of activity kept for the heatmap; the UI shows the most recent weeks that fit. */38internal const val ACTIVITY_WEEKS = 2639private const val GROWTH_MONTHS = 2440private const val TOP_GENRES = 84142@Immutable43internal data class StatisticsData(44 val titles: Int,45 val chapters: Int,46 val read: Int,47 val caughtUp: Int,48 val inProgress: Int,49 val notStarted: Int,50 val localTitles: Int,51 val downloadedTitles: Int,52 val trackedTitles: Int,53 val seconds: Long,54 val activeTitles: Int,55 val mostTime: List<History>,56 /** Titles last active per day, oldest first: starts on a Monday, ends today. */57 val dailyActivity: List<Int>,58 /** Titles last active per local hour of day (24 entries). */59 val hourly: List<Int>,60 /** Most common library genres, largest first. */61 val genres: List<Pair<String, Int>>,62 /** Library size at the end of each month, oldest first, ending this month. */63 val growth: List<Int>,64)6566/** History is one accumulated record per title, not a log of reading sessions. */67@OptIn(kotlin.time.ExperimentalTime::class)68internal fun summarizeStatistics(69 titles: List<Manga>,70 chapters: Map<Long, List<Chapter>>,71 history: List<History>,72 downloadedIds: Set<Long>,73 trackedIds: Set<Long>,74 now: Long = nowMillis(),75 zone: TimeZone = TimeZone.currentSystemDefault(),76): StatisticsData {77 fun local(millis: Long) = kotlin.time.Instant.fromEpochMilliseconds(millis).toLocalDateTime(zone)78 val library = titles.filter { it.favorite }79 val libraryChapters = library.flatMap { chapters[it.id].orEmpty() }80 val caughtUp = library.count { title ->81 chapters[title.id].orEmpty().let { it.isNotEmpty() && it.all(Chapter::isRead) }82 }83 val inProgress = library.count { title ->84 chapters[title.id].orEmpty().let { rows ->85 rows.any { it.isRead || it.lastPageRead.toFloatOrNull()?.let { page -> page > 0 } == true } &&86 !rows.all(Chapter::isRead)87 }88 }89 val today = local(now).date90 val todayDay = today.toEpochDays()91 val firstDay = todayDay - (today.dayOfWeek.isoDayNumber - 1) - (ACTIVITY_WEEKS - 1) * 7L92 val daily = IntArray((todayDay - firstDay + 1).toInt())93 val hourly = IntArray(24)94 history.filter { it.updatedAt > 0 }.forEach {95 val at = local(it.updatedAt)96 hourly[at.hour]++97 val day = at.date.toEpochDays()98 if (day in firstDay..todayDay) daily[(day - firstDay).toInt()]++99 }100 fun monthIndex(millis: Long) = local(millis).let { it.year * 12 + it.month.number - 1 }101 val nowMonth = monthIndex(now)102 val addedMonths = library.map { if (it.dateAddedMillis > 0) monthIndex(it.dateAddedMillis) else Int.MIN_VALUE }103 val firstMonth = maxOf(addedMonths.filter { it != Int.MIN_VALUE }.minOrNull() ?: nowMonth, nowMonth - GROWTH_MONTHS + 1)104 val growth = (firstMonth..nowMonth).map { month -> addedMonths.count { it <= month } }105 val genres = library.flatMap { title -> title.genres.map(String::trim).filter(String::isNotEmpty).distinctBy(String::lowercase) }106 .groupBy(String::lowercase).values.map { it.first() to it.size }107 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() }).take(TOP_GENRES)108 return StatisticsData(109 titles = library.size,110 chapters = libraryChapters.size,111 read = libraryChapters.count(Chapter::isRead),112 caughtUp = caughtUp,113 inProgress = inProgress,114 notStarted = library.size - caughtUp - inProgress,115 localTitles = library.count { it.isLocalArchive },116 downloadedTitles = library.count { chapters[it.id].orEmpty().any { chapter -> chapter.id in downloadedIds } },117 trackedTitles = library.count { it.id in trackedIds },118 seconds = history.sumOf { it.readingTimeSeconds.coerceAtLeast(0).toLong() },119 activeTitles = history.map { it.mangaId }.distinct().size,120 mostTime = history.filter { it.readingTimeSeconds > 0 }.sortedByDescending { it.readingTimeSeconds }.take(5),121 dailyActivity = daily.toList(),122 hourly = hourly.toList(),123 genres = genres,124 growth = growth,125 )126}127128@Immutable129internal data class StatisticsState(130 val type: ItemType,131 val data: StatisticsData? = null,132 val failed: Boolean = false,133 val downloadBytes: Long? = null,134 val localBytes: Long? = null,135 val storageFailed: Boolean = false,136)137138internal class StatisticsViewModel(139 initialType: ItemType,140 private val repository: YokanRepository,141 private val settings: SettingsStore,142 libraryIndex: LibraryIndexStore,143 private val files: LocalFileService,144 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,145) : ViewModel() {146 private val _state = MutableStateFlow(StatisticsState(initialType))147 val state = _state.asStateFlow()148 private val selectedType = MutableStateFlow(initialType)149 private val retries = MutableStateFlow(0)150151 init {152 viewModelScope.launch {153 combine(154 selectedType,155 retries,156 // Empty is the placeholder before the first build, not an empty library.157 libraryIndex.index.filter { it !== LibraryIndex.Empty },158 repository.snapshots.distinctUntilChanged { old, new -> old.mangas === new.mangas && old.histories === new.histories },159 ) { type, _, index, _ -> type to index }.collectLatest { (type, index) ->160 _state.update { it.copy(failed = false) }161 val data = withContext(workDispatcher) { catchingNonCancellation { summarize(type, index) } }162 _state.update { current ->163 if (current.type != type) current else data.fold({ current.copy(data = it) }, { current.copy(failed = true) })164 }165 }166 }167 // Disk scanning must not delay rendering the charts.168 viewModelScope.launch {169 combine(170 selectedType,171 retries,172 settings.db.map { Triple(it.downloadLocation, it.namedLocalFolders, it.localFolders) }.distinctUntilChanged(),173 repository.snapshots.distinctUntilChanged { old, new -> old.downloads === new.downloads },174 ) { type, _, _, _ -> type }.collectLatest { type ->175 _state.update { it.copy(storageFailed = false, downloadBytes = null, localBytes = null) }176 val db = settings.db.value177 val sizes = withContext(workDispatcher) {178 catchingNonCancellation {179 val location = db.downloadLocation.ifBlank { files.downloadRoot }180 downloadStorageRootCandidates(location, files).sumOf { files.directorySize("$it/${type.name}") } to181 db.configuredLocalFolders().sumOf { files.directorySize(it.path) }182 }183 }184 _state.update { current ->185 if (current.type != type) {186 current187 } else {188 sizes.fold(189 { current.copy(downloadBytes = it.first, localBytes = it.second) },190 { current.copy(storageFailed = true) },191 )192 }193 }194 }195 }196 }197198 fun select(type: ItemType) {199 if (type == selectedType.value) return200 _state.value = StatisticsState(type)201 selectedType.value = type202 }203204 fun refresh() = retries.update { it + 1 }205206 private fun summarize(type: ItemType, index: LibraryIndex): StatisticsData {207 val titles = repository.allTitles(type).filter { it.favorite }208 return summarizeStatistics(209 titles,210 titles.associate { it.id to index.chapters(it.id) },211 repository.history().filter { it.itemType == type },212 index.downloadedChapterIds,213 index.trackedMangaIds,214 )215 }216}217