X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fmain%2Fkotlin%2Fnet%2Fpterodactylus%2Fsone%2Fweb%2Fajax%2FGetLikesAjaxPage.kt;fp=src%2Fmain%2Fkotlin%2Fnet%2Fpterodactylus%2Fsone%2Fweb%2Fajax%2FGetLikesAjaxPage.kt;h=fc2142d3fd8f84e3198e7f633986dce1610c16d4;hb=889b7b47200adb464d44604a812e7bbb1ba89e1f;hp=0000000000000000000000000000000000000000;hpb=c3407a682f9f81b27d0354e59fe9e3d3d6dffcd6;p=Sone.git diff --git a/src/main/kotlin/net/pterodactylus/sone/web/ajax/GetLikesAjaxPage.kt b/src/main/kotlin/net/pterodactylus/sone/web/ajax/GetLikesAjaxPage.kt new file mode 100644 index 0000000..fc2142d --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/sone/web/ajax/GetLikesAjaxPage.kt @@ -0,0 +1,45 @@ +package net.pterodactylus.sone.web.ajax + +import net.pterodactylus.sone.data.Sone +import net.pterodactylus.sone.template.SoneAccessor +import net.pterodactylus.sone.utils.jsonArray +import net.pterodactylus.sone.utils.jsonObject +import net.pterodactylus.sone.utils.let +import net.pterodactylus.sone.utils.parameters +import net.pterodactylus.sone.web.WebInterface +import net.pterodactylus.sone.web.page.FreenetRequest + +/** + * AJAX page that retrieves the number of “likes” a [net.pterodactylus.sone.data.Post] + * or [net.pterodactylus.sone.data.PostReply] has. + */ +class GetLikesAjaxPage(webInterface: WebInterface) : JsonPage("getLikes.ajax", webInterface) { + + override fun needsFormPassword() = false + + override fun createJsonObject(request: FreenetRequest) = + when (request.parameters["type"]) { + "post" -> request.parameters["post"] + .let(webInterface.core::getPost) + ?.let(webInterface.core::getLikes) + ?.toReply() + ?: createErrorJsonObject("invalid-post-id") + "reply" -> request.parameters["reply"] + .let(webInterface.core::getPostReply) + ?.let(webInterface.core::getLikes) + ?.toReply() + ?: createErrorJsonObject("invalid-reply-id") + else -> createErrorJsonObject("invalid-type") + } + + private fun Set.toReply() = createSuccessJsonObject().apply { + put("likes", size) + put("sones", sortedBy { SoneAccessor.getNiceName(it) } + .map { + jsonObject("id" to it.id, "name" to SoneAccessor.getNiceName(it)) + } + .let { jsonArray(*it.toTypedArray()) } + ) + } + +}