Merge branch 'edit-wot-trust' into next
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.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.core;
19
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Client;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Profile.Field;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.freenet.wot.Identity;
41 import net.pterodactylus.sone.freenet.wot.IdentityListener;
42 import net.pterodactylus.sone.freenet.wot.IdentityManager;
43 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
44 import net.pterodactylus.sone.freenet.wot.Trust;
45 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
46 import net.pterodactylus.sone.main.SonePlugin;
47 import net.pterodactylus.util.config.Configuration;
48 import net.pterodactylus.util.config.ConfigurationException;
49 import net.pterodactylus.util.logging.Logging;
50 import net.pterodactylus.util.number.Numbers;
51 import net.pterodactylus.util.validation.Validation;
52 import net.pterodactylus.util.version.Version;
53 import freenet.keys.FreenetURI;
54
55 /**
56  * The Sone core.
57  *
58  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59  */
60 public class Core implements IdentityListener, UpdateListener {
61
62         /**
63          * Enumeration for the possible states of a {@link Sone}.
64          *
65          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66          */
67         public enum SoneStatus {
68
69                 /** The Sone is unknown, i.e. not yet downloaded. */
70                 unknown,
71
72                 /** The Sone is idle, i.e. not being downloaded or inserted. */
73                 idle,
74
75                 /** The Sone is currently being inserted. */
76                 inserting,
77
78                 /** The Sone is currently being downloaded. */
79                 downloading,
80         }
81
82         /** The logger. */
83         private static final Logger logger = Logging.getLogger(Core.class);
84
85         /** The options. */
86         private final Options options = new Options();
87
88         /** The core listener manager. */
89         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
90
91         /** The configuration. */
92         private Configuration configuration;
93
94         /** Whether we’re currently saving the configuration. */
95         private boolean storingConfiguration = false;
96
97         /** The identity manager. */
98         private final IdentityManager identityManager;
99
100         /** Interface to freenet. */
101         private final FreenetInterface freenetInterface;
102
103         /** The Sone downloader. */
104         private final SoneDownloader soneDownloader;
105
106         /** The update checker. */
107         private final UpdateChecker updateChecker;
108
109         /** Whether the core has been stopped. */
110         private volatile boolean stopped;
111
112         /** The Sones’ statuses. */
113         /* synchronize access on itself. */
114         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
115
116         /** Locked local Sones. */
117         /* synchronize on itself. */
118         private final Set<Sone> lockedSones = new HashSet<Sone>();
119
120         /** Sone inserters. */
121         /* synchronize access on this on localSones. */
122         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
123
124         /** All local Sones. */
125         /* synchronize access on this on itself. */
126         private Map<String, Sone> localSones = new HashMap<String, Sone>();
127
128         /** All remote Sones. */
129         /* synchronize access on this on itself. */
130         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
131
132         /** All new Sones. */
133         private Set<String> newSones = new HashSet<String>();
134
135         /** All known Sones. */
136         /* synchronize access on {@link #newSones}. */
137         private Set<String> knownSones = new HashSet<String>();
138
139         /** All posts. */
140         private Map<String, Post> posts = new HashMap<String, Post>();
141
142         /** All new posts. */
143         private Set<String> newPosts = new HashSet<String>();
144
145         /** All known posts. */
146         /* synchronize access on {@link #newPosts}. */
147         private Set<String> knownPosts = new HashSet<String>();
148
149         /** All replies. */
150         private Map<String, Reply> replies = new HashMap<String, Reply>();
151
152         /** All new replies. */
153         private Set<String> newReplies = new HashSet<String>();
154
155         /** All known replies. */
156         private Set<String> knownReplies = new HashSet<String>();
157
158         /** Trusted identities, sorted by own identities. */
159         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
160
161         /**
162          * Creates a new core.
163          *
164          * @param configuration
165          *            The configuration of the core
166          * @param freenetInterface
167          *            The freenet interface
168          * @param identityManager
169          *            The identity manager
170          */
171         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
172                 this.configuration = configuration;
173                 this.freenetInterface = freenetInterface;
174                 this.identityManager = identityManager;
175                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
176                 this.updateChecker = new UpdateChecker(freenetInterface);
177         }
178
179         //
180         // LISTENER MANAGEMENT
181         //
182
183         /**
184          * Adds a new core listener.
185          *
186          * @param coreListener
187          *            The listener to add
188          */
189         public void addCoreListener(CoreListener coreListener) {
190                 coreListenerManager.addListener(coreListener);
191         }
192
193         /**
194          * Removes a core listener.
195          *
196          * @param coreListener
197          *            The listener to remove
198          */
199         public void removeCoreListener(CoreListener coreListener) {
200                 coreListenerManager.removeListener(coreListener);
201         }
202
203         //
204         // ACCESSORS
205         //
206
207         /**
208          * Sets the configuration to use. This will automatically save the current
209          * configuration to the given configuration.
210          *
211          * @param configuration
212          *            The new configuration to use
213          */
214         public void setConfiguration(Configuration configuration) {
215                 this.configuration = configuration;
216                 saveConfiguration();
217         }
218
219         /**
220          * Returns the options used by the core.
221          *
222          * @return The options of the core
223          */
224         public Options getOptions() {
225                 return options;
226         }
227
228         /**
229          * Returns whether the “Sone rescue mode” is currently activated.
230          *
231          * @return {@code true} if the “Sone rescue mode” is currently activated,
232          *         {@code false} if it is not
233          */
234         public boolean isSoneRescueMode() {
235                 return options.getBooleanOption("SoneRescueMode").get();
236         }
237
238         /**
239          * Returns the identity manager used by the core.
240          *
241          * @return The identity manager
242          */
243         public IdentityManager getIdentityManager() {
244                 return identityManager;
245         }
246
247         /**
248          * Returns the update checker.
249          *
250          * @return The update checker
251          */
252         public UpdateChecker getUpdateChecker() {
253                 return updateChecker;
254         }
255
256         /**
257          * Returns the status of the given Sone.
258          *
259          * @param sone
260          *            The Sone to get the status for
261          * @return The status of the Sone
262          */
263         public SoneStatus getSoneStatus(Sone sone) {
264                 synchronized (soneStatuses) {
265                         return soneStatuses.get(sone);
266                 }
267         }
268
269         /**
270          * Sets the status of the given Sone.
271          *
272          * @param sone
273          *            The Sone to set the status of
274          * @param soneStatus
275          *            The status to set
276          */
277         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
278                 synchronized (soneStatuses) {
279                         soneStatuses.put(sone, soneStatus);
280                 }
281         }
282
283         /**
284          * Returns whether the given Sone is currently locked.
285          *
286          * @param sone
287          *            The sone to check
288          * @return {@code true} if the Sone is locked, {@code false} if it is not
289          */
290         public boolean isLocked(Sone sone) {
291                 synchronized (lockedSones) {
292                         return lockedSones.contains(sone);
293                 }
294         }
295
296         /**
297          * Returns all Sones, remote and local.
298          *
299          * @return All Sones
300          */
301         public Set<Sone> getSones() {
302                 Set<Sone> allSones = new HashSet<Sone>();
303                 allSones.addAll(getLocalSones());
304                 allSones.addAll(getRemoteSones());
305                 return allSones;
306         }
307
308         /**
309          * Returns the Sone with the given ID, regardless whether it’s local or
310          * remote.
311          *
312          * @param id
313          *            The ID of the Sone to get
314          * @return The Sone with the given ID, or {@code null} if there is no such
315          *         Sone
316          */
317         public Sone getSone(String id) {
318                 return getSone(id, true);
319         }
320
321         /**
322          * Returns the Sone with the given ID, regardless whether it’s local or
323          * remote.
324          *
325          * @param id
326          *            The ID of the Sone to get
327          * @param create
328          *            {@code true} to create a new Sone if none exists,
329          *            {@code false} to return {@code null} if a Sone with the given
330          *            ID does not exist
331          * @return The Sone with the given ID, or {@code null} if there is no such
332          *         Sone
333          */
334         public Sone getSone(String id, boolean create) {
335                 if (isLocalSone(id)) {
336                         return getLocalSone(id);
337                 }
338                 return getRemoteSone(id, create);
339         }
340
341         /**
342          * Checks whether the core knows a Sone with the given ID.
343          *
344          * @param id
345          *            The ID of the Sone
346          * @return {@code true} if there is a Sone with the given ID, {@code false}
347          *         otherwise
348          */
349         public boolean hasSone(String id) {
350                 return isLocalSone(id) || isRemoteSone(id);
351         }
352
353         /**
354          * Returns whether the given Sone is a local Sone.
355          *
356          * @param sone
357          *            The Sone to check for its locality
358          * @return {@code true} if the given Sone is local, {@code false} otherwise
359          */
360         public boolean isLocalSone(Sone sone) {
361                 synchronized (localSones) {
362                         return localSones.containsKey(sone.getId());
363                 }
364         }
365
366         /**
367          * Returns whether the given ID is the ID of a local Sone.
368          *
369          * @param id
370          *            The Sone ID to check for its locality
371          * @return {@code true} if the given ID is a local Sone, {@code false}
372          *         otherwise
373          */
374         public boolean isLocalSone(String id) {
375                 synchronized (localSones) {
376                         return localSones.containsKey(id);
377                 }
378         }
379
380         /**
381          * Returns all local Sones.
382          *
383          * @return All local Sones
384          */
385         public Set<Sone> getLocalSones() {
386                 synchronized (localSones) {
387                         return new HashSet<Sone>(localSones.values());
388                 }
389         }
390
391         /**
392          * Returns the local Sone with the given ID.
393          *
394          * @param id
395          *            The ID of the Sone to get
396          * @return The Sone with the given ID
397          */
398         public Sone getLocalSone(String id) {
399                 return getLocalSone(id, true);
400         }
401
402         /**
403          * Returns the local Sone with the given ID, optionally creating a new Sone.
404          *
405          * @param id
406          *            The ID of the Sone
407          * @param create
408          *            {@code true} to create a new Sone if none exists,
409          *            {@code false} to return null if none exists
410          * @return The Sone with the given ID, or {@code null}
411          */
412         public Sone getLocalSone(String id, boolean create) {
413                 synchronized (localSones) {
414                         Sone sone = localSones.get(id);
415                         if ((sone == null) && create) {
416                                 sone = new Sone(id);
417                                 localSones.put(id, sone);
418                         }
419                         return sone;
420                 }
421         }
422
423         /**
424          * Returns all remote Sones.
425          *
426          * @return All remote Sones
427          */
428         public Set<Sone> getRemoteSones() {
429                 synchronized (remoteSones) {
430                         return new HashSet<Sone>(remoteSones.values());
431                 }
432         }
433
434         /**
435          * Returns the remote Sone with the given ID.
436          *
437          * @param id
438          *            The ID of the remote Sone to get
439          * @return The Sone with the given ID
440          */
441         public Sone getRemoteSone(String id) {
442                 return getRemoteSone(id, true);
443         }
444
445         /**
446          * Returns the remote Sone with the given ID.
447          *
448          * @param id
449          *            The ID of the remote Sone to get
450          * @param create
451          *            {@code true} to always create a Sone, {@code false} to return
452          *            {@code null} if no Sone with the given ID exists
453          * @return The Sone with the given ID
454          */
455         public Sone getRemoteSone(String id, boolean create) {
456                 synchronized (remoteSones) {
457                         Sone sone = remoteSones.get(id);
458                         if ((sone == null) && create) {
459                                 sone = new Sone(id);
460                                 remoteSones.put(id, sone);
461                         }
462                         return sone;
463                 }
464         }
465
466         /**
467          * Returns whether the given Sone is a remote Sone.
468          *
469          * @param sone
470          *            The Sone to check
471          * @return {@code true} if the given Sone is a remote Sone, {@code false}
472          *         otherwise
473          */
474         public boolean isRemoteSone(Sone sone) {
475                 synchronized (remoteSones) {
476                         return remoteSones.containsKey(sone.getId());
477                 }
478         }
479
480         /**
481          * Returns whether the Sone with the given ID is a remote Sone.
482          *
483          * @param id
484          *            The ID of the Sone to check
485          * @return {@code true} if the Sone with the given ID is a remote Sone,
486          *         {@code false} otherwise
487          */
488         public boolean isRemoteSone(String id) {
489                 synchronized (remoteSones) {
490                         return remoteSones.containsKey(id);
491                 }
492         }
493
494         /**
495          * Returns whether the given Sone is a new Sone. After this check, the Sone
496          * is marked as known, i.e. a second call with the same parameters will
497          * always yield {@code false}.
498          *
499          * @param sone
500          *            The sone to check for
501          * @return {@code true} if the given Sone is new, false otherwise
502          */
503         public boolean isNewSone(Sone sone) {
504                 synchronized (newSones) {
505                         boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
506                         knownSones.add(sone.getId());
507                         if (isNew) {
508                                 coreListenerManager.fireMarkSoneKnown(sone);
509                         }
510                         return isNew;
511                 }
512         }
513
514         /**
515          * Returns whether the given Sone has been modified.
516          *
517          * @param sone
518          *            The Sone to check for modifications
519          * @return {@code true} if a modification has been detected in the Sone,
520          *         {@code false} otherwise
521          */
522         public boolean isModifiedSone(Sone sone) {
523                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
524         }
525
526         /**
527          * Returns whether the target Sone is trusted by the origin Sone.
528          *
529          * @param origin
530          *            The origin Sone
531          * @param target
532          *            The target Sone
533          * @return {@code true} if the target Sone is trusted by the origin Sone
534          */
535         public boolean isSoneTrusted(Sone origin, Sone target) {
536                 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
537         }
538
539         /**
540          * Returns the post with the given ID.
541          *
542          * @param postId
543          *            The ID of the post to get
544          * @return The post, or {@code null} if there is no such post
545          */
546         public Post getPost(String postId) {
547                 return getPost(postId, true);
548         }
549
550         /**
551          * Returns the post with the given ID, optionally creating a new post.
552          *
553          * @param postId
554          *            The ID of the post to get
555          * @param create
556          *            {@code true} it create a new post if no post with the given ID
557          *            exists, {@code false} to return {@code null}
558          * @return The post, or {@code null} if there is no such post
559          */
560         public Post getPost(String postId, boolean create) {
561                 synchronized (posts) {
562                         Post post = posts.get(postId);
563                         if ((post == null) && create) {
564                                 post = new Post(postId);
565                                 posts.put(postId, post);
566                         }
567                         return post;
568                 }
569         }
570
571         /**
572          * Returns whether the given post ID is new. After this method returns it is
573          * marked a known post ID.
574          *
575          * @param postId
576          *            The post ID
577          * @return {@code true} if the post is considered to be new, {@code false}
578          *         otherwise
579          */
580         public boolean isNewPost(String postId) {
581                 return isNewPost(postId, true);
582         }
583
584         /**
585          * Returns whether the given post ID is new. If {@code markAsKnown} is
586          * {@code true} then after this method returns the post ID is marked a known
587          * post ID.
588          *
589          * @param postId
590          *            The post ID
591          * @param markAsKnown
592          *            {@code true} to mark the post ID as known, {@code false} to
593          *            not to mark it as known
594          * @return {@code true} if the post is considered to be new, {@code false}
595          *         otherwise
596          */
597         public boolean isNewPost(String postId, boolean markAsKnown) {
598                 synchronized (newPosts) {
599                         boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
600                         if (markAsKnown) {
601                                 Post post = getPost(postId, false);
602                                 if (post != null) {
603                                         markPostKnown(post);
604                                 }
605                         }
606                         return isNew;
607                 }
608         }
609
610         /**
611          * Returns the reply with the given ID. If there is no reply with the given
612          * ID yet, a new one is created.
613          *
614          * @param replyId
615          *            The ID of the reply to get
616          * @return The reply
617          */
618         public Reply getReply(String replyId) {
619                 return getReply(replyId, true);
620         }
621
622         /**
623          * Returns the reply with the given ID. If there is no reply with the given
624          * ID yet, a new one is created, unless {@code create} is false in which
625          * case {@code null} is returned.
626          *
627          * @param replyId
628          *            The ID of the reply to get
629          * @param create
630          *            {@code true} to always return a {@link Reply}, {@code false}
631          *            to return {@code null} if no reply can be found
632          * @return The reply, or {@code null} if there is no such reply
633          */
634         public Reply getReply(String replyId, boolean create) {
635                 synchronized (replies) {
636                         Reply reply = replies.get(replyId);
637                         if (create && (reply == null)) {
638                                 reply = new Reply(replyId);
639                                 replies.put(replyId, reply);
640                         }
641                         return reply;
642                 }
643         }
644
645         /**
646          * Returns all replies for the given post, order ascending by time.
647          *
648          * @param post
649          *            The post to get all replies for
650          * @return All replies for the given post
651          */
652         public List<Reply> getReplies(Post post) {
653                 Set<Sone> sones = getSones();
654                 List<Reply> replies = new ArrayList<Reply>();
655                 for (Sone sone : sones) {
656                         for (Reply reply : sone.getReplies()) {
657                                 if (reply.getPost().equals(post)) {
658                                         replies.add(reply);
659                                 }
660                         }
661                 }
662                 Collections.sort(replies, Reply.TIME_COMPARATOR);
663                 return replies;
664         }
665
666         /**
667          * Returns whether the reply with the given ID is new.
668          *
669          * @param replyId
670          *            The ID of the reply to check
671          * @return {@code true} if the reply is considered to be new, {@code false}
672          *         otherwise
673          */
674         public boolean isNewReply(String replyId) {
675                 return isNewReply(replyId, true);
676         }
677
678         /**
679          * Returns whether the reply with the given ID is new.
680          *
681          * @param replyId
682          *            The ID of the reply to check
683          * @param markAsKnown
684          *            {@code true} to mark the reply as known, {@code false} to not
685          *            to mark it as known
686          * @return {@code true} if the reply is considered to be new, {@code false}
687          *         otherwise
688          */
689         public boolean isNewReply(String replyId, boolean markAsKnown) {
690                 synchronized (newReplies) {
691                         boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
692                         if (markAsKnown) {
693                                 Reply reply = getReply(replyId, false);
694                                 if (reply != null) {
695                                         markReplyKnown(reply);
696                                 }
697                         }
698                         return isNew;
699                 }
700         }
701
702         /**
703          * Returns all Sones that have liked the given post.
704          *
705          * @param post
706          *            The post to get the liking Sones for
707          * @return The Sones that like the given post
708          */
709         public Set<Sone> getLikes(Post post) {
710                 Set<Sone> sones = new HashSet<Sone>();
711                 for (Sone sone : getSones()) {
712                         if (sone.getLikedPostIds().contains(post.getId())) {
713                                 sones.add(sone);
714                         }
715                 }
716                 return sones;
717         }
718
719         /**
720          * Returns all Sones that have liked the given reply.
721          *
722          * @param reply
723          *            The reply to get the liking Sones for
724          * @return The Sones that like the given reply
725          */
726         public Set<Sone> getLikes(Reply reply) {
727                 Set<Sone> sones = new HashSet<Sone>();
728                 for (Sone sone : getSones()) {
729                         if (sone.getLikedReplyIds().contains(reply.getId())) {
730                                 sones.add(sone);
731                         }
732                 }
733                 return sones;
734         }
735
736         //
737         // ACTIONS
738         //
739
740         /**
741          * Locks the given Sone. A locked Sone will not be inserted by
742          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
743          * again.
744          *
745          * @param sone
746          *            The sone to lock
747          */
748         public void lockSone(Sone sone) {
749                 synchronized (lockedSones) {
750                         if (lockedSones.add(sone)) {
751                                 coreListenerManager.fireSoneLocked(sone);
752                         }
753                 }
754         }
755
756         /**
757          * Unlocks the given Sone.
758          *
759          * @see #lockSone(Sone)
760          * @param sone
761          *            The sone to unlock
762          */
763         public void unlockSone(Sone sone) {
764                 synchronized (lockedSones) {
765                         if (lockedSones.remove(sone)) {
766                                 coreListenerManager.fireSoneUnlocked(sone);
767                         }
768                 }
769         }
770
771         /**
772          * Adds a local Sone from the given ID which has to be the ID of an own
773          * identity.
774          *
775          * @param id
776          *            The ID of an own identity to add a Sone for
777          * @return The added (or already existing) Sone
778          */
779         public Sone addLocalSone(String id) {
780                 synchronized (localSones) {
781                         if (localSones.containsKey(id)) {
782                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
783                                 return localSones.get(id);
784                         }
785                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
786                         if (ownIdentity == null) {
787                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
788                                 return null;
789                         }
790                         return addLocalSone(ownIdentity);
791                 }
792         }
793
794         /**
795          * Adds a local Sone from the given own identity.
796          *
797          * @param ownIdentity
798          *            The own identity to create a Sone from
799          * @return The added (or already existing) Sone
800          */
801         public Sone addLocalSone(OwnIdentity ownIdentity) {
802                 if (ownIdentity == null) {
803                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
804                         return null;
805                 }
806                 synchronized (localSones) {
807                         final Sone sone;
808                         try {
809                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
810                         } catch (MalformedURLException mue1) {
811                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
812                                 return null;
813                         }
814                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
815                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
816                         /* TODO - load posts ’n stuff */
817                         localSones.put(ownIdentity.getId(), sone);
818                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
819                         soneInserters.put(sone, soneInserter);
820                         setSoneStatus(sone, SoneStatus.idle);
821                         loadSone(sone);
822                         if (!isSoneRescueMode()) {
823                                 soneInserter.start();
824                         }
825                         new Thread(new Runnable() {
826
827                                 @Override
828                                 @SuppressWarnings("synthetic-access")
829                                 public void run() {
830                                         if (!isSoneRescueMode()) {
831                                                 soneDownloader.fetchSone(sone);
832                                                 return;
833                                         }
834                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
835                                         coreListenerManager.fireRescuingSone(sone);
836                                         lockSone(sone);
837                                         long edition = sone.getLatestEdition();
838                                         while (!stopped && (edition >= 0) && isSoneRescueMode()) {
839                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
840                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
841                                                 --edition;
842                                         }
843                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
844                                         saveSone(sone);
845                                         coreListenerManager.fireRescuedSone(sone);
846                                         soneInserter.start();
847                                 }
848
849                         }, "Sone Downloader").start();
850                         return sone;
851                 }
852         }
853
854         /**
855          * Creates a new Sone for the given own identity.
856          *
857          * @param ownIdentity
858          *            The own identity to create a Sone for
859          * @return The created Sone
860          */
861         public Sone createSone(OwnIdentity ownIdentity) {
862                 try {
863                         ownIdentity.addContext("Sone");
864                 } catch (WebOfTrustException wote1) {
865                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
866                         return null;
867                 }
868                 Sone sone = addLocalSone(ownIdentity);
869                 return sone;
870         }
871
872         /**
873          * Adds the Sone of the given identity.
874          *
875          * @param identity
876          *            The identity whose Sone to add
877          * @return The added or already existing Sone
878          */
879         public Sone addRemoteSone(Identity identity) {
880                 if (identity == null) {
881                         logger.log(Level.WARNING, "Given Identity is null!");
882                         return null;
883                 }
884                 synchronized (remoteSones) {
885                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
886                         boolean newSone = sone.getRequestUri() == null;
887                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
888                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
889                         if (newSone) {
890                                 synchronized (newSones) {
891                                         newSone = !knownSones.contains(sone.getId());
892                                         if (newSone) {
893                                                 newSones.add(sone.getId());
894                                         }
895                                 }
896                                 if (newSone) {
897                                         coreListenerManager.fireNewSoneFound(sone);
898                                 }
899                         }
900                         remoteSones.put(identity.getId(), sone);
901                         soneDownloader.addSone(sone);
902                         setSoneStatus(sone, SoneStatus.unknown);
903                         new Thread(new Runnable() {
904
905                                 @Override
906                                 @SuppressWarnings("synthetic-access")
907                                 public void run() {
908                                         soneDownloader.fetchSone(sone);
909                                 }
910
911                         }, "Sone Downloader").start();
912                         return sone;
913                 }
914         }
915
916         /**
917          * Retrieves the trust relationship from the origin to the target. If the
918          * trust relationship can not be retrieved, {@code null} is returned.
919          *
920          * @see Identity#getTrust(OwnIdentity)
921          * @param origin
922          *            The origin of the trust tree
923          * @param target
924          *            The target of the trust
925          * @return The trust relationship
926          */
927         public Trust getTrust(Sone origin, Sone target) {
928                 if (!isLocalSone(origin)) {
929                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
930                         return null;
931                 }
932                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
933         }
934
935         /**
936          * Sets the trust value of the given origin Sone for the target Sone.
937          *
938          * @param origin
939          *            The origin Sone
940          * @param target
941          *            The target Sone
942          * @param trustValue
943          *            The trust value (from {@code -100} to {@code 100})
944          */
945         public void setTrust(Sone origin, Sone target, int trustValue) {
946                 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
947                 try {
948                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, options.getStringOption("TrustComment").get());
949                 } catch (WebOfTrustException wote1) {
950                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
951                 }
952         }
953
954         /**
955          * Removes any trust assignment for the given target Sone.
956          *
957          * @param origin
958          *            The trust origin
959          * @param target
960          *            The trust target
961          */
962         public void removeTrust(Sone origin, Sone target) {
963                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
964                 try {
965                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
966                 } catch (WebOfTrustException wote1) {
967                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
968                 }
969         }
970
971         /**
972          * Assigns the configured positive trust value for the given target.
973          *
974          * @param origin
975          *            The trust origin
976          * @param target
977          *            The trust target
978          */
979         public void trustSone(Sone origin, Sone target) {
980                 setTrust(origin, target, options.getIntegerOption("PositiveTrust").get());
981         }
982
983         /**
984          * Assigns the configured negative trust value for the given target.
985          *
986          * @param origin
987          *            The trust origin
988          * @param target
989          *            The trust target
990          */
991         public void distrustSone(Sone origin, Sone target) {
992                 setTrust(origin, target, options.getIntegerOption("NegativeTrust").get());
993         }
994
995         /**
996          * Removes the trust assignment for the given target.
997          *
998          * @param origin
999          *            The trust origin
1000          * @param target
1001          *            The trust target
1002          */
1003         public void untrustSone(Sone origin, Sone target) {
1004                 removeTrust(origin, target);
1005         }
1006
1007         /**
1008          * Updates the stores Sone with the given Sone.
1009          *
1010          * @param sone
1011          *            The updated Sone
1012          */
1013         public void updateSone(Sone sone) {
1014                 if (hasSone(sone.getId())) {
1015                         boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
1016                         Sone storedSone = getSone(sone.getId());
1017                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1018                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1019                                 return;
1020                         }
1021                         synchronized (posts) {
1022                                 if (!soneRescueMode) {
1023                                         for (Post post : storedSone.getPosts()) {
1024                                                 posts.remove(post.getId());
1025                                                 if (!sone.getPosts().contains(post)) {
1026                                                         coreListenerManager.firePostRemoved(post);
1027                                                 }
1028                                         }
1029                                 }
1030                                 synchronized (newPosts) {
1031                                         for (Post post : sone.getPosts()) {
1032                                                 post.setSone(getSone(post.getSone().getId()));
1033                                                 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
1034                                                         newPosts.add(post.getId());
1035                                                         coreListenerManager.fireNewPostFound(post);
1036                                                 }
1037                                                 posts.put(post.getId(), post);
1038                                         }
1039                                 }
1040                         }
1041                         synchronized (replies) {
1042                                 if (!soneRescueMode) {
1043                                         for (Reply reply : storedSone.getReplies()) {
1044                                                 replies.remove(reply.getId());
1045                                                 if (!sone.getReplies().contains(reply)) {
1046                                                         coreListenerManager.fireReplyRemoved(reply);
1047                                                 }
1048                                         }
1049                                 }
1050                                 synchronized (newReplies) {
1051                                         for (Reply reply : sone.getReplies()) {
1052                                                 reply.setSone(getSone(reply.getSone().getId()));
1053                                                 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
1054                                                         newReplies.add(reply.getId());
1055                                                         coreListenerManager.fireNewReplyFound(reply);
1056                                                 }
1057                                                 replies.put(reply.getId(), reply);
1058                                         }
1059                                 }
1060                         }
1061                         synchronized (storedSone) {
1062                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1063                                         storedSone.setTime(sone.getTime());
1064                                 }
1065                                 storedSone.setClient(sone.getClient());
1066                                 storedSone.setProfile(sone.getProfile());
1067                                 if (soneRescueMode) {
1068                                         for (Post post : sone.getPosts()) {
1069                                                 storedSone.addPost(post);
1070                                         }
1071                                         for (Reply reply : sone.getReplies()) {
1072                                                 storedSone.addReply(reply);
1073                                         }
1074                                         for (String likedPostId : sone.getLikedPostIds()) {
1075                                                 storedSone.addLikedPostId(likedPostId);
1076                                         }
1077                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1078                                                 storedSone.addLikedReplyId(likedReplyId);
1079                                         }
1080                                 } else {
1081                                         storedSone.setPosts(sone.getPosts());
1082                                         storedSone.setReplies(sone.getReplies());
1083                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1084                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1085                                 }
1086                                 storedSone.setLatestEdition(sone.getLatestEdition());
1087                         }
1088                 }
1089         }
1090
1091         /**
1092          * Deletes the given Sone. This will remove the Sone from the
1093          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1094          * and remove the context from its identity.
1095          *
1096          * @param sone
1097          *            The Sone to delete
1098          */
1099         public void deleteSone(Sone sone) {
1100                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1101                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1102                         return;
1103                 }
1104                 synchronized (localSones) {
1105                         if (!localSones.containsKey(sone.getId())) {
1106                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1107                                 return;
1108                         }
1109                         localSones.remove(sone.getId());
1110                         soneInserters.remove(sone).stop();
1111                 }
1112                 try {
1113                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1114                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1115                 } catch (WebOfTrustException wote1) {
1116                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1117                 }
1118                 try {
1119                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1120                 } catch (ConfigurationException ce1) {
1121                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1122                 }
1123         }
1124
1125         /**
1126          * Loads and updates the given Sone from the configuration. If any error is
1127          * encountered, loading is aborted and the given Sone is not changed.
1128          *
1129          * @param sone
1130          *            The Sone to load and update
1131          */
1132         public void loadSone(Sone sone) {
1133                 if (!isLocalSone(sone)) {
1134                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1135                         return;
1136                 }
1137
1138                 /* load Sone. */
1139                 String sonePrefix = "Sone/" + sone.getId();
1140                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1141                 if (soneTime == null) {
1142                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1143                         return;
1144                 }
1145                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1146
1147                 /* load profile. */
1148                 Profile profile = new Profile();
1149                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1150                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1151                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1152                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1153                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1154                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1155
1156                 /* load profile fields. */
1157                 while (true) {
1158                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1159                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1160                         if (fieldName == null) {
1161                                 break;
1162                         }
1163                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1164                         profile.addField(fieldName).setValue(fieldValue);
1165                 }
1166
1167                 /* load posts. */
1168                 Set<Post> posts = new HashSet<Post>();
1169                 while (true) {
1170                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1171                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1172                         if (postId == null) {
1173                                 break;
1174                         }
1175                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1176                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1177                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1178                         if ((postTime == 0) || (postText == null)) {
1179                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1180                                 return;
1181                         }
1182                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1183                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1184                                 post.setRecipient(getSone(postRecipientId));
1185                         }
1186                         posts.add(post);
1187                 }
1188
1189                 /* load replies. */
1190                 Set<Reply> replies = new HashSet<Reply>();
1191                 while (true) {
1192                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1193                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1194                         if (replyId == null) {
1195                                 break;
1196                         }
1197                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1198                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1199                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1200                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1201                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1202                                 return;
1203                         }
1204                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1205                 }
1206
1207                 /* load post likes. */
1208                 Set<String> likedPostIds = new HashSet<String>();
1209                 while (true) {
1210                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1211                         if (likedPostId == null) {
1212                                 break;
1213                         }
1214                         likedPostIds.add(likedPostId);
1215                 }
1216
1217                 /* load reply likes. */
1218                 Set<String> likedReplyIds = new HashSet<String>();
1219                 while (true) {
1220                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1221                         if (likedReplyId == null) {
1222                                 break;
1223                         }
1224                         likedReplyIds.add(likedReplyId);
1225                 }
1226
1227                 /* load friends. */
1228                 Set<String> friends = new HashSet<String>();
1229                 while (true) {
1230                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1231                         if (friendId == null) {
1232                                 break;
1233                         }
1234                         friends.add(friendId);
1235                 }
1236
1237                 /* if we’re still here, Sone was loaded successfully. */
1238                 synchronized (sone) {
1239                         sone.setTime(soneTime);
1240                         sone.setProfile(profile);
1241                         sone.setPosts(posts);
1242                         sone.setReplies(replies);
1243                         sone.setLikePostIds(likedPostIds);
1244                         sone.setLikeReplyIds(likedReplyIds);
1245                         sone.setFriends(friends);
1246                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1247                 }
1248                 synchronized (newSones) {
1249                         for (String friend : friends) {
1250                                 knownSones.add(friend);
1251                         }
1252                 }
1253                 synchronized (newPosts) {
1254                         for (Post post : posts) {
1255                                 knownPosts.add(post.getId());
1256                         }
1257                 }
1258                 synchronized (newReplies) {
1259                         for (Reply reply : replies) {
1260                                 knownReplies.add(reply.getId());
1261                         }
1262                 }
1263         }
1264
1265         /**
1266          * Saves the given Sone. This will persist all local settings for the given
1267          * Sone, such as the friends list and similar, private options.
1268          *
1269          * @param sone
1270          *            The Sone to save
1271          */
1272         public synchronized void saveSone(Sone sone) {
1273                 if (!isLocalSone(sone)) {
1274                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1275                         return;
1276                 }
1277                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1278                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1279                         return;
1280                 }
1281
1282                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1283                 try {
1284                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1285
1286                         /* save Sone into configuration. */
1287                         String sonePrefix = "Sone/" + sone.getId();
1288                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1289                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1290
1291                         /* save profile. */
1292                         Profile profile = sone.getProfile();
1293                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1294                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1295                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1296                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1297                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1298                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1299
1300                         /* save profile fields. */
1301                         int fieldCounter = 0;
1302                         for (Field profileField : profile.getFields()) {
1303                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1304                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1305                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1306                         }
1307                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1308
1309                         /* save posts. */
1310                         int postCounter = 0;
1311                         for (Post post : sone.getPosts()) {
1312                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1313                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1314                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1315                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1316                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1317                         }
1318                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1319
1320                         /* save replies. */
1321                         int replyCounter = 0;
1322                         for (Reply reply : sone.getReplies()) {
1323                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1324                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1325                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1326                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1327                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1328                         }
1329                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1330
1331                         /* save post likes. */
1332                         int postLikeCounter = 0;
1333                         for (String postId : sone.getLikedPostIds()) {
1334                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1335                         }
1336                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1337
1338                         /* save reply likes. */
1339                         int replyLikeCounter = 0;
1340                         for (String replyId : sone.getLikedReplyIds()) {
1341                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1342                         }
1343                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1344
1345                         /* save friends. */
1346                         int friendCounter = 0;
1347                         for (String friendId : sone.getFriends()) {
1348                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1349                         }
1350                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1351
1352                         configuration.save();
1353                         logger.log(Level.INFO, "Sone %s saved.", sone);
1354                 } catch (ConfigurationException ce1) {
1355                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1356                 } catch (WebOfTrustException wote1) {
1357                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1358                 }
1359         }
1360
1361         /**
1362          * Creates a new post.
1363          *
1364          * @param sone
1365          *            The Sone that creates the post
1366          * @param text
1367          *            The text of the post
1368          * @return The created post
1369          */
1370         public Post createPost(Sone sone, String text) {
1371                 return createPost(sone, System.currentTimeMillis(), text);
1372         }
1373
1374         /**
1375          * Creates a new post.
1376          *
1377          * @param sone
1378          *            The Sone that creates the post
1379          * @param time
1380          *            The time of the post
1381          * @param text
1382          *            The text of the post
1383          * @return The created post
1384          */
1385         public Post createPost(Sone sone, long time, String text) {
1386                 return createPost(sone, null, time, text);
1387         }
1388
1389         /**
1390          * Creates a new post.
1391          *
1392          * @param sone
1393          *            The Sone that creates the post
1394          * @param recipient
1395          *            The recipient Sone, or {@code null} if this post does not have
1396          *            a recipient
1397          * @param text
1398          *            The text of the post
1399          * @return The created post
1400          */
1401         public Post createPost(Sone sone, Sone recipient, String text) {
1402                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1403         }
1404
1405         /**
1406          * Creates a new post.
1407          *
1408          * @param sone
1409          *            The Sone that creates the post
1410          * @param recipient
1411          *            The recipient Sone, or {@code null} if this post does not have
1412          *            a recipient
1413          * @param time
1414          *            The time of the post
1415          * @param text
1416          *            The text of the post
1417          * @return The created post
1418          */
1419         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1420                 if (!isLocalSone(sone)) {
1421                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1422                         return null;
1423                 }
1424                 Post post = new Post(sone, time, text);
1425                 if (recipient != null) {
1426                         post.setRecipient(recipient);
1427                 }
1428                 synchronized (posts) {
1429                         posts.put(post.getId(), post);
1430                 }
1431                 synchronized (newPosts) {
1432                         knownPosts.add(post.getId());
1433                 }
1434                 sone.addPost(post);
1435                 saveSone(sone);
1436                 return post;
1437         }
1438
1439         /**
1440          * Deletes the given post.
1441          *
1442          * @param post
1443          *            The post to delete
1444          */
1445         public void deletePost(Post post) {
1446                 if (!isLocalSone(post.getSone())) {
1447                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1448                         return;
1449                 }
1450                 post.getSone().removePost(post);
1451                 synchronized (posts) {
1452                         posts.remove(post.getId());
1453                 }
1454                 saveSone(post.getSone());
1455         }
1456
1457         /**
1458          * Marks the given post as known, if it is currently a new post (according
1459          * to {@link #isNewPost(String)}).
1460          *
1461          * @param post
1462          *            The post to mark as known
1463          */
1464         public void markPostKnown(Post post) {
1465                 synchronized (newPosts) {
1466                         if (newPosts.remove(post.getId())) {
1467                                 knownPosts.add(post.getId());
1468                                 coreListenerManager.fireMarkPostKnown(post);
1469                                 saveConfiguration();
1470                         }
1471                 }
1472         }
1473
1474         /**
1475          * Creates a new reply.
1476          *
1477          * @param sone
1478          *            The Sone that creates the reply
1479          * @param post
1480          *            The post that this reply refers to
1481          * @param text
1482          *            The text of the reply
1483          * @return The created reply
1484          */
1485         public Reply createReply(Sone sone, Post post, String text) {
1486                 return createReply(sone, post, System.currentTimeMillis(), text);
1487         }
1488
1489         /**
1490          * Creates a new reply.
1491          *
1492          * @param sone
1493          *            The Sone that creates the reply
1494          * @param post
1495          *            The post that this reply refers to
1496          * @param time
1497          *            The time of the reply
1498          * @param text
1499          *            The text of the reply
1500          * @return The created reply
1501          */
1502         public Reply createReply(Sone sone, Post post, long time, String text) {
1503                 if (!isLocalSone(sone)) {
1504                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1505                         return null;
1506                 }
1507                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1508                 synchronized (replies) {
1509                         replies.put(reply.getId(), reply);
1510                 }
1511                 synchronized (newReplies) {
1512                         knownReplies.add(reply.getId());
1513                 }
1514                 sone.addReply(reply);
1515                 saveSone(sone);
1516                 return reply;
1517         }
1518
1519         /**
1520          * Deletes the given reply.
1521          *
1522          * @param reply
1523          *            The reply to delete
1524          */
1525         public void deleteReply(Reply reply) {
1526                 Sone sone = reply.getSone();
1527                 if (!isLocalSone(sone)) {
1528                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1529                         return;
1530                 }
1531                 synchronized (replies) {
1532                         replies.remove(reply.getId());
1533                 }
1534                 sone.removeReply(reply);
1535                 saveSone(sone);
1536         }
1537
1538         /**
1539          * Marks the given reply as known, if it is currently a new reply (according
1540          * to {@link #isNewReply(String)}).
1541          *
1542          * @param reply
1543          *            The reply to mark as known
1544          */
1545         public void markReplyKnown(Reply reply) {
1546                 synchronized (newReplies) {
1547                         if (newReplies.remove(reply.getId())) {
1548                                 knownReplies.add(reply.getId());
1549                                 coreListenerManager.fireMarkReplyKnown(reply);
1550                                 saveConfiguration();
1551                         }
1552                 }
1553         }
1554
1555         /**
1556          * Starts the core.
1557          */
1558         public void start() {
1559                 loadConfiguration();
1560                 updateChecker.addUpdateListener(this);
1561                 updateChecker.start();
1562         }
1563
1564         /**
1565          * Stops the core.
1566          */
1567         public void stop() {
1568                 synchronized (localSones) {
1569                         for (SoneInserter soneInserter : soneInserters.values()) {
1570                                 soneInserter.stop();
1571                         }
1572                 }
1573                 updateChecker.stop();
1574                 updateChecker.removeUpdateListener(this);
1575                 soneDownloader.stop();
1576                 saveConfiguration();
1577                 stopped = true;
1578         }
1579
1580         /**
1581          * Saves the current options.
1582          */
1583         public void saveConfiguration() {
1584                 synchronized (configuration) {
1585                         if (storingConfiguration) {
1586                                 logger.log(Level.FINE, "Already storing configuration…");
1587                                 return;
1588                         }
1589                         storingConfiguration = true;
1590                 }
1591
1592                 /* store the options first. */
1593                 try {
1594                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1595                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1596                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1597                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1598                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1599                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1600                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1601                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1602
1603                         /* save known Sones. */
1604                         int soneCounter = 0;
1605                         synchronized (newSones) {
1606                                 for (String knownSoneId : knownSones) {
1607                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1608                                 }
1609                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1610                         }
1611
1612                         /* save known posts. */
1613                         int postCounter = 0;
1614                         synchronized (newPosts) {
1615                                 for (String knownPostId : knownPosts) {
1616                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1617                                 }
1618                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1619                         }
1620
1621                         /* save known replies. */
1622                         int replyCounter = 0;
1623                         synchronized (newReplies) {
1624                                 for (String knownReplyId : knownReplies) {
1625                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1626                                 }
1627                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1628                         }
1629
1630                         /* now save it. */
1631                         configuration.save();
1632
1633                 } catch (ConfigurationException ce1) {
1634                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1635                 } finally {
1636                         synchronized (configuration) {
1637                                 storingConfiguration = false;
1638                         }
1639                 }
1640         }
1641
1642         //
1643         // PRIVATE METHODS
1644         //
1645
1646         /**
1647          * Loads the configuration.
1648          */
1649         @SuppressWarnings("unchecked")
1650         private void loadConfiguration() {
1651                 /* create options. */
1652                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1653
1654                         @Override
1655                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1656                                 SoneInserter.setInsertionDelay(newValue);
1657                         }
1658
1659                 }));
1660                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1661                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
1662                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1663                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1664                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1665                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1666
1667                 /* read options from configuration. */
1668                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1669                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1670                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1671                 options.getBooleanOption("ClearOnNextRestart").set(null);
1672                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1673                 if (clearConfiguration) {
1674                         /* stop loading the configuration. */
1675                         return;
1676                 }
1677
1678                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1679                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1680                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1681                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1682                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1683
1684                 /* load known Sones. */
1685                 int soneCounter = 0;
1686                 while (true) {
1687                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1688                         if (knownSoneId == null) {
1689                                 break;
1690                         }
1691                         synchronized (newSones) {
1692                                 knownSones.add(knownSoneId);
1693                         }
1694                 }
1695
1696                 /* load known posts. */
1697                 int postCounter = 0;
1698                 while (true) {
1699                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1700                         if (knownPostId == null) {
1701                                 break;
1702                         }
1703                         synchronized (newPosts) {
1704                                 knownPosts.add(knownPostId);
1705                         }
1706                 }
1707
1708                 /* load known replies. */
1709                 int replyCounter = 0;
1710                 while (true) {
1711                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1712                         if (knownReplyId == null) {
1713                                 break;
1714                         }
1715                         synchronized (newReplies) {
1716                                 knownReplies.add(knownReplyId);
1717                         }
1718                 }
1719
1720         }
1721
1722         /**
1723          * Generate a Sone URI from the given URI and latest edition.
1724          *
1725          * @param uriString
1726          *            The URI to derive the Sone URI from
1727          * @return The derived URI
1728          */
1729         private FreenetURI getSoneUri(String uriString) {
1730                 try {
1731                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1732                         return uri;
1733                 } catch (MalformedURLException mue1) {
1734                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1735                         return null;
1736                 }
1737         }
1738
1739         //
1740         // INTERFACE IdentityListener
1741         //
1742
1743         /**
1744          * {@inheritDoc}
1745          */
1746         @Override
1747         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1748                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1749                 if (ownIdentity.hasContext("Sone")) {
1750                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1751                         addLocalSone(ownIdentity);
1752                 }
1753         }
1754
1755         /**
1756          * {@inheritDoc}
1757          */
1758         @Override
1759         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1760                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1761                 trustedIdentities.remove(ownIdentity);
1762         }
1763
1764         /**
1765          * {@inheritDoc}
1766          */
1767         @Override
1768         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1769                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1770                 trustedIdentities.get(ownIdentity).add(identity);
1771                 addRemoteSone(identity);
1772         }
1773
1774         /**
1775          * {@inheritDoc}
1776          */
1777         @Override
1778         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1779                 new Thread(new Runnable() {
1780
1781                         @Override
1782                         @SuppressWarnings("synthetic-access")
1783                         public void run() {
1784                                 Sone sone = getRemoteSone(identity.getId());
1785                                 sone.setIdentity(identity);
1786                                 soneDownloader.fetchSone(sone);
1787                         }
1788                 }).start();
1789         }
1790
1791         /**
1792          * {@inheritDoc}
1793          */
1794         @Override
1795         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1796                 trustedIdentities.get(ownIdentity).remove(identity);
1797         }
1798
1799         //
1800         // INTERFACE UpdateListener
1801         //
1802
1803         /**
1804          * {@inheritDoc}
1805          */
1806         @Override
1807         public void updateFound(Version version, long releaseTime) {
1808                 coreListenerManager.fireUpdateFound(version, releaseTime);
1809         }
1810
1811 }