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