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.*
7 import net.pterodactylus.sone.web.WebInterface
8 import net.pterodactylus.sone.web.page.*
9 import net.pterodactylus.util.notify.Notification
10 import net.pterodactylus.util.notify.TemplateNotification
11 import java.io.StringWriter
12 import javax.inject.Inject
15 * AJAX handler to return all current notifications.
17 @ToadletPath("getNotifications.ajax")
18 class GetNotificationsAjaxPage @Inject constructor(webInterface: WebInterface) : JsonPage(webInterface) {
20 override val needsFormPassword = false
21 override val requiresLogin = false
23 override fun createJsonObject(request: FreenetRequest) =
24 getCurrentSone(request.toadletContext, false).let { currentSone ->
25 webInterface.getNotifications(currentSone)
26 .sortedBy(Notification::getCreatedTime)
27 .let { notifications ->
28 createSuccessJsonObject().apply {
29 put("notificationHash", notifications.hashCode())
30 put("options", currentSone?.options.asJsonObject)
31 put("notifications", notifications.asJsonObject(currentSone, request))
36 private fun Collection<Notification>.asJsonObject(currentSone: Sone?, freenetRequest: FreenetRequest) = jsonArray(
37 *map { notification ->
39 "id" to notification.id,
40 "createdTime" to notification.createdTime,
41 "lastUpdatedTime" to notification.lastUpdatedTime,
42 "dismissable" to notification.isDismissable,
43 "text" to if (notification is TemplateNotification) notification.render(currentSone, freenetRequest) else notification.render()
48 private fun TemplateNotification.render(currentSone: Sone?, freenetRequest: FreenetRequest) = StringWriter().use {
49 val mergedTemplateContext = webInterface.templateContextFactory.createTemplateContext()
50 .mergeContext(templateContext)
53 this["currentSone"] = currentSone
54 this["localSones"] = core.localSones
55 this["request"] = freenetRequest
56 this["currentVersion"] = SonePlugin.getPluginVersion()
57 this["hasLatestVersion"] = core.updateChecker.hasLatestVersion()
58 this["latestEdition"] = core.updateChecker.latestEdition
59 this["latestVersion"] = core.updateChecker.latestVersion
60 this["latestVersionTime"] = core.updateChecker.latestVersionDate
61 this["notification"] = this@render
63 it.also { render(mergedTemplateContext, it) }
68 private val SoneOptions?.asJsonObject
69 get() = this?.let { options ->
71 "ShowNotification/NewSones" to options.isShowNewSoneNotifications,
72 "ShowNotification/NewPosts" to options.isShowNewPostNotifications,
73 "ShowNotification/NewReplies" to options.isShowNewReplyNotifications