2 * Sone - FreenetSessionProvider.kt - Copyright © 2020 David ‘Bombe’ 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
20 import freenet.clients.http.SessionManager
21 import freenet.clients.http.ToadletContext
22 import net.pterodactylus.sone.data.Sone
23 import net.pterodactylus.sone.database.SoneProvider
25 import javax.inject.Inject
28 * [SoneProvider] implementation based on Freenet’s [SessionManager].
30 class FreenetSessionProvider @Inject constructor(private val soneProvider: SoneProvider, private val sessionManager: SessionManager) : SessionProvider {
32 override fun getCurrentSone(toadletContext: ToadletContext): Sone? =
33 soneProvider.localSones.singleOrNull()
34 ?: sessionManager.useSession(toadletContext)
35 ?.let { it.getAttribute("Sone.CurrentSone") as? String }
36 ?.let(soneProvider.soneLoader)
37 ?.takeIf { it.isLocal }
39 override fun setCurrentSone(toadletContext: ToadletContext, sone: Sone?) {
41 sessionManager.useSession(toadletContext)
42 ?.removeAttribute("Sone.CurrentSone")
44 sessionManager.getOrCreateSession(toadletContext)
45 ?.setAttribute("Sone.CurrentSone", sone.id)
49 private fun SessionManager.getOrCreateSession(toadletContext: ToadletContext) =
50 useSession(toadletContext)
51 ?: createSession(UUID.randomUUID().toString(), toadletContext)