d9800720d49239e7c77cb39226b684a0d6a9ad56
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / pages / SearchPage.kt
1 package net.pterodactylus.sone.web.pages
2
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
27
28 /**
29  * This page lets the user search for posts and replies that contain certain
30  * words.
31  */
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") {
34
35         @Inject constructor(template: Template, webInterface: WebInterface, loaders: Loaders) :
36                         this(template, webInterface, loaders, Ticker.systemTicker())
37
38         private val cache: Cache<Iterable<Phrase>, Pagination<Post>> = CacheBuilder.newBuilder().ticker(ticker).expireAfterAccess(5, MINUTES).build()
39
40         override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) {
41                 val startTime = System.currentTimeMillis()
42                 val phrases = try {
43                         soneRequest.parameters["query"].emptyToNull?.parse()
44                 } catch (te: TextException) {
45                         redirect("index.html")
46                 }
47                                 ?: redirect("index.html")
48
49                 when (phrases.size) {
50                         0 -> redirect("index.html")
51                         1 -> phrases.first().phrase.also { word ->
52                                 when {
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://")}")
58                                 }
59                         }
60                 }
61
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 }
72
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
78         }
79
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 }
84                                         .map { it.first }
85                                         .paginate(postsPerPage)
86
87         private fun Sone.names() =
88                         with(profile) {
89                                 listOf(name, firstName, middleName, lastName)
90                                                 .filterNotNull()
91                                                 .joinToString("")
92                         }
93
94         private fun Sone.allText(soneNameCache: (Sone) -> String) =
95                         (soneNameCache(this) + profile.fields.map { "${it.name} ${it.value}" }.joinToString(" ", " ")).toLowerCase()
96
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()
101
102         private fun Iterable<Phrase>.indicesFor(text: String, predicate: (Phrase) -> Boolean) =
103                         filter(predicate).map(Phrase::phrase).map(String::toLowerCase).flatMap { text.findAll(it) }
104
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) }
109                                 .sum()
110                 val optionalHits = phrases.indicesFor(text, Phrase::optional)
111                                 .map { Math.pow(1 - it / text.length.toDouble(), 2.0) }
112                                 .sum()
113                 val forbiddenHits = phrases.indicesFor(text, Phrase::forbidden)
114                                 .count()
115                 return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2)
116         }
117
118         private fun String.findAll(needle: String) =
119                         generateSequence(indexOf(needle).takeIf { it > -1 }) { lastPosition ->
120                                 lastPosition
121                                                 .let { indexOf(needle, it + 1) }
122                                                 .takeIf { it > -1 }
123                         }.toList()
124
125         private fun String.parse() =
126                         StringEscaper.parseLine(this)
127                                         .map {
128                                                 when {
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)
133                                                 }
134                                         }
135
136         private fun redirect(target: String): Nothing = throw RedirectException(target)
137
138         enum class Optionality {
139                 OPTIONAL,
140                 REQUIRED,
141                 FORBIDDEN
142         }
143
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
148         }
149
150 }