package eu.friedcutlet.yokan.ui import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.data.LibraryIndex import eu.friedcutlet.yokan.domain.effectiveChapterUpdateDays import eu.friedcutlet.yokan.util.nowMillis import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn /** Compiled once per query, with no database access or parsing in the per-title predicate. */ internal class LibrarySearchQuery( query: String, private val index: LibraryIndex = LibraryIndex.Empty, private val now: Long = nowMillis(), private val scheduleIndex: LibraryIndex = index, ) { private val predicate: SearchPredicate = compileSearch(query) fun matches(manga: Manga): Boolean = predicate(SearchEntry(manga, index, scheduleIndex, now)) } private typealias SearchPredicate = (SearchEntry) -> Boolean private class SearchEntry(val manga: Manga, index: LibraryIndex, private val scheduleIndex: LibraryIndex, private val now: Long) { private val chapters = index.chapters(manga.id) val total get() = chapters.size.toLong() private var cachedRead: Long? = null val read get() = cachedRead ?: chapters.count { it.isRead }.toLong().also { cachedRead = it } val unread get() = total - read private var cachedInterval: Long? = null val interval get() = cachedInterval ?: effectiveChapterUpdateDays(manga.smartUpdateDays, if (manga.smartUpdateDays == null) scheduleIndex.chapters(manga.id).map(Chapter::dateUpload) else emptyList(), now) .toLong().also { cachedInterval = it } val nextUpdate: Long? get() = manga.lastUpdateMillis.takeIf { it > 0 }?.let { val delay = interval * SearchDayMillis if (it > Long.MAX_VALUE - delay) Long.MAX_VALUE else it + delay } } private const val SearchDayMillis = 86_400_000L private const val MaxSearchLength = 4096 private const val MaxSearchTokens = 256 private const val MaxSearchDepth = 24 private fun generalSearch(value: String): SearchPredicate = { entry -> val manga = entry.manga manga.name.contains(value, true) || manga.alternativeTitles.any { it.contains(value, true) } || manga.source.contains(value, true) || manga.genres.any { it.contains(value, true) } } private fun legacySearch(query: String): SearchPredicate { val values = query.split(',').map(String::trim).filter(String::isNotEmpty).map(::generalSearch) return { entry -> values.isEmpty() || values.any { it(entry) } } } private fun compileSearch(query: String): SearchPredicate { val text = query.trim() if (text.length > MaxSearchLength) return generalSearch(text) if (text.isEmpty()) return { true } // Preserve existing exact, multiword genre links, including tags containing commas. if (text.startsWith("genre:", true) && text.none { it in "\"'()&|" } && text.substringAfter(':').none { it in ":<=>" } && !Regex("\\s(?:(?:AND|OR|NOT)(?:\\s|$)|-\\S)").containsMatchIn(text) ) { val genre = text.substringAfter(':').trim() return { entry -> entry.manga.genres.any { it.trim().equals(genre, true) } } } return try { val tokens = tokenizeSearch(text) if (tokens.none { (it.kind != SearchTokenKind.Value && it.kind != SearchTokenKind.Or) || (it.kind == SearchTokenKind.Value && (fieldParts(it.text) != null || it.quoted)) } && "||" !in text ) { legacySearch(text) } else SearchParser(tokens).parse() } catch (_: SearchSyntaxException) { // Never apply only the valid prefix of a malformed expression. generalSearch(text) } } private enum class SearchTokenKind { Value, And, Or, Not, Open, Close } private data class SearchToken(val kind: SearchTokenKind, val text: String = "", val quoted: Boolean = false, val literal: Boolean = false) private class SearchSyntaxException : Exception() /** Bounded linear scanner; quoted field values may contain operators and escaped quotes. */ private fun tokenizeSearch(text: String): List { val tokens = mutableListOf() var position = 0 while (position < text.length) { val char = text[position] if (char.isWhitespace()) { position++; continue } if (tokens.size >= MaxSearchTokens) throw SearchSyntaxException() val kind = when { char == '(' -> SearchTokenKind.Open char == ')' -> SearchTokenKind.Close char == ',' -> SearchTokenKind.Or char == '-' && position + 1 < text.length && !text[position + 1].isWhitespace() -> SearchTokenKind.Not text.startsWith("&&", position) -> SearchTokenKind.And text.startsWith("||", position) -> SearchTokenKind.Or else -> null } if (kind != null) { tokens += SearchToken(kind) position += if (char == '&' || char == '|') 2 else 1 continue } val value = StringBuilder() val literal = char == '"' || char == '\'' var quoted = false while (position < text.length) { val current = text[position] if (current.isWhitespace() || current in "()," || text.startsWith("&&", position) || text.startsWith("||", position)) break if ((current == '"' || current == '\'') && (value.isEmpty() || value.last() in ":<=>")) { quoted = true val quote = current position++ var closed = false while (position < text.length) { val next = text[position++] if (next == quote) { closed = true; break } if (next == '\\' && position < text.length && (text[position] == quote || text[position] == '\\')) { value.append(text[position++]) } else value.append(next) } if (!closed) throw SearchSyntaxException() } else { value.append(current); position++ } } val word = value.toString() val wordKind = if (quoted) SearchTokenKind.Value else when (word) { "AND" -> SearchTokenKind.And "OR" -> SearchTokenKind.Or "NOT" -> SearchTokenKind.Not else -> SearchTokenKind.Value } tokens += SearchToken(wordKind, word, quoted, literal) } return tokens } private class SearchParser(private val tokens: List) { private var position = 0 private fun peek() = tokens.getOrNull(position)?.kind fun parse(): SearchPredicate { val result = or(0) if (position != tokens.size) throw SearchSyntaxException() return result } private fun or(depth: Int): SearchPredicate { val children = mutableListOf(and(depth)) while (peek() == SearchTokenKind.Or) { position++; children += and(depth) } return if (children.size == 1) children.first() else { entry -> children.any { it(entry) } } } private fun and(depth: Int): SearchPredicate { val children = mutableListOf(term(depth)) while (peek() != null && peek() != SearchTokenKind.Or && peek() != SearchTokenKind.Close) { if (peek() == SearchTokenKind.And) position++ children += term(depth) } return if (children.size == 1) children.first() else { entry -> children.all { it(entry) } } } private fun term(depth: Int): SearchPredicate { var negate = false while (peek() == SearchTokenKind.Not) { negate = !negate; position++ } val token = tokens.getOrNull(position++) ?: throw SearchSyntaxException() val child = when (token.kind) { SearchTokenKind.Open -> { if (depth >= MaxSearchDepth) throw SearchSyntaxException() val result = or(depth + 1) if (peek() != SearchTokenKind.Close) throw SearchSyntaxException() position++ result } SearchTokenKind.Value -> if (token.literal) generalSearch(token.text) else compileTerm(token.text) else -> throw SearchSyntaxException() } return if (negate) { entry -> !child(entry) } else child } } private data class SearchField(val name: String, val comparator: String, val value: String) private fun fieldParts(text: String): SearchField? { val position = text.indexOfFirst { it in ":<=>" } if (position <= 0 || text.take(position).any { !it.isLetterOrDigit() && it != '_' }) return null val end = if (text[position] != ':' && text.getOrNull(position + 1) == '=') position + 2 else position + 1 return SearchField(text.take(position).lowercase(), text.substring(position, end), text.substring(end)) } private fun compileTerm(text: String): SearchPredicate { val field = fieldParts(text) ?: return generalSearch(text) val value = field.value if (value.isEmpty()) throw SearchSyntaxException() if (field.comparator == ":") { return when (field.name) { "title" -> { entry -> entry.manga.name.contains(value, true) || entry.manga.alternativeTitles.any { it.contains(value, true) } } "author" -> { entry -> entry.manga.author?.contains(value, true) == true } "artist" -> { entry -> entry.manga.artist?.contains(value, true) == true } "description", "desc" -> { entry -> entry.manga.description.contains(value, true) } "genre", "tag" -> { entry -> entry.manga.genres.any { it.trim().equals(value, true) } } "source", "src" -> { entry -> entry.manga.source.contains(value, true) } "notes", "note" -> { entry -> entry.manga.privateNote.contains(value, true) } "language", "lang" -> { entry -> entry.manga.lang.equals(value, true) } "source_id", "sourceid", "src_id", "srcid" -> { val id = value.toLongOrNull() ?: throw SearchSyntaxException(); { entry -> entry.manga.sourceId == id } } "status" -> { entry -> entry.manga.status.name.equals(value, true) || entry.manga.status.label.equals(value, true) } "type" -> { entry -> entry.manga.itemType.name.equals(value, true) } else -> generalSearch(text) } } val actual: (SearchEntry) -> Long? = when (field.name) { "id" -> { entry -> entry.manga.id } "total" -> { entry -> entry.total } "read" -> { entry -> entry.read } "unread" -> { entry -> entry.unread } "fetchinterval", "fi" -> { entry -> entry.interval } "added" -> { entry -> entry.manga.dateAddedMillis.takeIf { it > 0 }?.div(SearchDayMillis) } "nextupdate", "nu" -> { entry -> entry.nextUpdate?.div(SearchDayMillis) } else -> return generalSearch(text) } val dateField = field.name in setOf("added", "nextupdate", "nu") val expected = if (dateField) runCatching { LocalDate.parse(value).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() / SearchDayMillis }.getOrNull() else value.toLongOrNull() if (expected == null) throw SearchSyntaxException() return { entry -> val found = actual(entry) found != null && when (field.comparator) { ">" -> found > expected ">=" -> found >= expected "<" -> found < expected "<=" -> found <= expected "=" -> found == expected else -> false } } }