a06f826ee10615f5f499783d20dd44b42c6f2fa0
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / WebOfTrustConnector.java
1 /*
2  * Sone - WebOfTrustConnector.java - Copyright © 2010–2019 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.*;
21 import java.util.logging.Logger;
22 import java.util.logging.*;
23 import javax.annotation.*;
24
25 import net.pterodactylus.sone.freenet.plugin.*;
26
27 import com.google.inject.*;
28 import freenet.support.*;
29 import freenet.support.api.*;
30
31 import static java.lang.String.*;
32 import static java.util.logging.Logger.*;
33 import static net.pterodactylus.sone.utils.NumberParsers.*;
34
35 /**
36  * Connector for the Web of Trust plugin.
37  */
38 @Singleton
39 public class WebOfTrustConnector {
40
41         /** The logger. */
42         private static final Logger logger = getLogger(WebOfTrustConnector.class.getName());
43
44         /** The name of the WoT plugin. */
45         private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
46
47         /** The plugin connector. */
48         private final PluginConnector pluginConnector;
49
50         /**
51          * Creates a new Web of Trust connector that uses the given plugin
52          * connector.
53          *
54          * @param pluginConnector
55          *            The plugin connector
56          */
57         @Inject
58         public WebOfTrustConnector(PluginConnector pluginConnector) {
59                 this.pluginConnector = pluginConnector;
60         }
61
62         //
63         // ACTIONS
64         //
65
66         /**
67          * Stops the web of trust connector.
68          */
69         public void stop() {
70                 /* does nothing. */
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                 PluginReply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
82                 SimpleFieldSet fields = reply.getFields();
83                 int ownIdentityCounter = -1;
84                 Set<OwnIdentity> ownIdentities = new HashSet<>();
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(id, nickname, requestUri, insertUri);
94                         ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
95                         ownIdentity.setProperties(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, @Nullable String context) throws PluginException {
128                 PluginReply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).put("WantTrustValues", "true").get());
129                 SimpleFieldSet fields = reply.getFields();
130                 Set<Identity> identities = new HashSet<>();
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(id, nickname, requestUri);
140                         identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
141                         identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
142                         Integer trust = parseInt(fields.get("Trust" + identityCounter), null);
143                         int score = parseInt(fields.get("Score" + identityCounter), 0);
144                         int rank = parseInt(fields.get("Rank" + identityCounter), 0);
145                         identity.setTrust(ownIdentity, new Trust(trust, score, rank));
146                         identities.add(identity);
147                 }
148                 return identities;
149         }
150
151         /**
152          * Adds the given context to the given identity.
153          *
154          * @param ownIdentity
155          *            The identity to add the context to
156          * @param context
157          *            The context to add
158          * @throws PluginException
159          *             if an error occured talking to the Web of Trust plugin
160          */
161         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
162                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
163         }
164
165         /**
166          * Removes the given context from the given identity.
167          *
168          * @param ownIdentity
169          *            The identity to remove the context from
170          * @param context
171          *            The context to remove
172          * @throws PluginException
173          *             if an error occured talking to the Web of Trust plugin
174          */
175         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
176                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
177         }
178
179         /**
180          * Returns the value of the property with the given name.
181          *
182          * @param identity
183          *            The identity whose properties to check
184          * @param name
185          *            The name of the property to return
186          * @return The value of the property, or {@code null} if there is no value
187          * @throws PluginException
188          *             if an error occured talking to the Web of Trust plugin
189          */
190         public String getProperty(Identity identity, String name) throws PluginException {
191                 PluginReply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
192                 return reply.getFields().get("Property");
193         }
194
195         /**
196          * Sets the property with the given name to the given value.
197          *
198          * @param ownIdentity
199          *            The identity to set the property on
200          * @param name
201          *            The name of the property to set
202          * @param value
203          *            The value to set
204          * @throws PluginException
205          *             if an error occured talking to the Web of Trust plugin
206          */
207         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
208                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
209         }
210
211         /**
212          * Removes the property with the given name.
213          *
214          * @param ownIdentity
215          *            The identity to remove the property from
216          * @param name
217          *            The name of the property to remove
218          * @throws PluginException
219          *             if an error occured talking to the Web of Trust plugin
220          */
221         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
222                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
223         }
224
225         /**
226          * Returns the trust for the given identity assigned to it by the given own
227          * identity.
228          *
229          * @param ownIdentity
230          *            The own identity
231          * @param identity
232          *            The identity to get the trust for
233          * @return The trust for the given identity
234          * @throws PluginException
235          *             if an error occured talking to the Web of Trust plugin
236          */
237         public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
238                 PluginReply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
239                 String trust = getTrustReply.getFields().get("Trust");
240                 String score = getTrustReply.getFields().get("Score");
241                 String rank = getTrustReply.getFields().get("Rank");
242                 Integer explicit = null;
243                 Integer implicit = null;
244                 Integer distance = null;
245                 try {
246                         explicit = Integer.valueOf(trust);
247                 } catch (NumberFormatException nfe1) {
248                         /* ignore. */
249                 }
250                 try {
251                         implicit = Integer.valueOf(score);
252                         distance = Integer.valueOf(rank);
253                 } catch (NumberFormatException nfe1) {
254                         /* ignore. */
255                 }
256                 return new Trust(explicit, implicit, distance);
257         }
258
259         /**
260          * Sets the trust for the given identity.
261          *
262          * @param ownIdentity
263          *            The trusting identity
264          * @param identity
265          *            The trusted identity
266          * @param trust
267          *            The amount of trust (-100 thru 100)
268          * @param comment
269          *            The comment or explanation of the trust value
270          * @throws PluginException
271          *             if an error occured talking to the Web of Trust plugin
272          */
273         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
274                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
275         }
276
277         /**
278          * Removes any trust assignment of the given own identity for the given
279          * identity.
280          *
281          * @param ownIdentity
282          *            The own identity
283          * @param identity
284          *            The identity to remove all trust for
285          * @throws WebOfTrustException
286          *             if an error occurs
287          */
288         public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
289                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
290         }
291
292         /**
293          * Pings the Web of Trust plugin. If the plugin can not be reached, a
294          * {@link PluginException} is thrown.
295          *
296          * @throws PluginException
297          *             if the plugin is not loaded
298          */
299         public void ping() throws PluginException {
300                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
301         }
302
303         //
304         // PRIVATE ACTIONS
305         //
306
307         /**
308          * Parses the contexts from the given fields.
309          *
310          * @param prefix
311          *            The prefix to use to access the contexts
312          * @param fields
313          *            The fields to parse the contexts from
314          * @return The parsed contexts
315          */
316         private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
317                 Set<String> contexts = new HashSet<>();
318                 int contextCounter = -1;
319                 while (true) {
320                         String context = fields.get(prefix + "Context" + ++contextCounter);
321                         if (context == null) {
322                                 break;
323                         }
324                         contexts.add(context);
325                 }
326                 return contexts;
327         }
328
329         /**
330          * Parses the properties from the given fields.
331          *
332          * @param prefix
333          *            The prefix to use to access the properties
334          * @param fields
335          *            The fields to parse the properties from
336          * @return The parsed properties
337          */
338         private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
339                 Map<String, String> properties = new HashMap<>();
340                 int propertiesCounter = -1;
341                 while (true) {
342                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
343                         if (propertyName == null) {
344                                 break;
345                         }
346                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
347                         properties.put(propertyName, propertyValue);
348                 }
349                 return properties;
350         }
351
352         /**
353          * Sends a request containing the given fields and waits for the target
354          * message.
355          *
356          * @param fields
357          *            The fields of the message
358          * @return The reply message
359          * @throws PluginException
360          *             if the request could not be sent
361          */
362         private PluginReply performRequest(SimpleFieldSet fields) throws PluginException {
363                 return performRequest(fields, null);
364         }
365
366         /**
367          * Sends a request containing the given fields and waits for the target
368          * message.
369          *
370          * @param fields
371          *            The fields of the message
372          * @param data
373          *            The payload of the message
374          * @return The reply message
375          * @throws PluginException
376          *             if the request could not be sent
377          */
378         private PluginReply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
379                 logger.log(Level.FINE, format("Sending FCP Request: %s", fields.get("Message")));
380                 PluginReply pluginReply = pluginConnector.sendRequest(WOT_PLUGIN_NAME, "", fields, data);
381                 logger.log(Level.FINEST, format("Received FCP Response for %s: %s", fields.get("Message"), pluginReply.getFields().get("Message")));
382                 if ("Error".equals(pluginReply.getFields().get("Message"))) {
383                         throw new PluginException("Could not perform request for " + fields.get("Message"));
384                 }
385                 return pluginReply;
386         }
387
388         /**
389          * Helper method to create {@link SimpleFieldSet}s with terser code.
390          */
391         private static class SimpleFieldSetConstructor {
392
393                 /** The field set being created. */
394                 private SimpleFieldSet simpleFieldSet;
395
396                 /**
397                  * Creates a new simple field set constructor.
398                  *
399                  * @param shortLived
400                  *            {@code true} if the resulting simple field set should be
401                  *            short-lived, {@code false} otherwise
402                  */
403                 private SimpleFieldSetConstructor(boolean shortLived) {
404                         simpleFieldSet = new SimpleFieldSet(shortLived);
405                 }
406
407                 //
408                 // ACCESSORS
409                 //
410
411                 /**
412                  * Returns the created simple field set.
413                  *
414                  * @return The created simple field set
415                  */
416                 public SimpleFieldSet get() {
417                         return simpleFieldSet;
418                 }
419
420                 /**
421                  * Sets the field with the given name to the given value.
422                  *
423                  * @param name
424                  *            The name of the fleld
425                  * @param value
426                  *            The value of the field
427                  * @return This constructor (for method chaining)
428                  */
429                 public SimpleFieldSetConstructor put(String name, String value) {
430                         simpleFieldSet.putOverwrite(name, value);
431                         return this;
432                 }
433
434                 //
435                 // ACTIONS
436                 //
437
438                 /**
439                  * Creates a new simple field set constructor.
440                  *
441                  * @return The created simple field set constructor
442                  */
443                 public static SimpleFieldSetConstructor create() {
444                         return create(true);
445                 }
446
447                 /**
448                  * Creates a new simple field set constructor.
449                  *
450                  * @param shortLived
451                  *            {@code true} if the resulting simple field set should be
452                  *            short-lived, {@code false} otherwise
453                  * @return The created simple field set constructor
454                  */
455                 public static SimpleFieldSetConstructor create(boolean shortLived) {
456                         return new SimpleFieldSetConstructor(shortLived);
457                 }
458
459         }
460
461 }