1 package net.pterodactylus.sone.web.ajax
3 import net.pterodactylus.sone.data.Sone
4 import net.pterodactylus.sone.data.SoneOptions
5 import net.pterodactylus.sone.main.SonePlugin
6 import net.pterodactylus.sone.utils.jsonArray
7 import net.pterodactylus.sone.utils.jsonObject
8 import net.pterodactylus.sone.web.WebInterface
9 import net.pterodactylus.sone.web.page.FreenetRequest
10 import net.pterodactylus.util.notify.Notification
11 import net.pterodactylus.util.notify.TemplateNotification
12 import java.io.StringWriter
13 import javax.inject.Inject
16 * AJAX handler to return all current notifications.
18 class GetNotificationsAjaxPage @Inject constructor(webInterface: WebInterface) :
19 JsonPage("getNotifications.ajax", webInterface) {
21 override val needsFormPassword = false
22 override val requiresLogin = false
24 override fun createJsonObject(request: FreenetRequest) =
25 getCurrentSone(request.toadletContext, false).let { currentSone ->
26 webInterface.getNotifications(currentSone)
27 .sortedBy(Notification::getCreatedTime)
28 .let { notifications ->
29 createSuccessJsonObject().apply {
30 put("notificationHash", notifications.hashCode())
31 put("options", currentSone?.options.asJsonObject)
32 put("notifications", notifications.asJsonObject(currentSone, request))
37 private fun Collection<Notification>.asJsonObject(currentSone: Sone?, freenetRequest: FreenetRequest) = jsonArray(
38 *map { notification ->
40 "id" to notification.id,
41 "createdTime" to notification.createdTime,
42 "lastUpdatedTime" to notification.lastUpdatedTime,
43 "dismissable" to notification.isDismissable,
44 "text" to if (notification is TemplateNotification) notification.render(currentSone, freenetRequest) else notification.render()
49 private fun TemplateNotification.render(currentSone: Sone?, freenetRequest: FreenetRequest) = StringWriter().use {
50 val mergedTemplateContext = webInterface.templateContextFactory.createTemplateContext()
51 .mergeContext(templateContext)
54 this["currentSone"] = currentSone
55 this["localSones"] = core.localSones
56 this["request"] = freenetRequest
57 this["currentVersion"] = SonePlugin.getPluginVersion()
58 this["hasLatestVersion"] = core.updateChecker.hasLatestVersion()
59 this["latestEdition"] = core.updateChecker.latestEdition
60 this["latestVersion"] = core.updateChecker.latestVersion
61 this["latestVersionTime"] = core.updateChecker.latestVersionDate
62 this["notification"] = this@render
64 it.also { render(mergedTemplateContext, it) }
69 private val SoneOptions?.asJsonObject
70 get() = this?.let { options ->
72 "ShowNotification/NewSones" to options.isShowNewSoneNotifications,
73 "ShowNotification/NewPosts" to options.isShowNewPostNotifications,
74 "ShowNotification/NewReplies" to options.isShowNewReplyNotifications
78 private fun Notification.render() = StringWriter().use { it.also { render(it) } }.toString()