🚧 Add handler for image-insert notifications
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / page / FreenetTemplatePage.kt
1 /*
2  * Sone - FreenetTemplatePage.kt - 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 freenet.clients.http.*
21 import net.pterodactylus.sone.main.*
22 import net.pterodactylus.util.template.*
23 import net.pterodactylus.util.web.*
24 import java.lang.String.*
25 import java.net.*
26 import java.util.logging.*
27 import java.util.logging.Logger.*
28
29 /**
30  * Base class for all [Page]s that are rendered with [Template]s and
31  * fit into Freenet’s web interface.
32  */
33 open class FreenetTemplatePage(
34                 private val templateRenderer: TemplateRenderer,
35                 loaders: Loaders,
36                 private val invalidFormPasswordRedirectTarget: String
37 ) : FreenetPage, LinkEnabledCallback {
38
39         private val pageMakerInteractionFactory: PageMakerInteractionFactory = DefaultPageMakerInteractionFactory()
40         open val styleSheets: Collection<String> = emptySet()
41         open val shortcutIcon: String? get() = null
42         open val isFullAccessOnly get() = false
43
44         override fun getPath() = toadletPath
45
46         open fun getPageTitle(request: FreenetRequest) = ""
47
48         override fun isPrefixPage() = false
49
50         open fun getRedirectTarget(request: FreenetRequest): String? = null
51
52         open fun getAdditionalLinkNodes(request: FreenetRequest): List<Map<String, String>> = emptyList()
53
54         override fun isLinkExcepted(link: URI) = false
55
56         override fun isEnabled(toadletContext: ToadletContext) = !isFullAccessOnly
57
58         private val template = templatePath?.let(loaders::loadTemplate) ?: Template()
59
60         override fun handleRequest(request: FreenetRequest, response: Response): Response {
61                 getRedirectTarget(request)?.let { redirectTarget -> return RedirectResponse(redirectTarget) }
62
63                 if (isFullAccessOnly && !request.toadletContext.isAllowedFullAccess) {
64                         return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html")
65                 }
66                 val toadletContext = request.toadletContext
67                 if (request.method == Method.POST) {
68                         /* require form password. */
69                         val formPassword = request.httpRequest.getPartAsStringFailsafe("formPassword", 32)
70                         if (formPassword != toadletContext.container.formPassword) {
71                                 return RedirectResponse(invalidFormPasswordRedirectTarget)
72                         }
73                 }
74
75                 val pageMakerInteraction = pageMakerInteractionFactory.createPageMaker(toadletContext, getPageTitle(request))
76                 styleSheets.forEach(pageMakerInteraction::addStyleSheet)
77                 getAdditionalLinkNodes(request).forEach(pageMakerInteraction::addLinkNode)
78                 shortcutIcon?.let(pageMakerInteraction::addShortcutIcon)
79
80                 val output = try {
81                         val start = System.nanoTime()
82                         templateRenderer.render(template) { templateContext ->
83                                 processTemplate(request, templateContext)
84                         }.also {
85                                 val finish = System.nanoTime()
86                                 logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0))
87                         }
88                 } catch (re1: RedirectException) {
89                         return RedirectResponse(re1.target ?: "")
90                 }
91
92                 pageMakerInteraction.setContent(output)
93
94                 return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageMakerInteraction.renderPage())
95         }
96
97         open fun processTemplate(request: FreenetRequest, templateContext: TemplateContext) {
98                 /* do nothing. */
99         }
100
101         fun redirectTo(target: String?): Nothing =
102                         throw RedirectException(target)
103
104         class RedirectException(val target: String?) : Exception() {
105                 override fun toString(): String = format("RedirectException{target='%s'}", target)
106         }
107
108 }
109
110 private val logger: Logger = getLogger(FreenetTemplatePage::class.java.name)