Update year in copyright lines
[Sone.git] / src / main / java / net / pterodactylus / sone / web / page / FreenetTemplatePage.java
1 /*
2  * Sone - FreenetTemplatePage.java - Copyright © 2010–2019 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.page;
19
20 import static java.lang.String.format;
21 import static java.util.logging.Logger.getLogger;
22
23 import java.io.IOException;
24 import java.io.StringWriter;
25 import java.net.URI;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import net.pterodactylus.util.template.Template;
35 import net.pterodactylus.util.template.TemplateContext;
36 import net.pterodactylus.util.template.TemplateContextFactory;
37 import net.pterodactylus.util.web.Method;
38 import net.pterodactylus.util.web.Page;
39 import net.pterodactylus.util.web.RedirectResponse;
40 import net.pterodactylus.util.web.Response;
41 import freenet.clients.http.LinkEnabledCallback;
42 import freenet.clients.http.PageMaker;
43 import freenet.clients.http.PageNode;
44 import freenet.clients.http.ToadletContext;
45 import freenet.support.HTMLNode;
46
47 /**
48  * Base class for all {@link Page}s that are rendered with {@link Template}s and
49  * fit into Freenet’s web interface.
50  */
51 public class FreenetTemplatePage implements FreenetPage, LinkEnabledCallback {
52
53         /** The logger. */
54         private static final Logger logger = getLogger(FreenetTemplatePage.class.getName());
55
56         /** The path of the page. */
57         private final String path;
58
59         /** The template context factory. */
60         private final TemplateContextFactory templateContextFactory;
61
62         /** The template to render. */
63         private final Template template;
64
65         /** Where to redirect for invalid form passwords. */
66         private final String invalidFormPasswordRedirectTarget;
67
68         /**
69          * Creates a new template page.
70          *
71          * @param path
72          *            The path of the page
73          * @param templateContextFactory
74          *            The template context factory
75          * @param template
76          *            The template to render
77          * @param invalidFormPasswordRedirectTarget
78          *            The target to redirect to if a POST request does not contain
79          *            the correct form password
80          */
81         public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Template template, String invalidFormPasswordRedirectTarget) {
82                 this.path = path;
83                 this.templateContextFactory = templateContextFactory;
84                 this.template = template;
85                 this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget;
86         }
87
88         /**
89          * {@inheritDoc}
90          */
91         @Override
92         public String getPath() {
93                 return path;
94         }
95
96         /**
97          * Returns the title of the page.
98          *
99          * @param request
100          *            The request to serve
101          * @return The title of the page
102          */
103         @SuppressWarnings("static-method")
104         protected String getPageTitle(FreenetRequest request) {
105                 return null;
106         }
107
108         /**
109          * {@inheritDoc}
110          */
111         @Override
112         public boolean isPrefixPage() {
113                 return false;
114         }
115
116         /**
117          * {@inheritDoc}
118          */
119         @Override
120         public final Response handleRequest(FreenetRequest request, Response response) throws IOException {
121                 String redirectTarget = getRedirectTarget(request);
122                 if (redirectTarget != null) {
123                         return new RedirectResponse(redirectTarget);
124                 }
125
126                 if (isFullAccessOnly() && !request.getToadletContext().isAllowedFullAccess()) {
127                         return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html");
128                 }
129                 ToadletContext toadletContext = request.getToadletContext();
130                 if (request.getMethod() == Method.POST) {
131                         /* require form password. */
132                         String formPassword = request.getHttpRequest().getPartAsStringFailsafe("formPassword", 32);
133                         if (!formPassword.equals(toadletContext.getContainer().getFormPassword())) {
134                                 return new RedirectResponse(invalidFormPasswordRedirectTarget);
135                         }
136                 }
137                 PageMaker pageMaker = toadletContext.getPageMaker();
138                 PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext);
139                 for (String styleSheet : getStyleSheets()) {
140                         pageNode.addCustomStyleSheet(styleSheet);
141                 }
142                 for (Map<String, String> linkNodeParameters : getAdditionalLinkNodes(request)) {
143                         HTMLNode linkNode = pageNode.headNode.addChild("link");
144                         for (Entry<String, String> parameter : linkNodeParameters.entrySet()) {
145                                 linkNode.addAttribute(parameter.getKey(), parameter.getValue());
146                         }
147                 }
148                 String shortcutIcon = getShortcutIcon();
149                 if (shortcutIcon != null) {
150                         pageNode.addForwardLink("icon", shortcutIcon);
151                 }
152
153                 TemplateContext templateContext = templateContextFactory.createTemplateContext();
154                 templateContext.mergeContext(template.getInitialContext());
155                 try {
156                         long start = System.nanoTime();
157                         processTemplate(request, templateContext);
158                         long finish = System.nanoTime();
159                         logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0));
160                 } catch (RedirectException re1) {
161                         return new RedirectResponse(re1.getTarget());
162                 }
163
164                 StringWriter stringWriter = new StringWriter();
165                 template.render(templateContext, stringWriter);
166                 pageNode.content.addChild("%", stringWriter.toString());
167
168                 postProcess(request, templateContext);
169
170                 return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageNode.outer.generate());
171         }
172
173         /**
174          * Can be overridden to return a custom set of style sheets that are to be
175          * included in the page’s header.
176          *
177          * @return Additional style sheets to load
178          */
179         @SuppressWarnings("static-method")
180         protected Collection<String> getStyleSheets() {
181                 return Collections.emptySet();
182         }
183
184         /**
185          * Returns the name of the shortcut icon to include in the page’s header.
186          *
187          * @return The URL of the shortcut icon, or {@code null} for no icon
188          */
189         @SuppressWarnings("static-method")
190         protected String getShortcutIcon() {
191                 return null;
192         }
193
194         /**
195          * Can be overridden when extending classes need to set variables in the
196          * template before it is rendered.
197          *
198          * @param request
199          *            The request that is rendered
200          * @param templateContext
201          *            The template context to set variables in
202          * @throws RedirectException
203          *             if the processing page wants to redirect after processing
204          */
205         protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
206                 /* do nothing. */
207         }
208
209         /**
210          * This method will be called after
211          * {@link #processTemplate(FreenetRequest, TemplateContext)} has processed
212          * the template and the template was rendered. This method will not be
213          * called if {@link #processTemplate(FreenetRequest, TemplateContext)}
214          * throws a {@link RedirectException}!
215          *
216          * @param request
217          *            The request being processed
218          * @param templateContext
219          *            The template context that supplied the rendered data
220          */
221         protected void postProcess(FreenetRequest request, TemplateContext templateContext) {
222                 /* do nothing. */
223         }
224
225         /**
226          * Can be overridden to redirect the user to a different page, in case a log
227          * in is required, or something else is wrong.
228          *
229          * @param request
230          *            The request that is processed
231          * @return The URL to redirect to, or {@code null} to not redirect
232          */
233         @SuppressWarnings("static-method")
234         protected String getRedirectTarget(FreenetRequest request) {
235                 return null;
236         }
237
238         /**
239          * Returns additional &lt;link&gt; nodes for the HTML’s &lt;head&gt; node.
240          *
241          * @param request
242          *            The request for which to return the link nodes
243          * @return All link nodes that should be added to the HTML head
244          */
245         @SuppressWarnings("static-method")
246         protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
247                 return Collections.emptyList();
248         }
249
250         /**
251          * Returns whether this page should only be allowed for requests from hosts
252          * with full access.
253          *
254          * @return {@code true} if this page should only be allowed for hosts with
255          *         full access, {@code false} to allow this page for any host
256          */
257         @SuppressWarnings("static-method")
258         protected boolean isFullAccessOnly() {
259                 return false;
260         }
261
262         /**
263          * {@inheritDoc}
264          */
265         @Override
266         public boolean isLinkExcepted(URI link) {
267                 return false;
268         }
269
270         //
271         // INTERFACE LinkEnabledCallback
272         //
273
274         /**
275          * {@inheritDoc}
276          */
277         @Override
278         public boolean isEnabled(ToadletContext toadletContext) {
279                 return !isFullAccessOnly();
280         }
281
282         /**
283          * Exception that can be thrown to signal that a subclassed {@link Page}
284          * wants to redirect the user during the
285          * {@link FreenetTemplatePage#processTemplate(FreenetRequest, TemplateContext)}
286          * method call.
287          */
288         public static class RedirectException extends Exception {
289
290                 /** The target to redirect to. */
291                 private final String target;
292
293                 /**
294                  * Creates a new redirect exception.
295                  *
296                  * @param target
297                  *            The target of the redirect
298                  */
299                 public RedirectException(String target) {
300                         this.target = target;
301                 }
302
303                 /**
304                  * Returns the target to redirect to.
305                  *
306                  * @return The target to redirect to
307                  */
308                 public String getTarget() {
309                         return target;
310                 }
311
312                 @Override
313                 public String toString() {
314                         return format("RedirectException{target='%s'}", target);
315                 }
316
317         }
318
319 }