5b86db4bf52b70a434f18ed4e09947a46b6cb67c
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / IdentityManager.java
1 /*
2  * Sone - IdentityManager.java - Copyright © 2010–2012 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 java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Set;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.service.AbstractService;
32
33 import com.google.inject.Inject;
34 import com.google.inject.name.Named;
35
36 /**
37  * The identity manager takes care of loading and storing identities, their
38  * contexts, and properties. It does so in a way that does not expose errors via
39  * exceptions but it only logs them and tries to return sensible defaults.
40  * <p>
41  * It is also responsible for polling identities from the Web of Trust plugin
42  * and notifying registered {@link IdentityListener}s when {@link Identity}s and
43  * {@link OwnIdentity}s are discovered or disappearing.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class IdentityManager extends AbstractService {
48
49         /** Object used for synchronization. */
50         @SuppressWarnings("hiding")
51         private final Object syncObject = new Object() {
52                 /* inner class for better lock names. */
53         };
54
55         /** The logger. */
56         private static final Logger logger = Logging.getLogger(IdentityManager.class);
57
58         /** The event manager. */
59         private final IdentityListenerManager identityListenerManager = new IdentityListenerManager();
60
61         /** The Web of Trust connector. */
62         private final WebOfTrustConnector webOfTrustConnector;
63
64         /** The context to filter for. */
65         private final String context;
66
67         /** The currently known own identities. */
68         /* synchronize access on syncObject. */
69         private final Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
70
71         /** The last time all identities were loaded. */
72         private volatile long identitiesLastLoaded;
73
74         /**
75          * Creates a new identity manager.
76          *
77          * @param webOfTrustConnector
78          *            The Web of Trust connector
79          * @param context
80          *            The context to focus on (may be {@code null} to ignore
81          *            contexts)
82          */
83         @Inject
84         public IdentityManager(WebOfTrustConnector webOfTrustConnector, @Named("WebOfTrustContext") String context) {
85                 super("Sone Identity Manager", false);
86                 this.webOfTrustConnector = webOfTrustConnector;
87                 this.context = context;
88         }
89
90         //
91         // LISTENER MANAGEMENT
92         //
93
94         /**
95          * Adds a listener for identity events.
96          *
97          * @param identityListener
98          *            The listener to add
99          */
100         public void addIdentityListener(IdentityListener identityListener) {
101                 identityListenerManager.addListener(identityListener);
102         }
103
104         /**
105          * Removes a listener for identity events.
106          *
107          * @param identityListener
108          *            The listener to remove
109          */
110         public void removeIdentityListener(IdentityListener identityListener) {
111                 identityListenerManager.removeListener(identityListener);
112         }
113
114         //
115         // ACCESSORS
116         //
117
118         /**
119          * Returns the last time all identities were loaded.
120          *
121          * @return The last time all identities were loaded (in milliseconds since
122          *         Jan 1, 1970 UTC)
123          */
124         public long getIdentitiesLastLoaded() {
125                 return identitiesLastLoaded;
126         }
127
128         /**
129          * Returns whether the Web of Trust plugin could be reached during the last
130          * try.
131          *
132          * @return {@code true} if the Web of Trust plugin is connected,
133          *         {@code false} otherwise
134          */
135         public boolean isConnected() {
136                 try {
137                         webOfTrustConnector.ping();
138                         return true;
139                 } catch (PluginException pe1) {
140                         /* not connected, ignore. */
141                         return false;
142                 }
143         }
144
145         /**
146          * Returns the own identity with the given ID.
147          *
148          * @param id
149          *            The ID of the own identity
150          * @return The own identity, or {@code null} if there is no such identity
151          */
152         public OwnIdentity getOwnIdentity(String id) {
153                 Set<OwnIdentity> allOwnIdentities = getAllOwnIdentities();
154                 for (OwnIdentity ownIdentity : allOwnIdentities) {
155                         if (ownIdentity.getId().equals(id)) {
156                                 return new DefaultOwnIdentity(ownIdentity);
157                         }
158                 }
159                 return null;
160         }
161
162         /**
163          * Returns all own identities.
164          *
165          * @return All own identities
166          */
167         public Set<OwnIdentity> getAllOwnIdentities() {
168                 return new HashSet<OwnIdentity>(currentOwnIdentities.values());
169         }
170
171         //
172         // SERVICE METHODS
173         //
174
175         /**
176          * {@inheritDoc}
177          */
178         @Override
179         protected void serviceRun() {
180                 Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap();
181                 while (!shouldStop()) {
182                         Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
183                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
184
185                         Set<OwnIdentity> ownIdentities = null;
186                         boolean identitiesLoaded = false;
187                         try {
188                                 /* get all identities with the wanted context from WoT. */
189                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
190
191                                 /* load trusted identities. */
192                                 for (OwnIdentity ownIdentity : ownIdentities) {
193                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
194                                         Map<String, Identity> identities = new HashMap<String, Identity>();
195                                         currentIdentities.put(ownIdentity, identities);
196
197                                         /*
198                                          * if the context doesn’t match, skip getting trusted
199                                          * identities.
200                                          */
201                                         if ((context != null) && !ownIdentity.hasContext(context)) {
202                                                 continue;
203                                         }
204
205                                         /* load trusted identities. */
206                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
207                                         for (Identity identity : trustedIdentities) {
208                                                 identities.put(identity.getId(), identity);
209                                         }
210                                 }
211                                 identitiesLoaded = true;
212                                 identitiesLastLoaded = System.currentTimeMillis();
213                         } catch (WebOfTrustException wote1) {
214                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
215                         }
216
217                         if (identitiesLoaded) {
218
219                                 /* check for changes. */
220                                 checkOwnIdentities(currentOwnIdentities);
221
222                                 /* now check for changes in remote identities. */
223                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
224
225                                         /* find new identities. */
226                                         for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
227                                                 if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
228                                                         identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
229                                                 }
230                                         }
231
232                                         /* find removed identities. */
233                                         if (oldIdentities.containsKey(ownIdentity)) {
234                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
235                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
236                                                                 identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
237                                                         }
238                                                 }
239
240                                                 /* check for changes in the contexts. */
241                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
242                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
243                                                                 continue;
244                                                         }
245                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
246                                                         Set<String> oldContexts = oldIdentity.getContexts();
247                                                         Set<String> newContexts = newIdentity.getContexts();
248                                                         if (oldContexts.size() != newContexts.size()) {
249                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
250                                                                 continue;
251                                                         }
252                                                         for (String oldContext : oldContexts) {
253                                                                 if (!newContexts.contains(oldContext)) {
254                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
255                                                                         break;
256                                                                 }
257                                                         }
258                                                 }
259
260                                                 /* check for changes in the properties. */
261                                                 for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
262                                                         if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
263                                                                 continue;
264                                                         }
265                                                         Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
266                                                         Map<String, String> oldProperties = oldIdentity.getProperties();
267                                                         Map<String, String> newProperties = newIdentity.getProperties();
268                                                         if (oldProperties.size() != newProperties.size()) {
269                                                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
270                                                                 continue;
271                                                         }
272                                                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
273                                                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
274                                                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
275                                                                         break;
276                                                                 }
277                                                         }
278                                                 }
279                                         }
280                                 }
281
282                                 /* remember the current set of identities. */
283                                 oldIdentities = currentIdentities;
284                         }
285
286                         /* wait a minute before checking again. */
287                         sleep(60 * 1000);
288                 }
289         }
290
291         //
292         // PRIVATE METHODS
293         //
294
295         /**
296          * Checks the given new list of own identities for added or removed own
297          * identities, as compared to {@link #currentOwnIdentities}.
298          *
299          * @param newOwnIdentities
300          *            The new own identities
301          */
302         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
303                 synchronized (syncObject) {
304
305                         /* find removed own identities: */
306                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
307                                 OwnIdentity newOwnIdentity = newOwnIdentities.get(oldOwnIdentity.getId());
308                                 if ((newOwnIdentity == null) || ((context != null) && oldOwnIdentity.hasContext(context) && !newOwnIdentity.hasContext(context))) {
309                                         identityListenerManager.fireOwnIdentityRemoved(new DefaultOwnIdentity(oldOwnIdentity));
310                                 }
311                         }
312
313                         /* find added own identities. */
314                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
315                                 OwnIdentity oldOwnIdentity = currentOwnIdentities.get(currentOwnIdentity.getId());
316                                 if (((oldOwnIdentity == null) && ((context == null) || currentOwnIdentity.hasContext(context))) || ((oldOwnIdentity != null) && (context != null) && (!oldOwnIdentity.hasContext(context) && currentOwnIdentity.hasContext(context)))) {
317                                         identityListenerManager.fireOwnIdentityAdded(new DefaultOwnIdentity(currentOwnIdentity));
318                                 }
319                         }
320
321                         currentOwnIdentities.clear();
322                         currentOwnIdentities.putAll(newOwnIdentities);
323                 }
324         }
325
326 }