From 8572a749a619643392c776208027b3d0209e8f4c Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Fri, 6 Oct 2017 22:40:09 +0200 Subject: [PATCH] Replace Sone template page with Kotlin version --- .../sone/web/pages/SoneTemplatePage.java | 270 --------------------- .../sone/web/pages/SoneTemplatePage.kt | 101 ++++++++ .../sone/web/pages/SoneTemplatePageTest.kt | 49 +--- 3 files changed, 102 insertions(+), 318 deletions(-) delete mode 100644 src/main/java/net/pterodactylus/sone/web/pages/SoneTemplatePage.java create mode 100644 src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt diff --git a/src/main/java/net/pterodactylus/sone/web/pages/SoneTemplatePage.java b/src/main/java/net/pterodactylus/sone/web/pages/SoneTemplatePage.java deleted file mode 100644 index adc4a3a..0000000 --- a/src/main/java/net/pterodactylus/sone/web/pages/SoneTemplatePage.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Sone - SoneTemplatePage.java - Copyright © 2010–2016 David Roden - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.pterodactylus.sone.web.pages; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import net.pterodactylus.sone.data.Sone; -import net.pterodactylus.sone.main.SonePlugin; -import net.pterodactylus.sone.web.SessionProvider; -import net.pterodactylus.sone.web.WebInterface; -import net.pterodactylus.sone.web.page.FreenetRequest; -import net.pterodactylus.sone.web.page.FreenetTemplatePage; -import net.pterodactylus.util.notify.Notification; -import net.pterodactylus.util.template.Template; -import net.pterodactylus.util.template.TemplateContext; - -import freenet.clients.http.ToadletContext; -import freenet.support.api.HTTPRequest; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Base page for the Sone web interface. - * - * @author David ‘Bombe’ Roden - */ -public class SoneTemplatePage extends FreenetTemplatePage { - - /** The Sone core. */ - protected final WebInterface webInterface; - protected final SessionProvider sessionProvider; - - /** The page title l10n key. */ - private final String pageTitleKey; - - /** Whether to require a login. */ - private final boolean requireLogin; - - /** - * Creates a new template page for Sone that does not require the user to be - * logged in. - * - * @param path - * The path of the page - * @param template - * The template to render - * @param pageTitleKey - * The l10n key of the page title - * @param webInterface - * The Sone web interface - */ - public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface) { - this(path, template, pageTitleKey, webInterface, false); - } - - /** - * Creates a new template page for Sone. - * - * @param path - * The path of the page - * @param template - * The template to render - * @param webInterface - * The Sone web interface - * @param requireLogin - * Whether this page requires a login - */ - public SoneTemplatePage(String path, Template template, WebInterface webInterface, boolean requireLogin) { - this(path, template, null, webInterface, requireLogin); - } - - /** - * Creates a new template page for Sone. - * - * @param path - * The path of the page - * @param template - * The template to render - * @param pageTitleKey - * The l10n key of the page title - * @param webInterface - * The Sone web interface - * @param requireLogin - * Whether this page requires a login - */ - public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface, boolean requireLogin) { - super(path, webInterface.getTemplateContextFactory(), template, "noPermission.html"); - this.pageTitleKey = pageTitleKey; - this.webInterface = webInterface; - this.sessionProvider = webInterface; - this.requireLogin = requireLogin; - } - - // - // PROTECTED METHODS - // - - @Nullable - protected Sone getCurrentSone(@Nonnull ToadletContext toadletContext) { - return getCurrentSone(toadletContext, true); - } - - @Nullable - protected Sone getCurrentSone(@Nonnull ToadletContext toadletContext, boolean createSession) { - return sessionProvider.getCurrentSone(toadletContext, createSession); - } - - protected void setCurrentSone(@Nonnull ToadletContext toadletContext, @Nullable Sone sone) { - sessionProvider.setCurrentSone(toadletContext, sone); - } - - // - // TEMPLATEPAGE METHODS - // - - /** - * {@inheritDoc} - */ - @Override - protected String getPageTitle(FreenetRequest request) { - if (pageTitleKey != null) { - return webInterface.getL10n().getString(pageTitleKey); - } - return ""; - } - - /** - * {@inheritDoc} - */ - @Override - protected List> getAdditionalLinkNodes(FreenetRequest request) { - return ImmutableList.> builder().add(ImmutableMap. builder().put("rel", "search").put("type", "application/opensearchdescription+xml").put("title", "Sone").put("href", "http://" + request.getHttpRequest().getHeader("host") + "/Sone/OpenSearch.xml").build()).build(); - } - - /** - * {@inheritDoc} - */ - @Override - protected Collection getStyleSheets() { - return Arrays.asList("css/sone.css"); - } - - /** - * {@inheritDoc} - */ - @Override - protected String getShortcutIcon() { - return "images/icon.png"; - } - - /** - * Returns whether this page requires the user to log in. - * - * @return {@code true} if the user is required to be logged in to use this - * page, {@code false} otherwise - */ - protected boolean requiresLogin() { - return requireLogin; - } - - /** - * {@inheritDoc} - */ - @Override - protected final void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException { - super.processTemplate(request, templateContext); - Sone currentSone = getCurrentSone(request.getToadletContext(), false); - templateContext.set("preferences", webInterface.getCore().getPreferences()); - templateContext.set("currentSone", currentSone); - templateContext.set("localSones", webInterface.getCore().getLocalSones()); - templateContext.set("request", request); - templateContext.set("currentVersion", SonePlugin.getPluginVersion()); - templateContext.set("hasLatestVersion", webInterface.getCore().getUpdateChecker().hasLatestVersion()); - templateContext.set("latestEdition", webInterface.getCore().getUpdateChecker().getLatestEdition()); - templateContext.set("latestVersion", webInterface.getCore().getUpdateChecker().getLatestVersion()); - templateContext.set("latestVersionTime", webInterface.getCore().getUpdateChecker().getLatestVersionDate()); - List notifications = new ArrayList(webInterface.getNotifications(currentSone)); - Collections.sort(notifications, Notification.CREATED_TIME_SORTER); - templateContext.set("notifications", notifications); - templateContext.set("notificationHash", notifications.hashCode()); - handleRequest(request, templateContext); - } - - protected void handleRequest(@Nonnull FreenetRequest request, @Nonnull TemplateContext templateContext) throws RedirectException { - } - - /** - * {@inheritDoc} - */ - @Override - protected String getRedirectTarget(FreenetRequest request) { - if (requiresLogin() && (getCurrentSone(request.getToadletContext(), false) == null)) { - HTTPRequest httpRequest = request.getHttpRequest(); - String originalUrl = httpRequest.getPath(); - if (httpRequest.hasParameters()) { - StringBuilder requestParameters = new StringBuilder(); - for (String parameterName : httpRequest.getParameterNames()) { - if (requestParameters.length() > 0) { - requestParameters.append("&"); - } - String[] parameterValues = httpRequest.getMultipleParam(parameterName); - for (String parameterValue : parameterValues) { - requestParameters.append(urlEncode(parameterName)).append("=").append(urlEncode(parameterValue)); - } - } - originalUrl += "?" + requestParameters.toString(); - } - return "login.html?target=" + urlEncode(originalUrl); - } - return null; - } - - private static String urlEncode(String value) { - try { - return URLEncoder.encode(value, "UTF-8"); - } catch (UnsupportedEncodingException uee1) { - /* A JVM without UTF-8? I don’t think so. */ - throw new RuntimeException(uee1); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean isFullAccessOnly() { - return webInterface.getCore().getPreferences().isRequireFullAccess(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isEnabled(ToadletContext toadletContext) { - if (webInterface.getCore().getPreferences().isRequireFullAccess() && !toadletContext.isAllowedFullAccess()) { - return false; - } - if (requiresLogin()) { - return getCurrentSone(toadletContext, false) != null; - } - return true; - } - -} diff --git a/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt b/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt new file mode 100644 index 0000000..4d0fa3f --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePage.kt @@ -0,0 +1,101 @@ +package net.pterodactylus.sone.web.pages + +import freenet.clients.http.ToadletContext +import net.pterodactylus.sone.data.Sone +import net.pterodactylus.sone.main.SonePlugin +import net.pterodactylus.sone.utils.emptyToNull +import net.pterodactylus.sone.web.SessionProvider +import net.pterodactylus.sone.web.WebInterface +import net.pterodactylus.sone.web.page.FreenetRequest +import net.pterodactylus.sone.web.page.FreenetTemplatePage +import net.pterodactylus.util.notify.Notification +import net.pterodactylus.util.template.Template +import net.pterodactylus.util.template.TemplateContext +import java.net.URLEncoder + +/** + * Base page for the Sone web interface. + */ +open class SoneTemplatePage( + path: String, + protected val webInterface: WebInterface, + template: Template, + private val pageTitleKey: String? = null, + private val requiresLogin: Boolean = true +) : FreenetTemplatePage(path, webInterface.templateContextFactory, template, "noPermission.html") { + + @JvmOverloads + constructor(path: String, template: Template, pageTitleKey: String?, webInterface: WebInterface, requireLogin: Boolean = false) : + this(path, webInterface, template, pageTitleKey, requireLogin) + + constructor(path: String, template: Template, webInterface: WebInterface, requireLogin: Boolean = true) : + this(path, webInterface, template, null, requireLogin) + + private val core = webInterface.core + protected val sessionProvider: SessionProvider = webInterface + + protected fun getCurrentSone(toadletContext: ToadletContext, createSession: Boolean = true) = + sessionProvider.getCurrentSone(toadletContext, createSession) + + protected fun setCurrentSone(toadletContext: ToadletContext, sone: Sone?) = + sessionProvider.setCurrentSone(toadletContext, sone) + + fun requiresLogin() = requiresLogin + + override public fun getPageTitle(request: FreenetRequest) = + pageTitleKey?.let(webInterface.l10n::getString) ?: "" + + override public fun getStyleSheets() = + listOf("css/sone.css") + + override public fun getShortcutIcon() = "images/icon.png" + + override public fun getAdditionalLinkNodes(request: FreenetRequest) = + listOf(mapOf( + "rel" to "search", + "type" to "application/opensearchdescription+xml", + "title" to "Sone", + "href" to "http://${request.httpRequest.getHeader("host")}/Sone/OpenSearch.xml" + )) + + override public fun processTemplate(freenetRequest: FreenetRequest, templateContext: TemplateContext) { + super.processTemplate(freenetRequest, templateContext) + templateContext["preferences"] = core.preferences + templateContext["currentSone"] = getCurrentSone(freenetRequest.toadletContext) + templateContext["localSones"] = core.localSones + templateContext["request"] = freenetRequest + templateContext["currentVersion"] = SonePlugin.getPluginVersion() + templateContext["hasLatestVersion"] = core.updateChecker.hasLatestVersion() + templateContext["latestEdition"] = core.updateChecker.latestEdition + templateContext["latestVersion"] = core.updateChecker.latestVersion + templateContext["latestVersionTime"] = core.updateChecker.latestVersionDate + webInterface.getNotifications(getCurrentSone(freenetRequest.toadletContext)).sortedBy(Notification::getCreatedTime).run { + templateContext["notifications"] = this + templateContext["notificationHash"] = this.hashCode() + } + handleRequest(freenetRequest, templateContext) + } + + internal open fun handleRequest(request: FreenetRequest, templateContext: TemplateContext) { + } + + override public fun getRedirectTarget(request: FreenetRequest): String? { + if (requiresLogin && getCurrentSone(request.toadletContext) == null) { + val parameters = request.httpRequest.parameterNames + .flatMap { name -> request.httpRequest.getMultipleParam(name).map { name to it } } + .joinToString("&") { "${it.first.urlEncode}=${it.second.urlEncode}" } + .emptyToNull + return "login.html?target=${request.httpRequest.path}${parameters?.let { ("?" + it).urlEncode } ?: ""}" + } + return null + } + + private val String.urlEncode: String get() = URLEncoder.encode(this, "UTF-8") + + override fun isEnabled(toadletContext: ToadletContext) = when { + requiresLogin && getCurrentSone(toadletContext) == null -> false + core.preferences.isRequireFullAccess && !toadletContext.isAllowedFullAccess -> false + else -> true + } + +} diff --git a/src/test/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePageTest.kt b/src/test/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePageTest.kt index 10dfb6e..3993cda 100644 --- a/src/test/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePageTest.kt +++ b/src/test/kotlin/net/pterodactylus/sone/web/pages/SoneTemplatePageTest.kt @@ -16,33 +16,11 @@ import org.hamcrest.Matchers.containsInAnyOrder import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.nullValue import org.junit.Test -import org.mockito.Mockito.verify /** * Unit test for [SoneTemplatePage]. */ -class SoneTemplatePageTest: WebPageTest({ template, webInterface -> object : SoneTemplatePage("path.html", template, webInterface, true) {}}) { - - @Test - fun `current sone is retrieved from web interface`() { - assertThat(page.getCurrentSone(toadletContext), equalTo(currentSone)) - } - - @Test - fun `retrieving current sone without creation is forwarded to web interface`() { - mock().let { - whenever(webInterface.getCurrentSone(toadletContext, false)).thenReturn(it) - assertThat(page.getCurrentSone(toadletContext, false), equalTo(it)) - } - } - - @Test - fun `setting the current sone is forwarded to web interface`() { - mock().let { - page.setCurrentSone(toadletContext, it) - verify(webInterface).setCurrentSone(toadletContext, it) - } - } +class SoneTemplatePageTest : WebPageTest({ template, webInterface -> object : SoneTemplatePage("path.html", template, webInterface, true) {} }) { @Test fun `page title is empty string if no page title key was given`() { @@ -80,20 +58,6 @@ class SoneTemplatePageTest: WebPageTest({ template, webInterface -> object : Son assertThat(page.shortcutIcon, equalTo("images/icon.png")) } - @Test - fun `page requires login if require login was specified in the constructor`() { - SoneTemplatePage("path.html", template, webInterface, true).let { page -> - assertThat(page.requiresLogin(), equalTo(true)) - } - } - - @Test - fun `page does not require login if require login was not specified in the constructor`() { - SoneTemplatePage("path.html", template, webInterface, false).let { page -> - assertThat(page.requiresLogin(), equalTo(false)) - } - } - private fun verifyVariableIsSet(name: String, value: Any) = verifyVariableMatches(name, equalTo(value)) private fun verifyVariableMatches(name: String, matcher: Matcher) { @@ -220,17 +184,6 @@ class SoneTemplatePageTest: WebPageTest({ template, webInterface -> object : Son } @Test - fun `full access requirement is correctly forwarded from the preferences if false`() { - assertThat(page.isFullAccessOnly, equalTo(false)) - } - - @Test - fun `full access requirement is correctly forwarded from the preferences if true`() { - core.preferences.isRequireFullAccess = true - assertThat(page.isFullAccessOnly, equalTo(true)) - } - - @Test fun `page is disabled if full access is required but request does not have full access`() { core.preferences.isRequireFullAccess = true assertThat(page.isEnabled(toadletContext), equalTo(false)) -- 2.7.4