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