Add unit test for sone template page and fix parameter encoding
[Sone.git] / src / main / java / net / pterodactylus / sone / web / SoneTemplatePage.java
1 /*
2  * Sone - SoneTemplatePage.java - Copyright © 2010–2016 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web;
19
20 import java.io.UnsupportedEncodingException;
21 import java.net.URLEncoder;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.annotation.Nonnull;
30
31 import net.pterodactylus.sone.data.Sone;
32 import net.pterodactylus.sone.main.SonePlugin;
33 import net.pterodactylus.sone.web.page.FreenetRequest;
34 import net.pterodactylus.sone.web.page.FreenetTemplatePage;
35 import net.pterodactylus.util.notify.Notification;
36 import net.pterodactylus.util.template.Template;
37 import net.pterodactylus.util.template.TemplateContext;
38
39 import freenet.clients.http.SessionManager.Session;
40 import freenet.clients.http.ToadletContext;
41 import freenet.support.api.HTTPRequest;
42
43 import com.google.common.collect.ImmutableList;
44 import com.google.common.collect.ImmutableMap;
45
46 /**
47  * Base page for the Sone web interface.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class SoneTemplatePage extends FreenetTemplatePage {
52
53         /** The Sone core. */
54         protected final WebInterface webInterface;
55
56         /** The page title l10n key. */
57         private final String pageTitleKey;
58
59         /** Whether to require a login. */
60         private final boolean requireLogin;
61
62         /**
63          * Creates a new template page for Sone that does not require the user to be
64          * logged in.
65          *
66          * @param path
67          *            The path of the page
68          * @param template
69          *            The template to render
70          * @param pageTitleKey
71          *            The l10n key of the page title
72          * @param webInterface
73          *            The Sone web interface
74          */
75         public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface) {
76                 this(path, template, pageTitleKey, webInterface, false);
77         }
78
79         /**
80          * Creates a new template page for Sone.
81          *
82          * @param path
83          *            The path of the page
84          * @param template
85          *            The template to render
86          * @param webInterface
87          *            The Sone web interface
88          * @param requireLogin
89          *            Whether this page requires a login
90          */
91         public SoneTemplatePage(String path, Template template, WebInterface webInterface, boolean requireLogin) {
92                 this(path, template, null, webInterface, requireLogin);
93         }
94
95         /**
96          * Creates a new template page for Sone.
97          *
98          * @param path
99          *            The path of the page
100          * @param template
101          *            The template to render
102          * @param pageTitleKey
103          *            The l10n key of the page title
104          * @param webInterface
105          *            The Sone web interface
106          * @param requireLogin
107          *            Whether this page requires a login
108          */
109         public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface, boolean requireLogin) {
110                 super(path, webInterface.getTemplateContextFactory(), template, "noPermission.html");
111                 this.pageTitleKey = pageTitleKey;
112                 this.webInterface = webInterface;
113                 this.requireLogin = requireLogin;
114         }
115
116         //
117         // PROTECTED METHODS
118         //
119
120         /**
121          * Returns the current session, creating a new session if there is no
122          * current session.
123          *
124          * @param toadletContenxt
125          *            The toadlet context
126          * @return The current session, or {@code null} if there is no current
127          *         session
128          */
129         protected Session getCurrentSession(ToadletContext toadletContenxt) {
130                 return webInterface.getCurrentSession(toadletContenxt);
131         }
132
133         /**
134          * Returns the current session, creating a new session if there is no
135          * current session and {@code create} is {@code true}.
136          *
137          * @param toadletContenxt
138          *            The toadlet context
139          * @param create
140          *            {@code true} to create a new session if there is no current
141          *            session, {@code false} otherwise
142          * @return The current session, or {@code null} if there is no current
143          *         session
144          */
145         protected Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
146                 return webInterface.getCurrentSession(toadletContenxt, create);
147         }
148
149         /**
150          * Returns the currently logged in Sone.
151          *
152          * @param toadletContext
153          *            The toadlet context
154          * @return The currently logged in Sone, or {@code null} if no Sone is
155          *         currently logged in
156          */
157         protected Sone getCurrentSone(ToadletContext toadletContext) {
158                 return webInterface.getCurrentSone(toadletContext);
159         }
160
161         /**
162          * Returns the currently logged in Sone.
163          *
164          * @param toadletContext
165          *            The toadlet context
166          * @param create
167          *            {@code true} to create a new session if no session exists,
168          *            {@code false} to not create a new session
169          * @return The currently logged in Sone, or {@code null} if no Sone is
170          *         currently logged in
171          */
172         protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
173                 return webInterface.getCurrentSone(toadletContext, create);
174         }
175
176         /**
177          * Sets the currently logged in Sone.
178          *
179          * @param toadletContext
180          *            The toadlet context
181          * @param sone
182          *            The Sone to set as currently logged in
183          */
184         protected void setCurrentSone(ToadletContext toadletContext, Sone sone) {
185                 webInterface.setCurrentSone(toadletContext, sone);
186         }
187
188         //
189         // TEMPLATEPAGE METHODS
190         //
191
192         /**
193          * {@inheritDoc}
194          */
195         @Override
196         protected String getPageTitle(FreenetRequest request) {
197                 if (pageTitleKey != null) {
198                         return webInterface.getL10n().getString(pageTitleKey);
199                 }
200                 return "";
201         }
202
203         /**
204          * {@inheritDoc}
205          */
206         @Override
207         protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
208                 return ImmutableList.<Map<String, String>> builder().add(ImmutableMap.<String, String> builder().put("rel", "search").put("type", "application/opensearchdescription+xml").put("title", "Sone").put("href", "http://" + request.getHttpRequest().getHeader("host") + "/Sone/OpenSearch.xml").build()).build();
209         }
210
211         /**
212          * {@inheritDoc}
213          */
214         @Override
215         protected Collection<String> getStyleSheets() {
216                 return Arrays.asList("css/sone.css");
217         }
218
219         /**
220          * {@inheritDoc}
221          */
222         @Override
223         protected String getShortcutIcon() {
224                 return "images/icon.png";
225         }
226
227         /**
228          * Returns whether this page requires the user to log in.
229          *
230          * @return {@code true} if the user is required to be logged in to use this
231          *         page, {@code false} otherwise
232          */
233         protected boolean requiresLogin() {
234                 return requireLogin;
235         }
236
237         /**
238          * {@inheritDoc}
239          */
240         @Override
241         protected final void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
242                 super.processTemplate(request, templateContext);
243                 Sone currentSone = getCurrentSone(request.getToadletContext(), false);
244                 templateContext.set("core", webInterface.getCore());
245                 templateContext.set("currentSone", currentSone);
246                 templateContext.set("localSones", webInterface.getCore().getLocalSones());
247                 templateContext.set("request", request);
248                 templateContext.set("currentVersion", SonePlugin.getPluginVersion());
249                 templateContext.set("hasLatestVersion", webInterface.getCore().getUpdateChecker().hasLatestVersion());
250                 templateContext.set("latestEdition", webInterface.getCore().getUpdateChecker().getLatestEdition());
251                 templateContext.set("latestVersion", webInterface.getCore().getUpdateChecker().getLatestVersion());
252                 templateContext.set("latestVersionTime", webInterface.getCore().getUpdateChecker().getLatestVersionDate());
253                 List<Notification> notifications = new ArrayList<Notification>(webInterface.getNotifications(currentSone));
254                 Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
255                 templateContext.set("notifications", notifications);
256                 templateContext.set("notificationHash", notifications.hashCode());
257                 handleRequest(request, templateContext);
258         }
259
260         protected void handleRequest(@Nonnull FreenetRequest request, @Nonnull TemplateContext templateContext) throws RedirectException {
261         }
262
263         /**
264          * {@inheritDoc}
265          */
266         @Override
267         protected String getRedirectTarget(FreenetRequest request) {
268                 if (requiresLogin() && (getCurrentSone(request.getToadletContext(), false) == null)) {
269                         HTTPRequest httpRequest = request.getHttpRequest();
270                         String originalUrl = httpRequest.getPath();
271                         if (httpRequest.hasParameters()) {
272                                 StringBuilder requestParameters = new StringBuilder();
273                                 for (String parameterName : httpRequest.getParameterNames()) {
274                                         if (requestParameters.length() > 0) {
275                                                 requestParameters.append("&");
276                                         }
277                                         String[] parameterValues = httpRequest.getMultipleParam(parameterName);
278                                         for (String parameterValue : parameterValues) {
279                                                 requestParameters.append(urlEncode(parameterName)).append("=").append(urlEncode(parameterValue));
280                                         }
281                                 }
282                                 originalUrl += "?" + requestParameters.toString();
283                         }
284                         return "login.html?target=" + urlEncode(originalUrl);
285                 }
286                 return null;
287         }
288
289         private static String urlEncode(String value) {
290                 try {
291                         return URLEncoder.encode(value, "UTF-8");
292                 } catch (UnsupportedEncodingException uee1) {
293                                                         /* A JVM without UTF-8? I don’t think so. */
294                         throw new RuntimeException(uee1);
295                 }
296         }
297
298         /**
299          * {@inheritDoc}
300          */
301         @Override
302         protected boolean isFullAccessOnly() {
303                 return webInterface.getCore().getPreferences().isRequireFullAccess();
304         }
305
306         /**
307          * {@inheritDoc}
308          */
309         @Override
310         public boolean isEnabled(ToadletContext toadletContext) {
311                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !toadletContext.isAllowedFullAccess()) {
312                         return false;
313                 }
314                 if (requiresLogin()) {
315                         return getCurrentSone(toadletContext, false) != null;
316                 }
317                 return true;
318         }
319
320 }