@@ -3,61 +3,23 @@ package io.github.kdroidfilter.seforimlibrary.cli
33import io.github.kdroidfilter.seforimlibrary.dao.repository.SeforimRepository
44import io.github.kdroidfilter.seforimlibrary.search.LineSnippetInfo
55import io.github.kdroidfilter.seforimlibrary.search.SnippetProvider
6+ import io.github.kdroidfilter.seforimlibrary.search.SnippetSource
7+ import io.github.kdroidfilter.seforimlibrary.search.SnippetSources
68import kotlinx.coroutines.Dispatchers
79import kotlinx.coroutines.withContext
8- import org.jsoup.Jsoup
9- import org.jsoup.safety.Safelist
1010
1111/* *
1212 * CLI implementation of [SnippetProvider] that fetches line content from the database.
1313 */
14- private const val SNIPPET_NEIGHBOR_WINDOW = 4
15- private const val SNIPPET_MIN_LENGTH = 280
16-
1714class CliSnippetProvider (
1815 private val repository : SeforimRepository ,
1916) : SnippetProvider {
20- override suspend fun getSnippetSources (lines : List <LineSnippetInfo >): Map <Long , String > {
17+ override suspend fun getSnippetSources (lines : List <LineSnippetInfo >): Map <Long , SnippetSource > {
2118 if (lines.isEmpty()) return emptyMap()
22-
2319 return withContext(Dispatchers .IO ) {
24- val byBook = lines.groupBy { it.bookId }
25- val result = mutableMapOf<Long , String >()
26-
27- for ((bookId, bookLines) in byBook) {
28- val minIdx = bookLines.minOf { it.lineIndex }
29- val maxIdx = bookLines.maxOf { it.lineIndex }
30- val rangeStart = (minIdx - SNIPPET_NEIGHBOR_WINDOW ).coerceAtLeast(0 )
31- val rangeEnd = maxIdx + SNIPPET_NEIGHBOR_WINDOW
32-
33- val allLines = repository.getLines(bookId, rangeStart, rangeEnd)
34-
35- val plainByIndex = allLines.associate { line ->
36- line.lineIndex to cleanHtml(line.content)
37- }
38-
39- for (info in bookLines) {
40- val basePlain = plainByIndex[info.lineIndex].orEmpty()
41- val snippetSource = if (basePlain.length >= SNIPPET_MIN_LENGTH ) {
42- basePlain
43- } else {
44- val start = (info.lineIndex - SNIPPET_NEIGHBOR_WINDOW ).coerceAtLeast(0 )
45- val end = info.lineIndex + SNIPPET_NEIGHBOR_WINDOW
46- (start.. end)
47- .mapNotNull { plainByIndex[it] }
48- .joinToString(" " )
49- }
50- result[info.lineId] = snippetSource
51- }
20+ SnippetSources .build(lines) { bookId, from, to ->
21+ repository.getLines(bookId, from, to).associate { it.lineIndex to it.content }
5222 }
53-
54- result
5523 }
5624 }
57-
58- private fun cleanHtml (content : String ): String =
59- Jsoup
60- .clean(content, Safelist .none())
61- .replace(" \\ s+" .toRegex(), " " )
62- .trim()
6325}
0 commit comments