🔀 Merge branch 'release/v82'
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / FreenetSessionProvider.kt
1 /**
2  * Sone - FreenetSessionProvider.kt - Copyright Â© 2020 David â€˜Bombe’ 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
19
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
24 import java.util.UUID
25 import javax.inject.Inject
26
27 /**
28  * [SoneProvider] implementation based on Freenet’s [SessionManager].
29  */
30 class FreenetSessionProvider @Inject constructor(private val soneProvider: SoneProvider, private val sessionManager: SessionManager) : SessionProvider {
31
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 }
38
39         override fun setCurrentSone(toadletContext: ToadletContext, sone: Sone?) {
40                 if (sone == null) {
41                         sessionManager.useSession(toadletContext)
42                                         ?.removeAttribute("Sone.CurrentSone")
43                 } else {
44                         sessionManager.getOrCreateSession(toadletContext)
45                                         ?.setAttribute("Sone.CurrentSone", sone.id)
46                 }
47         }
48
49         private fun SessionManager.getOrCreateSession(toadletContext: ToadletContext) =
50                         useSession(toadletContext)
51                                         ?: createSession(UUID.randomUUID().toString(), toadletContext)
52
53 }