🚧 Add no-negative identity filter
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / freenet / wot / NoNegativeIdentityFilter.kt
1 package net.pterodactylus.sone.freenet.wot
2
3 /**
4  * Filter for identities that retains only those remote identities that do
5  * not have a single negative trust value (explicit or implicit) from any own
6  * identity.
7  */
8 class NoNegativeIdentityFilter {
9
10         fun filter(identities: Map<OwnIdentity, Set<Identity>>) =
11                 identities.run {
12                         val identitiesWithTrust = values.flatten()
13                                 .groupBy { it.id }
14                                 .mapValues { (_, identities) ->
15                                         identities.reduce { accIdentity, identity ->
16                                                 identity.trust.forEach { (ownIdentity: OwnIdentity?, trust: Trust?) ->
17                                                         accIdentity.setTrust(ownIdentity, trust)
18                                                 }
19                                                 accIdentity
20                                         }
21                                 }
22
23                         mapValues { (_, trustedIdentities) ->
24                                 trustedIdentities.filter { trustedIdentity ->
25                                         identitiesWithTrust[trustedIdentity.id]!!.trust.all { it.value.hasZeroOrPositiveTrust() }
26                                 }
27                         }
28                 }
29
30 }
31
32 private fun Trust.hasZeroOrPositiveTrust() =
33                 if (explicit == null) {
34                         implicit == null || implicit >= 0
35                 } else {
36                         explicit >= 0
37                 }