2b1deca1215e81184b0a37cf592a003a6a59a62f
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / ajax / GetPostAjaxPage.kt
1 package net.pterodactylus.sone.web.ajax
2
3 import net.pterodactylus.sone.data.Post
4 import net.pterodactylus.sone.data.Sone
5 import net.pterodactylus.sone.utils.jsonObject
6 import net.pterodactylus.sone.utils.let
7 import net.pterodactylus.sone.utils.parameters
8 import net.pterodactylus.sone.utils.render
9 import net.pterodactylus.sone.web.WebInterface
10 import net.pterodactylus.sone.web.page.FreenetRequest
11 import net.pterodactylus.util.template.Template
12
13 /**
14  * This AJAX handler retrieves information and rendered representation of a [Post].
15  */
16 class GetPostAjaxPage(webInterface: WebInterface, private val postTemplate: Template) : LoggedInJsonPage("getPost.ajax", webInterface) {
17
18         override fun needsFormPassword() = false
19
20         override fun createJsonObject(currentSone: Sone, request: FreenetRequest) =
21                         request.parameters["post"]
22                                         .let(core::getPost)
23                                         .let { post ->
24                                                 createSuccessJsonObject().
25                                                                 put("post", jsonObject(
26                                                                                 "id" to post.id,
27                                                                                 "sone" to post.sone.id,
28                                                                                 "time" to post.time,
29                                                                                 "recipient" to post.recipientId.orNull(),
30                                                                                 "html" to post.render(currentSone, request)
31                                                                 ))
32                                         } ?: createErrorJsonObject("invalid-post-id")
33
34         private fun Post.render(currentSone: Sone, request: FreenetRequest) =
35                         webInterface.templateContextFactory.createTemplateContext().apply {
36                                 set("core", core)
37                                 set("request", request)
38                                 set("post", this@render)
39                                 set("currentSone", currentSone)
40                                 set("localSones", core.localSones)
41                         }.let { postTemplate.render(it) }
42
43 }