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