Add method to remove trust assignments. (Not implemented in WoT yet!)
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / WebOfTrustConnector.java
1 /*
2  * Sone - WebOfTrustConnector.java - Copyright © 2010 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.Set;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.freenet.plugin.ConnectorListener;
29 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
30 import net.pterodactylus.sone.freenet.plugin.PluginException;
31 import net.pterodactylus.util.logging.Logging;
32 import freenet.support.SimpleFieldSet;
33 import freenet.support.api.Bucket;
34
35 /**
36  * Connector for the Web of Trust plugin.
37  *
38  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39  */
40 public class WebOfTrustConnector implements ConnectorListener {
41
42         /** The logger. */
43         private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
44
45         /** The name of the WoT plugin. */
46         private static final String WOT_PLUGIN_NAME = "plugins.WoT.WoT";
47
48         /** A random connection identifier. */
49         private static final String PLUGIN_CONNECTION_IDENTIFIER = "Sone-WoT-Connector-" + Math.abs(Math.random());
50
51         /** The current replies that we wait for. */
52         private final Map<String, Reply> replies = Collections.synchronizedMap(new HashMap<String, Reply>());
53
54         /** The plugin connector. */
55         private final PluginConnector pluginConnector;
56
57         /**
58          * Creates a new Web of Trust connector that uses the given plugin
59          * connector.
60          *
61          * @param pluginConnector
62          *            The plugin connector
63          */
64         public WebOfTrustConnector(PluginConnector pluginConnector) {
65                 this.pluginConnector = pluginConnector;
66                 pluginConnector.addConnectorListener(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, this);
67         }
68
69         //
70         // ACTIONS
71         //
72
73         /**
74          * Loads all own identities from the Web of Trust plugin.
75          *
76          * @return All own identity
77          * @throws WebOfTrustException
78          *             if the own identities can not be loaded
79          */
80         public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
81                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get(), "OwnIdentities");
82                 SimpleFieldSet fields = reply.getFields();
83                 int ownIdentityCounter = -1;
84                 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
85                 while (true) {
86                         String id = fields.get("Identity" + ++ownIdentityCounter);
87                         if (id == null) {
88                                 break;
89                         }
90                         String requestUri = fields.get("RequestURI" + ownIdentityCounter);
91                         String insertUri = fields.get("InsertURI" + ownIdentityCounter);
92                         String nickname = fields.get("Nickname" + ownIdentityCounter);
93                         DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(this, id, nickname, requestUri, insertUri);
94                         ownIdentity.setContextsPrivate(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
95                         ownIdentity.setPropertiesPrivate(parseProperties("Properties" + ownIdentityCounter + ".", fields));
96                         ownIdentities.add(ownIdentity);
97                 }
98                 return ownIdentities;
99         }
100
101         /**
102          * Loads all identities that the given identities trusts with a score of
103          * more than 0.
104          *
105          * @param ownIdentity
106          *            The own identity
107          * @return All trusted identities
108          * @throws PluginException
109          *             if an error occured talking to the Web of Trust plugin
110          */
111         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
112                 return loadTrustedIdentities(ownIdentity, null);
113         }
114
115         /**
116          * Loads all identities that the given identities trusts with a score of
117          * more than 0 and the (optional) given context.
118          *
119          * @param ownIdentity
120          *            The own identity
121          * @param context
122          *            The context to filter, or {@code null}
123          * @return All trusted identities
124          * @throws PluginException
125          *             if an error occured talking to the Web of Trust plugin
126          */
127         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
128                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("TreeOwner", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).get(), "Identities");
129                 SimpleFieldSet fields = reply.getFields();
130                 Set<Identity> identities = new HashSet<Identity>();
131                 int identityCounter = -1;
132                 while (true) {
133                         String id = fields.get("Identity" + ++identityCounter);
134                         if (id == null) {
135                                 break;
136                         }
137                         String nickname = fields.get("Nickname" + identityCounter);
138                         String requestUri = fields.get("RequestURI" + identityCounter);
139                         DefaultIdentity identity = new DefaultIdentity(this, id, nickname, requestUri);
140                         identity.setContextsPrivate(parseContexts("Contexts" + identityCounter + ".", fields));
141                         identity.setPropertiesPrivate(parseProperties("Properties" + identityCounter + ".", fields));
142                         identities.add(identity);
143                 }
144                 return identities;
145         }
146
147         /**
148          * Adds the given context to the given identity.
149          *
150          * @param ownIdentity
151          *            The identity to add the context to
152          * @param context
153          *            The context to add
154          * @throws PluginException
155          *             if an error occured talking to the Web of Trust plugin
156          */
157         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
158                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextAdded");
159         }
160
161         /**
162          * Removes the given context from the given identity.
163          *
164          * @param ownIdentity
165          *            The identity to remove the context from
166          * @param context
167          *            The context to remove
168          * @throws PluginException
169          *             if an error occured talking to the Web of Trust plugin
170          */
171         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
172                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get(), "ContextRemoved");
173         }
174
175         /**
176          * Returns the value of the property with the given name.
177          *
178          * @param identity
179          *            The identity whose properties to check
180          * @param name
181          *            The name of the property to return
182          * @return The value of the property, or {@code null} if there is no value
183          * @throws PluginException
184          *             if an error occured talking to the Web of Trust plugin
185          */
186         public String getProperty(Identity identity, String name) throws PluginException {
187                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get(), "PropertyValue");
188                 return reply.getFields().get("Property");
189         }
190
191         /**
192          * Sets the property with the given name to the given value.
193          *
194          * @param ownIdentity
195          *            The identity to set the property on
196          * @param name
197          *            The name of the property to set
198          * @param value
199          *            The value to set
200          * @throws PluginException
201          *             if an error occured talking to the Web of Trust plugin
202          */
203         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
204                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get(), "PropertyAdded");
205         }
206
207         /**
208          * Removes the property with the given name.
209          *
210          * @param ownIdentity
211          *            The identity to remove the property from
212          * @param name
213          *            The name of the property to remove
214          * @throws PluginException
215          *             if an error occured talking to the Web of Trust plugin
216          */
217         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
218                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get(), "PropertyRemoved");
219         }
220
221         /**
222          * Returns the trust for the given identity assigned to it by the given own
223          * identity.
224          *
225          * @param ownIdentity
226          *            The own identity
227          * @param identity
228          *            The identity to get the trust for
229          * @return The trust for the given identity
230          * @throws PluginException
231          *             if an error occured talking to the Web of Trust plugin
232          */
233         public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
234                 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("TreeOwner", ownIdentity.getId()).put("Identity", identity.getId()).get(), "Identity");
235                 String trust = getTrustReply.getFields().get("Trust");
236                 String score = getTrustReply.getFields().get("Score");
237                 String rank = getTrustReply.getFields().get("Rank");
238                 Integer explicit = null;
239                 Integer implicit = null;
240                 Integer distance = null;
241                 try {
242                         explicit = Integer.valueOf(trust);
243                 } catch (NumberFormatException nfe1) {
244                         /* ignore. */
245                 }
246                 try {
247                         implicit = Integer.valueOf(score);
248                         distance = Integer.valueOf(rank);
249                 } catch (NumberFormatException nfe1) {
250                         /* ignore. */
251                 }
252                 return new Trust(explicit, implicit, distance);
253         }
254
255         /**
256          * Sets the trust for the given identity.
257          *
258          * @param ownIdentity
259          *            The trusting identity
260          * @param identity
261          *            The trusted identity
262          * @param trust
263          *            The amount of trust (-100 thru 100)
264          * @param comment
265          *            The comment or explanation of the trust value
266          * @throws PluginException
267          *             if an error occured talking to the Web of Trust plugin
268          */
269         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
270                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get(), "TrustSet");
271         }
272
273         /**
274          * Removes any trust assignment of the given own identity for the given
275          * identity.
276          *
277          * @param ownIdentity
278          *            The own identity
279          * @param identity
280          *            The identity to remove all trust for
281          * @throws WebOfTrustException
282          *             if an error occurs
283          */
284         public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
285                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get(), "TrustRemoved");
286         }
287
288         /**
289          * Pings the Web of Trust plugin. If the plugin can not be reached, a
290          * {@link PluginException} is thrown.
291          *
292          * @throws PluginException
293          *             if the plugin is not loaded
294          */
295         public void ping() throws PluginException {
296                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get(), "Pong");
297         }
298
299         //
300         // PRIVATE ACTIONS
301         //
302
303         /**
304          * Parses the contexts from the given fields.
305          *
306          * @param prefix
307          *            The prefix to use to access the contexts
308          * @param fields
309          *            The fields to parse the contexts from
310          * @return The parsed contexts
311          */
312         private Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
313                 Set<String> contexts = new HashSet<String>();
314                 int contextCounter = -1;
315                 while (true) {
316                         String context = fields.get(prefix + "Context" + ++contextCounter);
317                         if (context == null) {
318                                 break;
319                         }
320                         contexts.add(context);
321                 }
322                 return contexts;
323         }
324
325         /**
326          * Parses the properties from the given fields.
327          *
328          * @param prefix
329          *            The prefix to use to access the properties
330          * @param fields
331          *            The fields to parse the properties from
332          * @return The parsed properties
333          */
334         private Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
335                 Map<String, String> properties = new HashMap<String, String>();
336                 int propertiesCounter = -1;
337                 while (true) {
338                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
339                         if (propertyName == null) {
340                                 break;
341                         }
342                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
343                         properties.put(propertyName, propertyValue);
344                 }
345                 return properties;
346         }
347
348         /**
349          * Sends a request containing the given fields and waits for the target
350          * message.
351          *
352          * @param fields
353          *            The fields of the message
354          * @param targetMessages
355          *            The messages of the reply to wait for
356          * @return The reply message
357          * @throws PluginException
358          *             if the request could not be sent
359          */
360         private Reply performRequest(SimpleFieldSet fields, String... targetMessages) throws PluginException {
361                 return performRequest(fields, null, targetMessages);
362         }
363
364         /**
365          * Sends a request containing the given fields and waits for the target
366          * message.
367          *
368          * @param fields
369          *            The fields of the message
370          * @param data
371          *            The payload of the message
372          * @param targetMessages
373          *            The messages of the reply to wait for
374          * @return The reply message
375          * @throws PluginException
376          *             if the request could not be sent
377          */
378         private Reply performRequest(SimpleFieldSet fields, Bucket data, String... targetMessages) throws PluginException {
379                 @SuppressWarnings("synthetic-access")
380                 Reply reply = new Reply();
381                 for (String targetMessage : targetMessages) {
382                         replies.put(targetMessage, reply);
383                 }
384                 replies.put("Error", reply);
385                 synchronized (reply) {
386                         pluginConnector.sendRequest(WOT_PLUGIN_NAME, PLUGIN_CONNECTION_IDENTIFIER, fields, data);
387                         try {
388                                 long now = System.currentTimeMillis();
389                                 while ((reply.getFields() == null) && ((System.currentTimeMillis() - now) < 60000)) {
390                                         reply.wait(60000 - (System.currentTimeMillis() - now));
391                                 }
392                                 if (reply.getFields() == null) {
393                                         for (String targetMessage : targetMessages) {
394                                                 replies.remove(targetMessage);
395                                         }
396                                         replies.remove("Error");
397                                         throw new PluginException("Timeout waiting for " + targetMessages[0] + "!");
398                                 }
399                         } catch (InterruptedException ie1) {
400                                 logger.log(Level.WARNING, "Got interrupted while waiting for reply on " + targetMessages[0] + ".", ie1);
401                         }
402                 }
403                 for (String targetMessage : targetMessages) {
404                         replies.remove(targetMessage);
405                 }
406                 replies.remove("Error");
407                 if ((reply.getFields() != null) && reply.getFields().get("Message").equals("Error")) {
408                         throw new PluginException("Could not perform request for " + targetMessages[0]);
409                 }
410                 return reply;
411         }
412
413         //
414         // INTERFACE ConnectorListener
415         //
416
417         /**
418          * {@inheritDoc}
419          */
420         @Override
421         public void receivedReply(PluginConnector pluginConnector, SimpleFieldSet fields, Bucket data) {
422                 String messageName = fields.get("Message");
423                 logger.log(Level.FINEST, "Received Reply from Plugin: " + messageName);
424                 Reply reply = replies.remove(messageName);
425                 if (reply == null) {
426                         logger.log(Level.FINE, "Not waiting for a “%s” message.", messageName);
427                         return;
428                 }
429                 synchronized (reply) {
430                         reply.setFields(fields);
431                         reply.setData(data);
432                         reply.notify();
433                 }
434         }
435
436         /**
437          * Container for the data of the reply from a plugin.
438          *
439          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
440          */
441         private static class Reply {
442
443                 /** The fields of the reply. */
444                 private SimpleFieldSet fields;
445
446                 /** The payload of the reply. */
447                 private Bucket data;
448
449                 /**
450                  * Returns the fields of the reply.
451                  *
452                  * @return The fields of the reply
453                  */
454                 public SimpleFieldSet getFields() {
455                         return fields;
456                 }
457
458                 /**
459                  * Sets the fields of the reply.
460                  *
461                  * @param fields
462                  *            The fields of the reply
463                  */
464                 public void setFields(SimpleFieldSet fields) {
465                         this.fields = fields;
466                 }
467
468                 /**
469                  * Returns the payload of the reply.
470                  *
471                  * @return The payload of the reply (may be {@code null})
472                  */
473                 @SuppressWarnings("unused")
474                 public Bucket getData() {
475                         return data;
476                 }
477
478                 /**
479                  * Sets the payload of the reply.
480                  *
481                  * @param data
482                  *            The payload of the reply (may be {@code null})
483                  */
484                 public void setData(Bucket data) {
485                         this.data = data;
486                 }
487
488         }
489
490         /**
491          * Helper method to create {@link SimpleFieldSet}s with terser code.
492          *
493          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
494          */
495         private static class SimpleFieldSetConstructor {
496
497                 /** The field set being created. */
498                 private SimpleFieldSet simpleFieldSet;
499
500                 /**
501                  * Creates a new simple field set constructor.
502                  *
503                  * @param shortLived
504                  *            {@code true} if the resulting simple field set should be
505                  *            short-lived, {@code false} otherwise
506                  */
507                 private SimpleFieldSetConstructor(boolean shortLived) {
508                         simpleFieldSet = new SimpleFieldSet(shortLived);
509                 }
510
511                 //
512                 // ACCESSORS
513                 //
514
515                 /**
516                  * Returns the created simple field set.
517                  *
518                  * @return The created simple field set
519                  */
520                 public SimpleFieldSet get() {
521                         return simpleFieldSet;
522                 }
523
524                 /**
525                  * Sets the field with the given name to the given value.
526                  *
527                  * @param name
528                  *            The name of the fleld
529                  * @param value
530                  *            The value of the field
531                  * @return This constructor (for method chaining)
532                  */
533                 public SimpleFieldSetConstructor put(String name, String value) {
534                         simpleFieldSet.putOverwrite(name, value);
535                         return this;
536                 }
537
538                 //
539                 // ACTIONS
540                 //
541
542                 /**
543                  * Creates a new simple field set constructor.
544                  *
545                  * @return The created simple field set constructor
546                  */
547                 public static SimpleFieldSetConstructor create() {
548                         return create(true);
549                 }
550
551                 /**
552                  * Creates a new simple field set constructor.
553                  *
554                  * @param shortLived
555                  *            {@code true} if the resulting simple field set should be
556                  *            short-lived, {@code false} otherwise
557                  * @return The created simple field set constructor
558                  */
559                 public static SimpleFieldSetConstructor create(boolean shortLived) {
560                         SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
561                         return simpleFieldSetConstructor;
562                 }
563
564         }
565
566 }