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