36d31fbff516a4a9e3fbec76c5b053c4f0e5bbba
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / freenet / wot / IdentityManagerImpl.kt
1 /*
2  * Sone - IdentityManagerImpl.kt - Copyright © 2010–2020 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.freenet.wot
19
20 import com.google.common.eventbus.*
21 import com.google.inject.*
22 import net.pterodactylus.util.service.*
23 import java.util.concurrent.TimeUnit.*
24 import java.util.logging.*
25 import java.util.logging.Logger.*
26
27 /**
28  * The identity manager takes care of loading and storing identities, their
29  * contexts, and properties. It does so in a way that does not expose errors via
30  * exceptions but it only logs them and tries to return sensible defaults.
31  *
32  *
33  * It is also responsible for polling identities from the Web of Trust plugin
34  * and sending events to the [EventBus] when [Identity]s and
35  * [OwnIdentity]s are discovered or disappearing.
36  */
37 @Singleton
38 class IdentityManagerImpl @Inject constructor(
39                 private val eventBus: EventBus,
40                 private val webOfTrustConnector: WebOfTrustConnector,
41                 private val identityLoader: IdentityLoader
42 ) : AbstractService("Sone Identity Manager", false), IdentityManager {
43
44         private val currentOwnIdentities = mutableSetOf<OwnIdentity>()
45
46         override val isConnected: Boolean
47                 get() = notThrowing { webOfTrustConnector.ping() }
48
49         override val allOwnIdentities: Set<OwnIdentity>
50                 get() = synchronized(currentOwnIdentities) {
51                         currentOwnIdentities.toSet()
52                 }
53
54         override fun serviceRun() {
55                 var oldIdentities = mapOf<OwnIdentity, Collection<Identity>>()
56
57                 while (!shouldStop()) {
58                         try {
59                                 val currentIdentities = identityLoader.loadTrustedIdentities()
60
61                                 val identitiesWithTrust = currentIdentities.values.flatten()
62                                                 .groupBy { it.id }
63                                                 .mapValues { (_, identities) ->
64                                                         identities.reduce { accIdentity, identity ->
65                                                                 identity.trust.forEach { (ownIdentity: OwnIdentity?, trust: Trust?) ->
66                                                                         accIdentity.setTrust(ownIdentity, trust)
67                                                                 }
68                                                                 accIdentity
69                                                         }
70                                                 }
71
72                                 val onlyTrustedByAll = currentIdentities.mapValues { (_, trustedIdentities) ->
73                                         trustedIdentities.filter { trustedIdentity ->
74                                                 identitiesWithTrust[trustedIdentity.id]!!.trust.all { it.value.hasZeroOrPositiveTrust() }
75                                         }
76                                 }
77                                 logger.log(Level.FINE, "Reduced (${currentIdentities.size},(${currentIdentities.values.joinToString { it.size.toString() }})) identities to (${onlyTrustedByAll.size},(${onlyTrustedByAll.values.joinToString { it.size.toString() }})).")
78
79                                 val identityChangeEventSender = IdentityChangeEventSender(eventBus, oldIdentities)
80                                 identityChangeEventSender.detectChanges(currentIdentities)
81
82                                 oldIdentities = currentIdentities
83
84                                 synchronized(currentOwnIdentities) {
85                                         currentOwnIdentities.clear()
86                                         currentOwnIdentities.addAll(currentIdentities.keys)
87                                 }
88                         } catch (wote1: WebOfTrustException) {
89                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1)
90                         } catch (e: Exception) {
91                                 logger.log(Level.SEVERE, "Uncaught exception in IdentityManager thread!", e)
92                         }
93
94                         /* wait a minute before checking again. */
95                         sleep(SECONDS.toMillis(60))
96                 }
97         }
98
99 }
100
101 private val logger: Logger = getLogger(IdentityManagerImpl::class.java.name)
102
103 private fun notThrowing(action: () -> Unit): Boolean =
104                 try {
105                         action()
106                         true
107                 } catch (e: Exception) {
108                         false
109                 }
110
111 private fun Trust.hasZeroOrPositiveTrust() =
112                 if (explicit == null) {
113                         implicit == null || implicit >= 0
114                 } else {
115                         explicit >= 0
116                 }