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