2 * Sone - PageToadlet.kt - Copyright © 2010–2020 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 freenet.client.HighLevelSimpleClient
21 import freenet.clients.http.LinkEnabledCallback
22 import freenet.clients.http.LinkFilterExceptedToadlet
23 import freenet.clients.http.Toadlet
24 import freenet.clients.http.ToadletContext
25 import freenet.support.MultiValueTable
26 import freenet.support.api.HTTPRequest
27 import net.pterodactylus.sone.utils.use
28 import net.pterodactylus.util.web.Method
29 import net.pterodactylus.util.web.Page
30 import net.pterodactylus.util.web.Response
34 * [Toadlet] implementation that is wrapped around a [Page].
37 highLevelSimpleClient: HighLevelSimpleClient,
38 val menuName: String?,
39 private val page: Page<FreenetRequest>,
40 private val pathPrefix: String
41 ) : Toadlet(highLevelSimpleClient), LinkEnabledCallback, LinkFilterExceptedToadlet {
43 override fun path() = pathPrefix + page.path
45 override fun handleMethodGET(uri: URI, httpRequest: HTTPRequest, toadletContext: ToadletContext) =
46 handleRequest(FreenetRequest(uri, Method.GET, httpRequest, toadletContext))
48 fun handleMethodPOST(uri: URI?, httpRequest: HTTPRequest?, toadletContext: ToadletContext?) =
49 handleRequest(FreenetRequest(uri!!, Method.POST, httpRequest!!, toadletContext!!))
51 private fun handleRequest(pageRequest: FreenetRequest) {
52 pageRequest.toadletContext.bucketFactory.makeBucket(-1).use { pageBucket ->
53 pageBucket.outputStream.use { pageBucketOutputStream ->
54 val pageResponse = page.handleRequest(pageRequest, Response(pageBucketOutputStream))
55 // according to the javadoc, headers is allowed to return null but that’s stupid and it doesn’t do that.
56 val headers = pageResponse.headers.fold(MultiValueTable<String, String>()) { headers, header ->
58 header.forEach { put(header.name, it) }
62 writeReply(pageRequest.toadletContext, statusCode, contentType, statusText, headers, pageBucket)
68 override fun isEnabled(toadletContext: ToadletContext) =
69 if (page is LinkEnabledCallback) {
70 page.isEnabled(toadletContext)
74 override fun isLinkExcepted(link: URI) =
75 page is FreenetPage && page.isLinkExcepted(link)
77 override fun toString() = "${javaClass.name}[path=${path()},page=$page]"