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