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