2 * Sone - IdentityLoader.kt - Copyright © 2013–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.freenet.wot
20 import com.google.common.base.*
21 import com.google.inject.*
22 import net.pterodactylus.sone.freenet.plugin.*
23 import java.util.concurrent.TimeUnit.*
24 import java.util.logging.*
27 * Loads [OwnIdentity]s and the [Identity]s they trust.
29 class IdentityLoader @Inject constructor(private val webOfTrustConnector: WebOfTrustConnector, private val context: Context? = null) {
31 private val logger: Logger = Logger.getLogger(IdentityLoader::class.java.name)
33 fun loadAllIdentities() =
34 time({ stopwatch, identities -> "Loaded ${identities.size} own identities in ${stopwatch.elapsed(MILLISECONDS) / 1000.0}s." }) {
35 webOfTrustConnector.loadAllOwnIdentities()
36 }.let(this::loadAllIdentitiesForOwnIdentities)
37 .mergeRemoteIdentities()
39 private fun loadAllIdentitiesForOwnIdentities(ownIdentities: Collection<OwnIdentity>) =
41 .also { logger.fine { "Getting trusted identities for ${it.size} own identities..." } }
42 .associateWith { ownIdentity ->
43 logger.fine { "Getting trusted identities for $ownIdentity..." }
44 if (ownIdentity.doesNotHaveCorrectContext()) {
45 logger.fine { "Skipping $ownIdentity because of incorrect context." }
48 logger.fine { "Loading trusted identities for $ownIdentity from WoT..." }
49 time({ stopwatch, identities -> "Loaded ${identities.size} identities for ${ownIdentity.nickname} in ${stopwatch.elapsed(MILLISECONDS) / 1000.0}s." }) {
50 webOfTrustConnector.loadAllIdentities(ownIdentity, context?.context)
55 private fun OwnIdentity.doesNotHaveCorrectContext() =
56 context?.let { it.context !in contexts } ?: false
58 private fun <R> time(logMessage: (Stopwatch, R) -> String, loader: () -> R) =
59 Stopwatch.createStarted().let { stopwatch ->
60 loader().also { logger.fine(logMessage(stopwatch, it)) }
63 private fun Map<OwnIdentity, Set<Identity>>.mergeRemoteIdentities() =
67 it.value.reduce { accIdentity, identity ->
68 identity.trust.forEach { (ownIdentity, trust) -> accIdentity.setTrust(ownIdentity, trust) }
72 .let { reducedIdentities ->
73 mapValues { it.value.map { identity -> reducedIdentities[identity.id]!! }.toSet() }