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