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