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
15 * AJAX handler to return all current notifications.
17 class GetNotificationsAjaxPage(webInterface: WebInterface) : JsonPage("getNotifications.ajax", webInterface) {
19 override fun needsFormPassword() = false
20 override fun requiresLogin() = false
22 override fun createJsonObject(request: FreenetRequest) =
23 getCurrentSone(request.toadletContext, false).let { currentSone ->
24 webInterface.getNotifications(currentSone)
25 .sortedBy(Notification::getCreatedTime)
26 .let { notifications ->
27 createSuccessJsonObject().apply {
28 put("notificationHash", notifications.hashCode())
29 put("options", currentSone?.options.asJsonObject)
30 put("notifications", notifications.asJsonObject(currentSone, request))
35 private fun Collection<Notification>.asJsonObject(currentSone: Sone?, freenetRequest: FreenetRequest) = jsonArray(
36 *map { notification ->
38 "id" to notification.id,
39 "createdTime" to notification.createdTime,
40 "lastUpdatedTime" to notification.lastUpdatedTime,
41 "dismissable" to notification.isDismissable,
42 "text" to if (notification is TemplateNotification) notification.render(currentSone, freenetRequest) else notification.render()
47 private fun TemplateNotification.render(currentSone: Sone?, freenetRequest: FreenetRequest) = StringWriter().use {
48 val mergedTemplateContext = webInterface.templateContextFactory.createTemplateContext()
49 .mergeContext(templateContext)
51 this["core"] = webInterface.core
52 this["currentSone"] = currentSone
53 this["localSones"] = webInterface.core.localSones
54 this["request"] = freenetRequest
55 this["currentVersion"] = SonePlugin.getPluginVersion()
56 this["hasLatestVersion"] = webInterface.core.updateChecker.hasLatestVersion()
57 this["latestEdition"] = webInterface.core.updateChecker.latestEdition
58 this["latestVersion"] = webInterface.core.updateChecker.latestVersion
59 this["latestVersionTime"] = webInterface.core.updateChecker.latestVersionDate
60 this["notification"] = this@render
62 it.also { render(mergedTemplateContext, it) }
67 private val SoneOptions?.asJsonObject
68 get() = this?.let { options ->
70 "ShowNotification/NewSones" to options.isShowNewSoneNotifications,
71 "ShowNotification/NewPosts" to options.isShowNewPostNotifications,
72 "ShowNotification/NewReplies" to options.isShowNewReplyNotifications
76 private fun Notification.render() = StringWriter().use { it.also { render(it) } }.toString()