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