1 package net.pterodactylus.sone.web.pages
3 import com.google.common.base.Ticker
4 import com.google.common.cache.Cache
5 import com.google.common.cache.CacheBuilder
6 import freenet.support.Logger
7 import net.pterodactylus.sone.data.Post
8 import net.pterodactylus.sone.data.PostReply
9 import net.pterodactylus.sone.data.Sone
10 import net.pterodactylus.sone.main.*
11 import net.pterodactylus.sone.utils.Pagination
12 import net.pterodactylus.sone.utils.emptyToNull
13 import net.pterodactylus.sone.utils.memoize
14 import net.pterodactylus.sone.utils.paginate
15 import net.pterodactylus.sone.utils.parameters
16 import net.pterodactylus.sone.web.WebInterface
17 import net.pterodactylus.sone.web.page.*
18 import net.pterodactylus.sone.web.pages.SearchPage.Optionality.FORBIDDEN
19 import net.pterodactylus.sone.web.pages.SearchPage.Optionality.OPTIONAL
20 import net.pterodactylus.sone.web.pages.SearchPage.Optionality.REQUIRED
21 import net.pterodactylus.util.template.Template
22 import net.pterodactylus.util.template.TemplateContext
23 import net.pterodactylus.util.text.StringEscaper
24 import net.pterodactylus.util.text.TextException
25 import java.util.concurrent.TimeUnit.MINUTES
26 import javax.inject.Inject
29 * This page lets the user search for posts and replies that contain certain
32 class SearchPage(template: Template, webInterface: WebInterface, loaders: Loaders, ticker: Ticker = Ticker.systemTicker()) :
33 SoneTemplatePage("search.html", webInterface, loaders, template = template, pageTitleKey = "Page.Search.Title") {
35 @Inject constructor(template: Template, webInterface: WebInterface, loaders: Loaders) :
36 this(template, webInterface, loaders, Ticker.systemTicker())
38 private val cache: Cache<Iterable<Phrase>, Pagination<Post>> = CacheBuilder.newBuilder().ticker(ticker).expireAfterAccess(5, MINUTES).build()
40 override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) {
41 val startTime = System.currentTimeMillis()
43 soneRequest.parameters["query"].emptyToNull?.parse()
44 } catch (te: TextException) {
45 redirect("index.html")
47 ?: redirect("index.html")
50 0 -> redirect("index.html")
51 1 -> phrases.first().phrase.also { word ->
53 word.removePrefix("sone://").let(soneRequest.core::getSone) != null -> redirect("viewSone.html?sone=${word.removePrefix("sone://")}")
54 word.removePrefix("post://").let(soneRequest.core::getPost) != null -> redirect("viewPost.html?post=${word.removePrefix("post://")}")
55 word.removePrefix("reply://").let(soneRequest.core::getPostReply) != null -> redirect("viewPost.html?post=${word.removePrefix("reply://").let(soneRequest.core::getPostReply)?.postId}")
56 word.removePrefix("album://").let(soneRequest.core::getAlbum) != null -> redirect("imageBrowser.html?album=${word.removePrefix("album://")}")
57 word.removePrefix("image://").let { soneRequest.core.getImage(it, false) } != null -> redirect("imageBrowser.html?image=${word.removePrefix("image://")}")
62 val soneNameCache = { sone: Sone -> sone.names() }.memoize()
63 val sonePagination = soneRequest.core.sones
64 .scoreAndPaginate(phrases, soneRequest.core.preferences.postsPerPage) { it.allText(soneNameCache) }
65 .apply { page = soneRequest.parameters["sonePage"].emptyToNull?.toIntOrNull() ?: 0 }
66 val postPagination = cache.get(phrases) {
67 soneRequest.core.sones
68 .flatMap(Sone::getPosts)
69 .filter { Post.FUTURE_POSTS_FILTER.apply(it) }
70 .scoreAndPaginate(phrases, soneRequest.core.preferences.postsPerPage) { it.allText(soneNameCache, soneRequest.core::getReplies) }
71 }.apply { page = soneRequest.parameters["postPage"].emptyToNull?.toIntOrNull() ?: 0 }
73 Logger.normal(SearchPage::class.java, "Finished search for “${soneRequest.parameters["query"]}” in ${System.currentTimeMillis() - startTime}ms.")
74 templateContext["sonePagination"] = sonePagination
75 templateContext["soneHits"] = sonePagination.items
76 templateContext["postPagination"] = postPagination
77 templateContext["postHits"] = postPagination.items
80 private fun <T> Iterable<T>.scoreAndPaginate(phrases: Iterable<Phrase>, postsPerPage: Int, texter: (T) -> String) =
81 map { it to score(texter(it), phrases) }
82 .filter { it.second > 0 }
83 .sortedByDescending { it.second }
85 .paginate(postsPerPage)
87 private fun Sone.names() =
89 listOf(name, firstName, middleName, lastName)
94 private fun Sone.allText(soneNameCache: (Sone) -> String) =
95 (soneNameCache(this) + profile.fields.map { "${it.name} ${it.value}" }.joinToString(" ", " ")).toLowerCase()
97 private fun Post.allText(soneNameCache: (Sone) -> String, getReplies: (String) -> Collection<PostReply>) =
98 (text + recipient.orNull()?.let { " ${soneNameCache(it)}" } + getReplies(id)
99 .filter { PostReply.FUTURE_REPLY_FILTER.apply(it) }
100 .map { "${soneNameCache(it.sone)} ${it.text}" }.joinToString(" ", " ")).toLowerCase()
102 private fun Iterable<Phrase>.indicesFor(text: String, predicate: (Phrase) -> Boolean) =
103 filter(predicate).map(Phrase::phrase).map(String::toLowerCase).flatMap { text.findAll(it) }
105 private fun score(text: String, phrases: Iterable<Phrase>): Double {
106 val requiredPhrases = phrases.count { it.required }
107 val requiredHits = phrases.indicesFor(text, Phrase::required)
108 .map { Math.pow(1 - it / text.length.toDouble(), 2.0) }
110 val optionalHits = phrases.indicesFor(text, Phrase::optional)
111 .map { Math.pow(1 - it / text.length.toDouble(), 2.0) }
113 val forbiddenHits = phrases.indicesFor(text, Phrase::forbidden)
115 return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2)
118 private fun String.findAll(needle: String) =
119 generateSequence(indexOf(needle).takeIf { it > -1 }) { lastPosition ->
121 .let { indexOf(needle, it + 1) }
125 private fun String.parse() =
126 StringEscaper.parseLine(this)
129 it == "+" || it == "-" -> Phrase(it, OPTIONAL)
130 it.startsWith("+") -> Phrase(it.drop(1), REQUIRED)
131 it.startsWith("-") -> Phrase(it.drop(1), FORBIDDEN)
132 else -> Phrase(it, OPTIONAL)
136 private fun redirect(target: String): Nothing = throw RedirectException(target)
138 enum class Optionality {
144 private data class Phrase(val phrase: String, val optionality: Optionality) {
145 val required = optionality == REQUIRED
146 val forbidden = optionality == FORBIDDEN
147 val optional = optionality == OPTIONAL