LibrarySearch.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/LibrarySearch.kt
1package eu.friedcutlet.yokan.ui23import eu.friedcutlet.yokan.domain.Manga4import eu.friedcutlet.yokan.domain.Chapter5import eu.friedcutlet.yokan.data.LibraryIndex6import eu.friedcutlet.yokan.domain.effectiveChapterUpdateDays7import eu.friedcutlet.yokan.util.nowMillis8import kotlinx.datetime.LocalDate9import kotlinx.datetime.TimeZone10import kotlinx.datetime.atStartOfDayIn1112/** Compiled once per query, with no database access or parsing in the per-title predicate. */13internal class LibrarySearchQuery(14 query: String,15 private val index: LibraryIndex = LibraryIndex.Empty,16 private val now: Long = nowMillis(),17 private val scheduleIndex: LibraryIndex = index,18) {19 private val predicate: SearchPredicate = compileSearch(query)20 fun matches(manga: Manga): Boolean = predicate(SearchEntry(manga, index, scheduleIndex, now))21}2223private typealias SearchPredicate = (SearchEntry) -> Boolean2425private class SearchEntry(val manga: Manga, index: LibraryIndex, private val scheduleIndex: LibraryIndex, private val now: Long) {26 private val chapters = index.chapters(manga.id)27 val total get() = chapters.size.toLong()28 private var cachedRead: Long? = null29 val read get() = cachedRead ?: chapters.count { it.isRead }.toLong().also { cachedRead = it }30 val unread get() = total - read31 private var cachedInterval: Long? = null32 val interval get() = cachedInterval ?: effectiveChapterUpdateDays(manga.smartUpdateDays,33 if (manga.smartUpdateDays == null) scheduleIndex.chapters(manga.id).map(Chapter::dateUpload) else emptyList(), now)34 .toLong().also { cachedInterval = it }35 val nextUpdate: Long? get() = manga.lastUpdateMillis.takeIf { it > 0 }?.let {36 val delay = interval * SearchDayMillis37 if (it > Long.MAX_VALUE - delay) Long.MAX_VALUE else it + delay38 }39}4041private const val SearchDayMillis = 86_400_000L42private const val MaxSearchLength = 409643private const val MaxSearchTokens = 25644private const val MaxSearchDepth = 244546private fun generalSearch(value: String): SearchPredicate = { entry ->47 val manga = entry.manga48 manga.name.contains(value, true) || manga.alternativeTitles.any { it.contains(value, true) } ||49 manga.source.contains(value, true) || manga.genres.any { it.contains(value, true) }50}5152private fun legacySearch(query: String): SearchPredicate {53 val values = query.split(',').map(String::trim).filter(String::isNotEmpty).map(::generalSearch)54 return { entry -> values.isEmpty() || values.any { it(entry) } }55}5657private fun compileSearch(query: String): SearchPredicate {58 val text = query.trim()59 if (text.length > MaxSearchLength) return generalSearch(text)60 if (text.isEmpty()) return { true }61 // Preserve existing exact, multiword genre links, including tags containing commas.62 if (text.startsWith("genre:", true) && text.none { it in "\"'()&|" } &&63 text.substringAfter(':').none { it in ":<=>" } &&64 !Regex("\\s(?:(?:AND|OR|NOT)(?:\\s|$)|-\\S)").containsMatchIn(text)65 ) {66 val genre = text.substringAfter(':').trim()67 return { entry -> entry.manga.genres.any { it.trim().equals(genre, true) } }68 }69 return try {70 val tokens = tokenizeSearch(text)71 if (tokens.none { (it.kind != SearchTokenKind.Value && it.kind != SearchTokenKind.Or) ||72 (it.kind == SearchTokenKind.Value && (fieldParts(it.text) != null || it.quoted)) } &&73 "||" !in text74 ) {75 legacySearch(text)76 } else SearchParser(tokens).parse()77 } catch (_: SearchSyntaxException) {78 // Never apply only the valid prefix of a malformed expression.79 generalSearch(text)80 }81}8283private enum class SearchTokenKind { Value, And, Or, Not, Open, Close }84private data class SearchToken(val kind: SearchTokenKind, val text: String = "", val quoted: Boolean = false, val literal: Boolean = false)85private class SearchSyntaxException : Exception()8687/** Bounded linear scanner; quoted field values may contain operators and escaped quotes. */88private fun tokenizeSearch(text: String): List<SearchToken> {89 val tokens = mutableListOf<SearchToken>()90 var position = 091 while (position < text.length) {92 val char = text[position]93 if (char.isWhitespace()) { position++; continue }94 if (tokens.size >= MaxSearchTokens) throw SearchSyntaxException()95 val kind = when {96 char == '(' -> SearchTokenKind.Open97 char == ')' -> SearchTokenKind.Close98 char == ',' -> SearchTokenKind.Or99 char == '-' && position + 1 < text.length && !text[position + 1].isWhitespace() -> SearchTokenKind.Not100 text.startsWith("&&", position) -> SearchTokenKind.And101 text.startsWith("||", position) -> SearchTokenKind.Or102 else -> null103 }104 if (kind != null) {105 tokens += SearchToken(kind)106 position += if (char == '&' || char == '|') 2 else 1107 continue108 }109 val value = StringBuilder()110 val literal = char == '"' || char == '\''111 var quoted = false112 while (position < text.length) {113 val current = text[position]114 if (current.isWhitespace() || current in "()," || text.startsWith("&&", position) || text.startsWith("||", position)) break115 if ((current == '"' || current == '\'') && (value.isEmpty() || value.last() in ":<=>")) {116 quoted = true117 val quote = current118 position++119 var closed = false120 while (position < text.length) {121 val next = text[position++]122 if (next == quote) { closed = true; break }123 if (next == '\\' && position < text.length && (text[position] == quote || text[position] == '\\')) {124 value.append(text[position++])125 } else value.append(next)126 }127 if (!closed) throw SearchSyntaxException()128 } else { value.append(current); position++ }129 }130 val word = value.toString()131 val wordKind = if (quoted) SearchTokenKind.Value else when (word) {132 "AND" -> SearchTokenKind.And133 "OR" -> SearchTokenKind.Or134 "NOT" -> SearchTokenKind.Not135 else -> SearchTokenKind.Value136 }137 tokens += SearchToken(wordKind, word, quoted, literal)138 }139 return tokens140}141142private class SearchParser(private val tokens: List<SearchToken>) {143 private var position = 0144 private fun peek() = tokens.getOrNull(position)?.kind145 fun parse(): SearchPredicate {146 val result = or(0)147 if (position != tokens.size) throw SearchSyntaxException()148 return result149 }150 private fun or(depth: Int): SearchPredicate {151 val children = mutableListOf(and(depth))152 while (peek() == SearchTokenKind.Or) { position++; children += and(depth) }153 return if (children.size == 1) children.first() else { entry -> children.any { it(entry) } }154 }155 private fun and(depth: Int): SearchPredicate {156 val children = mutableListOf(term(depth))157 while (peek() != null && peek() != SearchTokenKind.Or && peek() != SearchTokenKind.Close) {158 if (peek() == SearchTokenKind.And) position++159 children += term(depth)160 }161 return if (children.size == 1) children.first() else { entry -> children.all { it(entry) } }162 }163 private fun term(depth: Int): SearchPredicate {164 var negate = false165 while (peek() == SearchTokenKind.Not) { negate = !negate; position++ }166 val token = tokens.getOrNull(position++) ?: throw SearchSyntaxException()167 val child = when (token.kind) {168 SearchTokenKind.Open -> {169 if (depth >= MaxSearchDepth) throw SearchSyntaxException()170 val result = or(depth + 1)171 if (peek() != SearchTokenKind.Close) throw SearchSyntaxException()172 position++173 result174 }175 SearchTokenKind.Value -> if (token.literal) generalSearch(token.text) else compileTerm(token.text)176 else -> throw SearchSyntaxException()177 }178 return if (negate) { entry -> !child(entry) } else child179 }180}181182private data class SearchField(val name: String, val comparator: String, val value: String)183private fun fieldParts(text: String): SearchField? {184 val position = text.indexOfFirst { it in ":<=>" }185 if (position <= 0 || text.take(position).any { !it.isLetterOrDigit() && it != '_' }) return null186 val end = if (text[position] != ':' && text.getOrNull(position + 1) == '=') position + 2 else position + 1187 return SearchField(text.take(position).lowercase(), text.substring(position, end), text.substring(end))188}189190private fun compileTerm(text: String): SearchPredicate {191 val field = fieldParts(text) ?: return generalSearch(text)192 val value = field.value193 if (value.isEmpty()) throw SearchSyntaxException()194 if (field.comparator == ":") {195 return when (field.name) {196 "title" -> { entry -> entry.manga.name.contains(value, true) || entry.manga.alternativeTitles.any { it.contains(value, true) } }197 "author" -> { entry -> entry.manga.author?.contains(value, true) == true }198 "artist" -> { entry -> entry.manga.artist?.contains(value, true) == true }199 "description", "desc" -> { entry -> entry.manga.description.contains(value, true) }200 "genre", "tag" -> { entry -> entry.manga.genres.any { it.trim().equals(value, true) } }201 "source", "src" -> { entry -> entry.manga.source.contains(value, true) }202 "notes", "note" -> { entry -> entry.manga.privateNote.contains(value, true) }203 "language", "lang" -> { entry -> entry.manga.lang.equals(value, true) }204 "source_id", "sourceid", "src_id", "srcid" -> {205 val id = value.toLongOrNull() ?: throw SearchSyntaxException();206 { entry -> entry.manga.sourceId == id }207 }208 "status" -> { entry -> entry.manga.status.name.equals(value, true) || entry.manga.status.label.equals(value, true) }209 "type" -> { entry -> entry.manga.itemType.name.equals(value, true) }210 else -> generalSearch(text)211 }212 }213 val actual: (SearchEntry) -> Long? = when (field.name) {214 "id" -> { entry -> entry.manga.id }215 "total" -> { entry -> entry.total }216 "read" -> { entry -> entry.read }217 "unread" -> { entry -> entry.unread }218 "fetchinterval", "fi" -> { entry -> entry.interval }219 "added" -> { entry -> entry.manga.dateAddedMillis.takeIf { it > 0 }?.div(SearchDayMillis) }220 "nextupdate", "nu" -> { entry -> entry.nextUpdate?.div(SearchDayMillis) }221 else -> return generalSearch(text)222 }223 val dateField = field.name in setOf("added", "nextupdate", "nu")224 val expected = if (dateField) runCatching {225 LocalDate.parse(value).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() / SearchDayMillis226 }.getOrNull() else value.toLongOrNull()227 if (expected == null) throw SearchSyntaxException()228 return { entry ->229 val found = actual(entry)230 found != null && when (field.comparator) {231 ">" -> found > expected232 ">=" -> found >= expected233 "<" -> found < expected234 "<=" -> found <= expected235 "=" -> found == expected236 else -> false237 }238 }239}240