2 * Sone - FreenetTemplatePage.java - Copyright © 2010–2019 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.web.page;
20 import static java.lang.String.format;
21 import static java.util.logging.Logger.getLogger;
23 import java.io.IOException;
24 import java.io.StringWriter;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
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;
49 * Base class for all {@link Page}s that are rendered with {@link Template}s and
50 * fit into Freenet’s web interface.
52 public class FreenetTemplatePage implements FreenetPage, LinkEnabledCallback {
55 private static final Logger logger = getLogger(FreenetTemplatePage.class.getName());
57 /** The path of the page. */
58 private final String path;
60 /** The template context factory. */
61 private final TemplateContextFactory templateContextFactory;
63 /** The template to render. */
64 private final Template template;
65 private final Loaders loaders;
67 /** Where to redirect for invalid form passwords. */
68 private final String invalidFormPasswordRedirectTarget;
70 public FreenetTemplatePage(String path, TemplateContextFactory templateContextFactory, Loaders loaders, Template template, String invalidFormPasswordRedirectTarget) {
72 this.templateContextFactory = templateContextFactory;
73 this.loaders = loaders;
74 this.template = template;
75 this.invalidFormPasswordRedirectTarget = invalidFormPasswordRedirectTarget;
82 public String getPath() {
87 * Returns the title of the page.
90 * The request to serve
91 * @return The title of the page
93 @SuppressWarnings("static-method")
94 protected String getPageTitle(FreenetRequest request) {
102 public boolean isPrefixPage() {
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);
116 if (isFullAccessOnly() && !request.getToadletContext().isAllowedFullAccess()) {
117 return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html");
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);
127 PageMaker pageMaker = toadletContext.getPageMaker();
128 PageNode pageNode = pageMaker.getPageNode(getPageTitle(request), toadletContext);
129 for (String styleSheet : getStyleSheets()) {
130 pageNode.addCustomStyleSheet(styleSheet);
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());
138 String shortcutIcon = getShortcutIcon();
139 if (shortcutIcon != null) {
140 pageNode.addForwardLink("icon", shortcutIcon);
143 TemplateContext templateContext = templateContextFactory.createTemplateContext();
144 templateContext.mergeContext(template.getInitialContext());
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());
154 StringWriter stringWriter = new StringWriter();
155 template.render(templateContext, stringWriter);
156 pageNode.content.addChild("%", stringWriter.toString());
158 postProcess(request, templateContext);
160 return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageNode.outer.generate());
164 * Can be overridden to return a custom set of style sheets that are to be
165 * included in the page’s header.
167 * @return Additional style sheets to load
169 @SuppressWarnings("static-method")
170 protected Collection<String> getStyleSheets() {
171 return Collections.emptySet();
175 * Returns the name of the shortcut icon to include in the page’s header.
177 * @return The URL of the shortcut icon, or {@code null} for no icon
179 @SuppressWarnings("static-method")
180 protected String getShortcutIcon() {
185 * Can be overridden when extending classes need to set variables in the
186 * template before it is rendered.
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
195 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
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}!
207 * The request being processed
208 * @param templateContext
209 * The template context that supplied the rendered data
211 protected void postProcess(FreenetRequest request, TemplateContext templateContext) {
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.
220 * The request that is processed
221 * @return The URL to redirect to, or {@code null} to not redirect
223 @SuppressWarnings("static-method")
224 protected String getRedirectTarget(FreenetRequest request) {
229 * Returns additional <link> nodes for the HTML’s <head> node.
232 * The request for which to return the link nodes
233 * @return All link nodes that should be added to the HTML head
235 @SuppressWarnings("static-method")
236 protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
237 return Collections.emptyList();
241 * Returns whether this page should only be allowed for requests from hosts
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
247 @SuppressWarnings("static-method")
248 protected boolean isFullAccessOnly() {
256 public boolean isLinkExcepted(URI link) {
261 // INTERFACE LinkEnabledCallback
268 public boolean isEnabled(ToadletContext toadletContext) {
269 return !isFullAccessOnly();
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)}
278 public static class RedirectException extends Exception {
280 /** The target to redirect to. */
281 private final String target;
284 * Creates a new redirect exception.
287 * The target of the redirect
289 public RedirectException(String target) {
290 this.target = target;
294 * Returns the target to redirect to.
296 * @return The target to redirect to
298 public String getTarget() {
303 public String toString() {
304 return format("RedirectException{target='%s'}", target);