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