Use method from JsonPage
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / ajax / GetLinkedElementAjaxPage.kt
1 package net.pterodactylus.sone.web.ajax
2
3 import com.fasterxml.jackson.databind.JsonNode
4 import com.fasterxml.jackson.databind.ObjectMapper
5 import net.pterodactylus.sone.core.ElementLoader
6 import net.pterodactylus.sone.core.LinkedElement
7 import net.pterodactylus.sone.template.LinkedElementRenderFilter
8 import net.pterodactylus.sone.utils.jsonArray
9 import net.pterodactylus.sone.utils.jsonObject
10 import net.pterodactylus.sone.web.WebInterface
11 import net.pterodactylus.sone.web.page.FreenetRequest
12
13 /**
14  * Renders linked elements after they have been loaded.
15  */
16 class GetLinkedElementAjaxPage(webInterface: WebInterface, private val elementLoader: ElementLoader, private val linkedElementRenderFilter: LinkedElementRenderFilter):
17                 JsonPage("getLinkedElement.ajax", webInterface) {
18
19         override fun createJsonObject(request: FreenetRequest): JsonReturnObject =
20                         request.httpRequest.getParam("elements", "[]").asJson()
21                                         .map(JsonNode::asText)
22                                         .map(elementLoader::loadElement)
23                                         .filterNot { it.loading }
24                                         .map { it to renderLinkedElement(it) }
25                                         .let { elements ->
26                                                 jsonArray(
27                                                                 *(elements.map { element ->
28                                                                         jsonObject {
29                                                                                 put("link", element.first.link)
30                                                                                 put("html", element.second)
31                                                                         }
32                                                                 }.toTypedArray())
33                                                 )
34                                         }.let { linkedElements ->
35                                 createSuccessJsonObject().apply {
36                                         put("linkedElements", linkedElements)
37                                 }
38                         }
39
40         override fun needsFormPassword() = false
41         override fun requiresLogin() = false
42
43         private fun String.asJson() = ObjectMapper().readTree(this).asIterable()
44
45         private fun renderLinkedElement(linkedElement: LinkedElement) =
46                         linkedElementRenderFilter.format(null, linkedElement, emptyMap())
47
48 }