Return an optional Sone from the current session.
[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.template.Template;
35 import net.pterodactylus.util.template.TemplateContext;
36
37 import com.google.common.base.Optional;
38 import com.google.common.collect.ImmutableList;
39 import com.google.common.collect.ImmutableMap;
40
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 currently logged in Sone.
135          *
136          * @param toadletContext
137          *            The toadlet context
138          * @return The currently logged in Sone, or {@code null} if no Sone is
139          *         currently logged in
140          */
141         protected Optional<Sone> getCurrentSone(ToadletContext toadletContext) {
142                 return webInterface.getCurrentSone(toadletContext);
143         }
144
145         /**
146          * Returns the currently logged in Sone.
147          *
148          * @param toadletContext
149          *            The toadlet context
150          * @param create
151          *            {@code true} to create a new session if no session exists,
152          *            {@code false} to not create a new session
153          * @return The currently logged in Sone, or {@code null} if no Sone is
154          *         currently logged in
155          */
156         protected Optional<Sone> getCurrentSone(ToadletContext toadletContext, boolean create) {
157                 return webInterface.getCurrentSone(toadletContext, create);
158         }
159
160         /**
161          * Sets the currently logged in Sone.
162          *
163          * @param toadletContext
164          *            The toadlet context
165          * @param sone
166          *            The Sone to set as currently logged in
167          */
168         protected void setCurrentSone(ToadletContext toadletContext, Sone sone) {
169                 webInterface.setCurrentSone(toadletContext, sone);
170         }
171
172         //
173         // TEMPLATEPAGE METHODS
174         //
175
176         /**
177          * {@inheritDoc}
178          */
179         @Override
180         protected String getPageTitle(FreenetRequest request) {
181                 if (pageTitleKey != null) {
182                         return webInterface.getL10n().getString(pageTitleKey);
183                 }
184                 return "";
185         }
186
187         /**
188          * {@inheritDoc}
189          */
190         @Override
191         protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
192                 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();
193         }
194
195         /**
196          * {@inheritDoc}
197          */
198         @Override
199         protected Collection<String> getStyleSheets() {
200                 return Arrays.asList("css/sone.css");
201         }
202
203         /**
204          * {@inheritDoc}
205          */
206         @Override
207         protected String getShortcutIcon() {
208                 return "images/icon.png";
209         }
210
211         /**
212          * Returns whether this page requires the user to log in.
213          *
214          * @return {@code true} if the user is required to be logged in to use this
215          *         page, {@code false} otherwise
216          */
217         protected boolean requiresLogin() {
218                 return requireLogin;
219         }
220
221         /**
222          * {@inheritDoc}
223          */
224         @Override
225         protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
226                 super.processTemplate(request, templateContext);
227                 Optional<Sone> currentSone = getCurrentSone(request.getToadletContext(), false);
228                 templateContext.set("core", webInterface.getCore());
229                 templateContext.set("currentSone", currentSone.orNull());
230                 templateContext.set("localSones", webInterface.getCore().getLocalSones());
231                 templateContext.set("request", request);
232                 templateContext.set("currentVersion", SonePlugin.VERSION);
233                 templateContext.set("hasLatestVersion", webInterface.getCore().getUpdateChecker().hasLatestVersion());
234                 templateContext.set("latestEdition", webInterface.getCore().getUpdateChecker().getLatestEdition());
235                 templateContext.set("latestVersion", webInterface.getCore().getUpdateChecker().getLatestVersion());
236                 templateContext.set("latestVersionTime", webInterface.getCore().getUpdateChecker().getLatestVersionDate());
237                 List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone.orNull());
238                 Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
239                 templateContext.set("notifications", notifications);
240                 templateContext.set("notificationHash", notifications.hashCode());
241         }
242
243         /**
244          * {@inheritDoc}
245          */
246         @Override
247         protected String getRedirectTarget(FreenetRequest request) {
248                 if (requiresLogin() && !getCurrentSone(request.getToadletContext(), false).isPresent()) {
249                         HTTPRequest httpRequest = request.getHttpRequest();
250                         String originalUrl = httpRequest.getPath();
251                         if (httpRequest.hasParameters()) {
252                                 StringBuilder requestParameters = new StringBuilder();
253                                 for (String parameterName : httpRequest.getParameterNames()) {
254                                         if (requestParameters.length() > 0) {
255                                                 requestParameters.append("%26");
256                                         }
257                                         String[] parameterValues = httpRequest.getMultipleParam(parameterName);
258                                         for (String parameterValue : parameterValues) {
259                                                 try {
260                                                         requestParameters.append(URLEncoder.encode(parameterName, "UTF-8")).append("%3d").append(URLEncoder.encode(parameterValue, "UTF-8"));
261                                                 } catch (UnsupportedEncodingException uee1) {
262                                                         /* A JVM without UTF-8? I don’t think so. */
263                                                 }
264                                         }
265                                 }
266                                 originalUrl += "?" + requestParameters.toString();
267                         }
268                         return "login.html?target=" + originalUrl;
269                 }
270                 return null;
271         }
272
273         /**
274          * {@inheritDoc}
275          */
276         @Override
277         protected boolean isFullAccessOnly() {
278                 return webInterface.getCore().getPreferences().isRequireFullAccess();
279         }
280
281         /**
282          * {@inheritDoc}
283          */
284         @Override
285         public boolean isEnabled(ToadletContext toadletContext) {
286                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !toadletContext.isAllowedFullAccess()) {
287                         return false;
288                 }
289                 if (requiresLogin()) {
290                         return getCurrentSone(toadletContext, false).isPresent();
291                 }
292                 return true;
293         }
294
295 }