Add context menues when hovering over avatar images.
[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.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Client;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Profile.Field;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.fcp.FcpInterface;
44 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.IdentityListener;
47 import net.pterodactylus.sone.freenet.wot.IdentityManager;
48 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
49 import net.pterodactylus.sone.freenet.wot.Trust;
50 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
51 import net.pterodactylus.sone.main.SonePlugin;
52 import net.pterodactylus.util.collection.Pair;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
55 import net.pterodactylus.util.logging.Logging;
56 import net.pterodactylus.util.number.Numbers;
57 import net.pterodactylus.util.thread.Ticker;
58 import net.pterodactylus.util.validation.EqualityValidator;
59 import net.pterodactylus.util.validation.IntegerRangeValidator;
60 import net.pterodactylus.util.validation.OrValidator;
61 import net.pterodactylus.util.validation.Validation;
62 import net.pterodactylus.util.version.Version;
63 import freenet.client.FetchResult;
64 import freenet.keys.FreenetURI;
65
66 /**
67  * The Sone core.
68  *
69  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70  */
71 public class Core implements IdentityListener, UpdateListener, SoneProvider, PostProvider {
72
73         /**
74          * Enumeration for the possible states of a {@link Sone}.
75          *
76          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77          */
78         public enum SoneStatus {
79
80                 /** The Sone is unknown, i.e. not yet downloaded. */
81                 unknown,
82
83                 /** The Sone is idle, i.e. not being downloaded or inserted. */
84                 idle,
85
86                 /** The Sone is currently being inserted. */
87                 inserting,
88
89                 /** The Sone is currently being downloaded. */
90                 downloading,
91         }
92
93         /** The logger. */
94         private static final Logger logger = Logging.getLogger(Core.class);
95
96         /** The options. */
97         private final Options options = new Options();
98
99         /** The preferences. */
100         private final Preferences preferences = new Preferences(options);
101
102         /** The core listener manager. */
103         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
104
105         /** The configuration. */
106         private Configuration configuration;
107
108         /** Whether we’re currently saving the configuration. */
109         private boolean storingConfiguration = false;
110
111         /** The identity manager. */
112         private final IdentityManager identityManager;
113
114         /** Interface to freenet. */
115         private final FreenetInterface freenetInterface;
116
117         /** The Sone downloader. */
118         private final SoneDownloader soneDownloader;
119
120         /** Sone downloader thread-pool. */
121         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
122
123         /** The update checker. */
124         private final UpdateChecker updateChecker;
125
126         /** The FCP interface. */
127         private volatile FcpInterface fcpInterface;
128
129         /** Whether the core has been stopped. */
130         private volatile boolean stopped;
131
132         /** The Sones’ statuses. */
133         /* synchronize access on itself. */
134         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
135
136         /** Locked local Sones. */
137         /* synchronize on itself. */
138         private final Set<Sone> lockedSones = new HashSet<Sone>();
139
140         /** Sone inserters. */
141         /* synchronize access on this on localSones. */
142         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
143
144         /** All local Sones. */
145         /* synchronize access on this on itself. */
146         private Map<String, Sone> localSones = new HashMap<String, Sone>();
147
148         /** All remote Sones. */
149         /* synchronize access on this on itself. */
150         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
151
152         /** All new Sones. */
153         private Set<String> newSones = new HashSet<String>();
154
155         /** All known Sones. */
156         /* synchronize access on {@link #newSones}. */
157         private Set<String> knownSones = new HashSet<String>();
158
159         /** All posts. */
160         private Map<String, Post> posts = new HashMap<String, Post>();
161
162         /** All new posts. */
163         private Set<String> newPosts = new HashSet<String>();
164
165         /** All known posts. */
166         /* synchronize access on {@link #newPosts}. */
167         private Set<String> knownPosts = new HashSet<String>();
168
169         /** All replies. */
170         private Map<String, Reply> replies = new HashMap<String, Reply>();
171
172         /** All new replies. */
173         private Set<String> newReplies = new HashSet<String>();
174
175         /** All known replies. */
176         private Set<String> knownReplies = new HashSet<String>();
177
178         /** All bookmarked posts. */
179         /* synchronize access on itself. */
180         private Set<String> bookmarkedPosts = new HashSet<String>();
181
182         /** Trusted identities, sorted by own identities. */
183         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
184
185         /** Ticker for threads that mark own elements as known. */
186         private Ticker localElementTicker = new Ticker();
187
188         /**
189          * Creates a new core.
190          *
191          * @param configuration
192          *            The configuration of the core
193          * @param freenetInterface
194          *            The freenet interface
195          * @param identityManager
196          *            The identity manager
197          */
198         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
199                 this.configuration = configuration;
200                 this.freenetInterface = freenetInterface;
201                 this.identityManager = identityManager;
202                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
203                 this.updateChecker = new UpdateChecker(freenetInterface);
204         }
205
206         //
207         // LISTENER MANAGEMENT
208         //
209
210         /**
211          * Adds a new core listener.
212          *
213          * @param coreListener
214          *            The listener to add
215          */
216         public void addCoreListener(CoreListener coreListener) {
217                 coreListenerManager.addListener(coreListener);
218         }
219
220         /**
221          * Removes a core listener.
222          *
223          * @param coreListener
224          *            The listener to remove
225          */
226         public void removeCoreListener(CoreListener coreListener) {
227                 coreListenerManager.removeListener(coreListener);
228         }
229
230         //
231         // ACCESSORS
232         //
233
234         /**
235          * Sets the configuration to use. This will automatically save the current
236          * configuration to the given configuration.
237          *
238          * @param configuration
239          *            The new configuration to use
240          */
241         public void setConfiguration(Configuration configuration) {
242                 this.configuration = configuration;
243                 saveConfiguration();
244         }
245
246         /**
247          * Returns the options used by the core.
248          *
249          * @return The options of the core
250          */
251         public Preferences getPreferences() {
252                 return preferences;
253         }
254
255         /**
256          * Returns the identity manager used by the core.
257          *
258          * @return The identity manager
259          */
260         public IdentityManager getIdentityManager() {
261                 return identityManager;
262         }
263
264         /**
265          * Returns the update checker.
266          *
267          * @return The update checker
268          */
269         public UpdateChecker getUpdateChecker() {
270                 return updateChecker;
271         }
272
273         /**
274          * Sets the FCP interface to use.
275          *
276          * @param fcpInterface
277          *            The FCP interface to use
278          */
279         public void setFcpInterface(FcpInterface fcpInterface) {
280                 this.fcpInterface = fcpInterface;
281         }
282
283         /**
284          * Returns the status of the given Sone.
285          *
286          * @param sone
287          *            The Sone to get the status for
288          * @return The status of the Sone
289          */
290         public SoneStatus getSoneStatus(Sone sone) {
291                 synchronized (soneStatuses) {
292                         return soneStatuses.get(sone);
293                 }
294         }
295
296         /**
297          * Sets the status of the given Sone.
298          *
299          * @param sone
300          *            The Sone to set the status of
301          * @param soneStatus
302          *            The status to set
303          */
304         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
305                 synchronized (soneStatuses) {
306                         soneStatuses.put(sone, soneStatus);
307                 }
308         }
309
310         /**
311          * Returns whether the given Sone is currently locked.
312          *
313          * @param sone
314          *            The sone to check
315          * @return {@code true} if the Sone is locked, {@code false} if it is not
316          */
317         public boolean isLocked(Sone sone) {
318                 synchronized (lockedSones) {
319                         return lockedSones.contains(sone);
320                 }
321         }
322
323         /**
324          * Returns all Sones, remote and local.
325          *
326          * @return All Sones
327          */
328         public Set<Sone> getSones() {
329                 Set<Sone> allSones = new HashSet<Sone>();
330                 allSones.addAll(getLocalSones());
331                 allSones.addAll(getRemoteSones());
332                 return allSones;
333         }
334
335         /**
336          * Returns the Sone with the given ID, regardless whether it’s local or
337          * remote.
338          *
339          * @param id
340          *            The ID of the Sone to get
341          * @return The Sone with the given ID, or {@code null} if there is no such
342          *         Sone
343          */
344         public Sone getSone(String id) {
345                 return getSone(id, true);
346         }
347
348         /**
349          * Returns the Sone with the given ID, regardless whether it’s local or
350          * remote.
351          *
352          * @param id
353          *            The ID of the Sone to get
354          * @param create
355          *            {@code true} to create a new Sone if none exists,
356          *            {@code false} to return {@code null} if a Sone with the given
357          *            ID does not exist
358          * @return The Sone with the given ID, or {@code null} if there is no such
359          *         Sone
360          */
361         @Override
362         public Sone getSone(String id, boolean create) {
363                 if (isLocalSone(id)) {
364                         return getLocalSone(id);
365                 }
366                 return getRemoteSone(id, create);
367         }
368
369         /**
370          * Checks whether the core knows a Sone with the given ID.
371          *
372          * @param id
373          *            The ID of the Sone
374          * @return {@code true} if there is a Sone with the given ID, {@code false}
375          *         otherwise
376          */
377         public boolean hasSone(String id) {
378                 return isLocalSone(id) || isRemoteSone(id);
379         }
380
381         /**
382          * Returns whether the given Sone is a local Sone.
383          *
384          * @param sone
385          *            The Sone to check for its locality
386          * @return {@code true} if the given Sone is local, {@code false} otherwise
387          */
388         public boolean isLocalSone(Sone sone) {
389                 synchronized (localSones) {
390                         return localSones.containsKey(sone.getId());
391                 }
392         }
393
394         /**
395          * Returns whether the given ID is the ID of a local Sone.
396          *
397          * @param id
398          *            The Sone ID to check for its locality
399          * @return {@code true} if the given ID is a local Sone, {@code false}
400          *         otherwise
401          */
402         public boolean isLocalSone(String id) {
403                 synchronized (localSones) {
404                         return localSones.containsKey(id);
405                 }
406         }
407
408         /**
409          * Returns all local Sones.
410          *
411          * @return All local Sones
412          */
413         public Set<Sone> getLocalSones() {
414                 synchronized (localSones) {
415                         return new HashSet<Sone>(localSones.values());
416                 }
417         }
418
419         /**
420          * Returns the local Sone with the given ID.
421          *
422          * @param id
423          *            The ID of the Sone to get
424          * @return The Sone with the given ID
425          */
426         public Sone getLocalSone(String id) {
427                 return getLocalSone(id, true);
428         }
429
430         /**
431          * Returns the local Sone with the given ID, optionally creating a new Sone.
432          *
433          * @param id
434          *            The ID of the Sone
435          * @param create
436          *            {@code true} to create a new Sone if none exists,
437          *            {@code false} to return null if none exists
438          * @return The Sone with the given ID, or {@code null}
439          */
440         public Sone getLocalSone(String id, boolean create) {
441                 synchronized (localSones) {
442                         Sone sone = localSones.get(id);
443                         if ((sone == null) && create) {
444                                 sone = new Sone(id);
445                                 localSones.put(id, sone);
446                                 setSoneStatus(sone, SoneStatus.unknown);
447                         }
448                         return sone;
449                 }
450         }
451
452         /**
453          * Returns all remote Sones.
454          *
455          * @return All remote Sones
456          */
457         public Set<Sone> getRemoteSones() {
458                 synchronized (remoteSones) {
459                         return new HashSet<Sone>(remoteSones.values());
460                 }
461         }
462
463         /**
464          * Returns the remote Sone with the given ID.
465          *
466          * @param id
467          *            The ID of the remote Sone to get
468          * @return The Sone with the given ID
469          */
470         public Sone getRemoteSone(String id) {
471                 return getRemoteSone(id, true);
472         }
473
474         /**
475          * Returns the remote Sone with the given ID.
476          *
477          * @param id
478          *            The ID of the remote Sone to get
479          * @param create
480          *            {@code true} to always create a Sone, {@code false} to return
481          *            {@code null} if no Sone with the given ID exists
482          * @return The Sone with the given ID
483          */
484         public Sone getRemoteSone(String id, boolean create) {
485                 synchronized (remoteSones) {
486                         Sone sone = remoteSones.get(id);
487                         if ((sone == null) && create) {
488                                 sone = new Sone(id);
489                                 remoteSones.put(id, sone);
490                                 setSoneStatus(sone, SoneStatus.unknown);
491                         }
492                         return sone;
493                 }
494         }
495
496         /**
497          * Returns whether the given Sone is a remote Sone.
498          *
499          * @param sone
500          *            The Sone to check
501          * @return {@code true} if the given Sone is a remote Sone, {@code false}
502          *         otherwise
503          */
504         public boolean isRemoteSone(Sone sone) {
505                 synchronized (remoteSones) {
506                         return remoteSones.containsKey(sone.getId());
507                 }
508         }
509
510         /**
511          * Returns whether the Sone with the given ID is a remote Sone.
512          *
513          * @param id
514          *            The ID of the Sone to check
515          * @return {@code true} if the Sone with the given ID is a remote Sone,
516          *         {@code false} otherwise
517          */
518         public boolean isRemoteSone(String id) {
519                 synchronized (remoteSones) {
520                         return remoteSones.containsKey(id);
521                 }
522         }
523
524         /**
525          * Returns whether the Sone with the given ID is a new Sone.
526          *
527          * @param soneId
528          *            The ID of the sone to check for
529          * @return {@code true} if the given Sone is new, false otherwise
530          */
531         public boolean isNewSone(String soneId) {
532                 synchronized (newSones) {
533                         return !knownSones.contains(soneId) && newSones.contains(soneId);
534                 }
535         }
536
537         /**
538          * Returns whether the given Sone has been modified.
539          *
540          * @param sone
541          *            The Sone to check for modifications
542          * @return {@code true} if a modification has been detected in the Sone,
543          *         {@code false} otherwise
544          */
545         public boolean isModifiedSone(Sone sone) {
546                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
547         }
548
549         /**
550          * Returns whether the target Sone is trusted by the origin Sone.
551          *
552          * @param origin
553          *            The origin Sone
554          * @param target
555          *            The target Sone
556          * @return {@code true} if the target Sone is trusted by the origin Sone
557          */
558         public boolean isSoneTrusted(Sone origin, Sone target) {
559                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
560                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
561         }
562
563         /**
564          * Returns the post with the given ID.
565          *
566          * @param postId
567          *            The ID of the post to get
568          * @return The post with the given ID, or a new post with the given ID
569          */
570         public Post getPost(String postId) {
571                 return getPost(postId, true);
572         }
573
574         /**
575          * Returns the post with the given ID, optionally creating a new post.
576          *
577          * @param postId
578          *            The ID of the post to get
579          * @param create
580          *            {@code true} it create a new post if no post with the given ID
581          *            exists, {@code false} to return {@code null}
582          * @return The post, or {@code null} if there is no such post
583          */
584         @Override
585         public Post getPost(String postId, boolean create) {
586                 synchronized (posts) {
587                         Post post = posts.get(postId);
588                         if ((post == null) && create) {
589                                 post = new Post(postId);
590                                 posts.put(postId, post);
591                         }
592                         return post;
593                 }
594         }
595
596         /**
597          * Returns whether the given post ID is new.
598          *
599          * @param postId
600          *            The post ID
601          * @return {@code true} if the post is considered to be new, {@code false}
602          *         otherwise
603          */
604         public boolean isNewPost(String postId) {
605                 synchronized (newPosts) {
606                         return !knownPosts.contains(postId) && newPosts.contains(postId);
607                 }
608         }
609
610         /**
611          * Returns all posts that have the given Sone as recipient.
612          *
613          * @see Post#getRecipient()
614          * @param recipient
615          *            The recipient of the posts
616          * @return All posts that have the given Sone as recipient
617          */
618         public Set<Post> getDirectedPosts(Sone recipient) {
619                 Validation.begin().isNotNull("Recipient", recipient).check();
620                 Set<Post> directedPosts = new HashSet<Post>();
621                 synchronized (posts) {
622                         for (Post post : posts.values()) {
623                                 if (recipient.equals(post.getRecipient())) {
624                                         directedPosts.add(post);
625                                 }
626                         }
627                 }
628                 return directedPosts;
629         }
630
631         /**
632          * Returns the reply with the given ID. If there is no reply with the given
633          * ID yet, a new one is created.
634          *
635          * @param replyId
636          *            The ID of the reply to get
637          * @return The reply
638          */
639         public Reply getReply(String replyId) {
640                 return getReply(replyId, true);
641         }
642
643         /**
644          * Returns the reply with the given ID. If there is no reply with the given
645          * ID yet, a new one is created, unless {@code create} is false in which
646          * case {@code null} is returned.
647          *
648          * @param replyId
649          *            The ID of the reply to get
650          * @param create
651          *            {@code true} to always return a {@link Reply}, {@code false}
652          *            to return {@code null} if no reply can be found
653          * @return The reply, or {@code null} if there is no such reply
654          */
655         public Reply getReply(String replyId, boolean create) {
656                 synchronized (replies) {
657                         Reply reply = replies.get(replyId);
658                         if (create && (reply == null)) {
659                                 reply = new Reply(replyId);
660                                 replies.put(replyId, reply);
661                         }
662                         return reply;
663                 }
664         }
665
666         /**
667          * Returns all replies for the given post, order ascending by time.
668          *
669          * @param post
670          *            The post to get all replies for
671          * @return All replies for the given post
672          */
673         public List<Reply> getReplies(Post post) {
674                 Set<Sone> sones = getSones();
675                 List<Reply> replies = new ArrayList<Reply>();
676                 for (Sone sone : sones) {
677                         for (Reply reply : sone.getReplies()) {
678                                 if (reply.getPost().equals(post)) {
679                                         replies.add(reply);
680                                 }
681                         }
682                 }
683                 Collections.sort(replies, Reply.TIME_COMPARATOR);
684                 return replies;
685         }
686
687         /**
688          * Returns whether the reply with the given ID is new.
689          *
690          * @param replyId
691          *            The ID of the reply to check
692          * @return {@code true} if the reply is considered to be new, {@code false}
693          *         otherwise
694          */
695         public boolean isNewReply(String replyId) {
696                 synchronized (newReplies) {
697                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
698                 }
699         }
700
701         /**
702          * Returns all Sones that have liked the given post.
703          *
704          * @param post
705          *            The post to get the liking Sones for
706          * @return The Sones that like the given post
707          */
708         public Set<Sone> getLikes(Post post) {
709                 Set<Sone> sones = new HashSet<Sone>();
710                 for (Sone sone : getSones()) {
711                         if (sone.getLikedPostIds().contains(post.getId())) {
712                                 sones.add(sone);
713                         }
714                 }
715                 return sones;
716         }
717
718         /**
719          * Returns all Sones that have liked the given reply.
720          *
721          * @param reply
722          *            The reply to get the liking Sones for
723          * @return The Sones that like the given reply
724          */
725         public Set<Sone> getLikes(Reply reply) {
726                 Set<Sone> sones = new HashSet<Sone>();
727                 for (Sone sone : getSones()) {
728                         if (sone.getLikedReplyIds().contains(reply.getId())) {
729                                 sones.add(sone);
730                         }
731                 }
732                 return sones;
733         }
734
735         /**
736          * Returns whether the given post is bookmarked.
737          *
738          * @param post
739          *            The post to check
740          * @return {@code true} if the given post is bookmarked, {@code false}
741          *         otherwise
742          */
743         public boolean isBookmarked(Post post) {
744                 return isPostBookmarked(post.getId());
745         }
746
747         /**
748          * Returns whether the post with the given ID is bookmarked.
749          *
750          * @param id
751          *            The ID of the post to check
752          * @return {@code true} if the post with the given ID is bookmarked,
753          *         {@code false} otherwise
754          */
755         public boolean isPostBookmarked(String id) {
756                 synchronized (bookmarkedPosts) {
757                         return bookmarkedPosts.contains(id);
758                 }
759         }
760
761         /**
762          * Returns all currently known bookmarked posts.
763          *
764          * @return All bookmarked posts
765          */
766         public Set<Post> getBookmarkedPosts() {
767                 Set<Post> posts = new HashSet<Post>();
768                 synchronized (bookmarkedPosts) {
769                         for (String bookmarkedPostId : bookmarkedPosts) {
770                                 Post post = getPost(bookmarkedPostId, false);
771                                 if (post != null) {
772                                         posts.add(post);
773                                 }
774                         }
775                 }
776                 return posts;
777         }
778
779         //
780         // ACTIONS
781         //
782
783         /**
784          * Locks the given Sone. A locked Sone will not be inserted by
785          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
786          * again.
787          *
788          * @param sone
789          *            The sone to lock
790          */
791         public void lockSone(Sone sone) {
792                 synchronized (lockedSones) {
793                         if (lockedSones.add(sone)) {
794                                 coreListenerManager.fireSoneLocked(sone);
795                         }
796                 }
797         }
798
799         /**
800          * Unlocks the given Sone.
801          *
802          * @see #lockSone(Sone)
803          * @param sone
804          *            The sone to unlock
805          */
806         public void unlockSone(Sone sone) {
807                 synchronized (lockedSones) {
808                         if (lockedSones.remove(sone)) {
809                                 coreListenerManager.fireSoneUnlocked(sone);
810                         }
811                 }
812         }
813
814         /**
815          * Adds a local Sone from the given ID which has to be the ID of an own
816          * identity.
817          *
818          * @param id
819          *            The ID of an own identity to add a Sone for
820          * @return The added (or already existing) Sone
821          */
822         public Sone addLocalSone(String id) {
823                 synchronized (localSones) {
824                         if (localSones.containsKey(id)) {
825                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
826                                 return localSones.get(id);
827                         }
828                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
829                         if (ownIdentity == null) {
830                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
831                                 return null;
832                         }
833                         return addLocalSone(ownIdentity);
834                 }
835         }
836
837         /**
838          * Adds a local Sone from the given own identity.
839          *
840          * @param ownIdentity
841          *            The own identity to create a Sone from
842          * @return The added (or already existing) Sone
843          */
844         public Sone addLocalSone(OwnIdentity ownIdentity) {
845                 if (ownIdentity == null) {
846                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
847                         return null;
848                 }
849                 synchronized (localSones) {
850                         final Sone sone;
851                         try {
852                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
853                         } catch (MalformedURLException mue1) {
854                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
855                                 return null;
856                         }
857                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
858                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
859                         /* TODO - load posts ’n stuff */
860                         localSones.put(ownIdentity.getId(), sone);
861                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
862                         soneInserters.put(sone, soneInserter);
863                         setSoneStatus(sone, SoneStatus.idle);
864                         loadSone(sone);
865                         if (!preferences.isSoneRescueMode()) {
866                                 soneInserter.start();
867                         }
868                         new Thread(new Runnable() {
869
870                                 @Override
871                                 @SuppressWarnings("synthetic-access")
872                                 public void run() {
873                                         if (!preferences.isSoneRescueMode()) {
874                                                 return;
875                                         }
876                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
877                                         coreListenerManager.fireRescuingSone(sone);
878                                         lockSone(sone);
879                                         long edition = sone.getLatestEdition();
880                                         /* find the latest edition the node knows about. */
881                                         Pair<FreenetURI, FetchResult> currentUri = freenetInterface.fetchUri(sone.getRequestUri());
882                                         if (currentUri != null) {
883                                                 long currentEdition = currentUri.getLeft().getEdition();
884                                                 if (currentEdition > edition) {
885                                                         edition = currentEdition;
886                                                 }
887                                         }
888                                         while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
889                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
890                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
891                                                 --edition;
892                                         }
893                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
894                                         saveSone(sone);
895                                         coreListenerManager.fireRescuedSone(sone);
896                                         soneInserter.start();
897                                 }
898
899                         }, "Sone Downloader").start();
900                         return sone;
901                 }
902         }
903
904         /**
905          * Creates a new Sone for the given own identity.
906          *
907          * @param ownIdentity
908          *            The own identity to create a Sone for
909          * @return The created Sone
910          */
911         public Sone createSone(OwnIdentity ownIdentity) {
912                 try {
913                         ownIdentity.addContext("Sone");
914                 } catch (WebOfTrustException wote1) {
915                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
916                         return null;
917                 }
918                 Sone sone = addLocalSone(ownIdentity);
919                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
920                 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
921                 saveSone(sone);
922                 return sone;
923         }
924
925         /**
926          * Adds the Sone of the given identity.
927          *
928          * @param identity
929          *            The identity whose Sone to add
930          * @return The added or already existing Sone
931          */
932         public Sone addRemoteSone(Identity identity) {
933                 if (identity == null) {
934                         logger.log(Level.WARNING, "Given Identity is null!");
935                         return null;
936                 }
937                 synchronized (remoteSones) {
938                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
939                         boolean newSone = sone.getRequestUri() == null;
940                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
941                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
942                         if (newSone) {
943                                 synchronized (newSones) {
944                                         newSone = !knownSones.contains(sone.getId());
945                                         if (newSone) {
946                                                 newSones.add(sone.getId());
947                                         }
948                                 }
949                                 if (newSone) {
950                                         coreListenerManager.fireNewSoneFound(sone);
951                                         for (Sone localSone : getLocalSones()) {
952                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
953                                                         localSone.addFriend(sone.getId());
954                                                         saveSone(localSone);
955                                                 }
956                                         }
957                                 }
958                         }
959                         remoteSones.put(identity.getId(), sone);
960                         soneDownloader.addSone(sone);
961                         setSoneStatus(sone, SoneStatus.unknown);
962                         soneDownloaders.execute(new Runnable() {
963
964                                 @Override
965                                 @SuppressWarnings("synthetic-access")
966                                 public void run() {
967                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
968                                 }
969
970                         });
971                         return sone;
972                 }
973         }
974
975         /**
976          * Retrieves the trust relationship from the origin to the target. If the
977          * trust relationship can not be retrieved, {@code null} is returned.
978          *
979          * @see Identity#getTrust(OwnIdentity)
980          * @param origin
981          *            The origin of the trust tree
982          * @param target
983          *            The target of the trust
984          * @return The trust relationship
985          */
986         public Trust getTrust(Sone origin, Sone target) {
987                 if (!isLocalSone(origin)) {
988                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
989                         return null;
990                 }
991                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
992         }
993
994         /**
995          * Sets the trust value of the given origin Sone for the target Sone.
996          *
997          * @param origin
998          *            The origin Sone
999          * @param target
1000          *            The target Sone
1001          * @param trustValue
1002          *            The trust value (from {@code -100} to {@code 100})
1003          */
1004         public void setTrust(Sone origin, Sone target, int trustValue) {
1005                 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();
1006                 try {
1007                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1008                 } catch (WebOfTrustException wote1) {
1009                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1010                 }
1011         }
1012
1013         /**
1014          * Removes any trust assignment for the given target Sone.
1015          *
1016          * @param origin
1017          *            The trust origin
1018          * @param target
1019          *            The trust target
1020          */
1021         public void removeTrust(Sone origin, Sone target) {
1022                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1023                 try {
1024                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1025                 } catch (WebOfTrustException wote1) {
1026                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1027                 }
1028         }
1029
1030         /**
1031          * Assigns the configured positive trust value for the given target.
1032          *
1033          * @param origin
1034          *            The trust origin
1035          * @param target
1036          *            The trust target
1037          */
1038         public void trustSone(Sone origin, Sone target) {
1039                 setTrust(origin, target, preferences.getPositiveTrust());
1040         }
1041
1042         /**
1043          * Assigns the configured negative trust value for the given target.
1044          *
1045          * @param origin
1046          *            The trust origin
1047          * @param target
1048          *            The trust target
1049          */
1050         public void distrustSone(Sone origin, Sone target) {
1051                 setTrust(origin, target, preferences.getNegativeTrust());
1052         }
1053
1054         /**
1055          * Removes the trust assignment for the given target.
1056          *
1057          * @param origin
1058          *            The trust origin
1059          * @param target
1060          *            The trust target
1061          */
1062         public void untrustSone(Sone origin, Sone target) {
1063                 removeTrust(origin, target);
1064         }
1065
1066         /**
1067          * Updates the stores Sone with the given Sone.
1068          *
1069          * @param sone
1070          *            The updated Sone
1071          */
1072         public void updateSone(Sone sone) {
1073                 if (hasSone(sone.getId())) {
1074                         boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1075                         Sone storedSone = getSone(sone.getId());
1076                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1077                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1078                                 return;
1079                         }
1080                         synchronized (posts) {
1081                                 if (!soneRescueMode) {
1082                                         for (Post post : storedSone.getPosts()) {
1083                                                 posts.remove(post.getId());
1084                                                 if (!sone.getPosts().contains(post)) {
1085                                                         coreListenerManager.firePostRemoved(post);
1086                                                 }
1087                                         }
1088                                 }
1089                                 List<Post> storedPosts = storedSone.getPosts();
1090                                 synchronized (newPosts) {
1091                                         for (Post post : sone.getPosts()) {
1092                                                 post.setSone(storedSone);
1093                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1094                                                         newPosts.add(post.getId());
1095                                                         coreListenerManager.fireNewPostFound(post);
1096                                                 }
1097                                                 posts.put(post.getId(), post);
1098                                         }
1099                                 }
1100                         }
1101                         synchronized (replies) {
1102                                 if (!soneRescueMode) {
1103                                         for (Reply reply : storedSone.getReplies()) {
1104                                                 replies.remove(reply.getId());
1105                                                 if (!sone.getReplies().contains(reply)) {
1106                                                         coreListenerManager.fireReplyRemoved(reply);
1107                                                 }
1108                                         }
1109                                 }
1110                                 Set<Reply> storedReplies = storedSone.getReplies();
1111                                 synchronized (newReplies) {
1112                                         for (Reply reply : sone.getReplies()) {
1113                                                 reply.setSone(storedSone);
1114                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1115                                                         newReplies.add(reply.getId());
1116                                                         coreListenerManager.fireNewReplyFound(reply);
1117                                                 }
1118                                                 replies.put(reply.getId(), reply);
1119                                         }
1120                                 }
1121                         }
1122                         synchronized (storedSone) {
1123                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1124                                         storedSone.setTime(sone.getTime());
1125                                 }
1126                                 storedSone.setClient(sone.getClient());
1127                                 storedSone.setProfile(sone.getProfile());
1128                                 if (soneRescueMode) {
1129                                         for (Post post : sone.getPosts()) {
1130                                                 storedSone.addPost(post);
1131                                         }
1132                                         for (Reply reply : sone.getReplies()) {
1133                                                 storedSone.addReply(reply);
1134                                         }
1135                                         for (String likedPostId : sone.getLikedPostIds()) {
1136                                                 storedSone.addLikedPostId(likedPostId);
1137                                         }
1138                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1139                                                 storedSone.addLikedReplyId(likedReplyId);
1140                                         }
1141                                 } else {
1142                                         storedSone.setPosts(sone.getPosts());
1143                                         storedSone.setReplies(sone.getReplies());
1144                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1145                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1146                                 }
1147                                 storedSone.setLatestEdition(sone.getLatestEdition());
1148                         }
1149                 }
1150         }
1151
1152         /**
1153          * Deletes the given Sone. This will remove the Sone from the
1154          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1155          * and remove the context from its identity.
1156          *
1157          * @param sone
1158          *            The Sone to delete
1159          */
1160         public void deleteSone(Sone sone) {
1161                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1162                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1163                         return;
1164                 }
1165                 synchronized (localSones) {
1166                         if (!localSones.containsKey(sone.getId())) {
1167                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1168                                 return;
1169                         }
1170                         localSones.remove(sone.getId());
1171                         soneInserters.remove(sone).stop();
1172                 }
1173                 try {
1174                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1175                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1176                 } catch (WebOfTrustException wote1) {
1177                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1178                 }
1179                 try {
1180                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1181                 } catch (ConfigurationException ce1) {
1182                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1183                 }
1184         }
1185
1186         /**
1187          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1188          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1189          *
1190          * @param sone
1191          *            The Sone to mark as known
1192          */
1193         public void markSoneKnown(Sone sone) {
1194                 synchronized (newSones) {
1195                         if (newSones.remove(sone.getId())) {
1196                                 knownSones.add(sone.getId());
1197                                 coreListenerManager.fireMarkSoneKnown(sone);
1198                                 saveConfiguration();
1199                         }
1200                 }
1201         }
1202
1203         /**
1204          * Loads and updates the given Sone from the configuration. If any error is
1205          * encountered, loading is aborted and the given Sone is not changed.
1206          *
1207          * @param sone
1208          *            The Sone to load and update
1209          */
1210         public void loadSone(Sone sone) {
1211                 if (!isLocalSone(sone)) {
1212                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1213                         return;
1214                 }
1215
1216                 /* initialize options. */
1217                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1218
1219                 /* load Sone. */
1220                 String sonePrefix = "Sone/" + sone.getId();
1221                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1222                 if (soneTime == null) {
1223                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1224                         return;
1225                 }
1226                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1227
1228                 /* load profile. */
1229                 Profile profile = new Profile();
1230                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1231                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1232                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1233                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1234                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1235                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1236
1237                 /* load profile fields. */
1238                 while (true) {
1239                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1240                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1241                         if (fieldName == null) {
1242                                 break;
1243                         }
1244                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1245                         profile.addField(fieldName).setValue(fieldValue);
1246                 }
1247
1248                 /* load posts. */
1249                 Set<Post> posts = new HashSet<Post>();
1250                 while (true) {
1251                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1252                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1253                         if (postId == null) {
1254                                 break;
1255                         }
1256                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1257                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1258                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1259                         if ((postTime == 0) || (postText == null)) {
1260                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1261                                 return;
1262                         }
1263                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1264                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1265                                 post.setRecipient(getSone(postRecipientId));
1266                         }
1267                         posts.add(post);
1268                 }
1269
1270                 /* load replies. */
1271                 Set<Reply> replies = new HashSet<Reply>();
1272                 while (true) {
1273                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1274                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1275                         if (replyId == null) {
1276                                 break;
1277                         }
1278                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1279                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1280                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1281                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1282                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1283                                 return;
1284                         }
1285                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1286                 }
1287
1288                 /* load post likes. */
1289                 Set<String> likedPostIds = new HashSet<String>();
1290                 while (true) {
1291                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1292                         if (likedPostId == null) {
1293                                 break;
1294                         }
1295                         likedPostIds.add(likedPostId);
1296                 }
1297
1298                 /* load reply likes. */
1299                 Set<String> likedReplyIds = new HashSet<String>();
1300                 while (true) {
1301                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1302                         if (likedReplyId == null) {
1303                                 break;
1304                         }
1305                         likedReplyIds.add(likedReplyId);
1306                 }
1307
1308                 /* load friends. */
1309                 Set<String> friends = new HashSet<String>();
1310                 while (true) {
1311                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1312                         if (friendId == null) {
1313                                 break;
1314                         }
1315                         friends.add(friendId);
1316                 }
1317
1318                 /* load options. */
1319                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1320
1321                 /* if we’re still here, Sone was loaded successfully. */
1322                 synchronized (sone) {
1323                         sone.setTime(soneTime);
1324                         sone.setProfile(profile);
1325                         sone.setPosts(posts);
1326                         sone.setReplies(replies);
1327                         sone.setLikePostIds(likedPostIds);
1328                         sone.setLikeReplyIds(likedReplyIds);
1329                         sone.setFriends(friends);
1330                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1331                 }
1332                 synchronized (newSones) {
1333                         for (String friend : friends) {
1334                                 knownSones.add(friend);
1335                         }
1336                 }
1337                 synchronized (newPosts) {
1338                         for (Post post : posts) {
1339                                 knownPosts.add(post.getId());
1340                         }
1341                 }
1342                 synchronized (newReplies) {
1343                         for (Reply reply : replies) {
1344                                 knownReplies.add(reply.getId());
1345                         }
1346                 }
1347         }
1348
1349         /**
1350          * Saves the given Sone. This will persist all local settings for the given
1351          * Sone, such as the friends list and similar, private options.
1352          *
1353          * @param sone
1354          *            The Sone to save
1355          */
1356         public synchronized void saveSone(Sone sone) {
1357                 if (!isLocalSone(sone)) {
1358                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1359                         return;
1360                 }
1361                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1362                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1363                         return;
1364                 }
1365
1366                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1367                 try {
1368                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1369
1370                         /* save Sone into configuration. */
1371                         String sonePrefix = "Sone/" + sone.getId();
1372                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1373                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1374
1375                         /* save profile. */
1376                         Profile profile = sone.getProfile();
1377                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1378                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1379                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1380                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1381                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1382                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1383
1384                         /* save profile fields. */
1385                         int fieldCounter = 0;
1386                         for (Field profileField : profile.getFields()) {
1387                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1388                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1389                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1390                         }
1391                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1392
1393                         /* save posts. */
1394                         int postCounter = 0;
1395                         for (Post post : sone.getPosts()) {
1396                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1397                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1398                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1399                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1400                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1401                         }
1402                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1403
1404                         /* save replies. */
1405                         int replyCounter = 0;
1406                         for (Reply reply : sone.getReplies()) {
1407                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1408                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1409                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1410                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1411                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1412                         }
1413                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1414
1415                         /* save post likes. */
1416                         int postLikeCounter = 0;
1417                         for (String postId : sone.getLikedPostIds()) {
1418                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1419                         }
1420                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1421
1422                         /* save reply likes. */
1423                         int replyLikeCounter = 0;
1424                         for (String replyId : sone.getLikedReplyIds()) {
1425                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1426                         }
1427                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1428
1429                         /* save friends. */
1430                         int friendCounter = 0;
1431                         for (String friendId : sone.getFriends()) {
1432                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1433                         }
1434                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1435
1436                         /* save options. */
1437                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1438
1439                         configuration.save();
1440                         logger.log(Level.INFO, "Sone %s saved.", sone);
1441                 } catch (ConfigurationException ce1) {
1442                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1443                 } catch (WebOfTrustException wote1) {
1444                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1445                 }
1446         }
1447
1448         /**
1449          * Creates a new post.
1450          *
1451          * @param sone
1452          *            The Sone that creates the post
1453          * @param text
1454          *            The text of the post
1455          * @return The created post
1456          */
1457         public Post createPost(Sone sone, String text) {
1458                 return createPost(sone, System.currentTimeMillis(), text);
1459         }
1460
1461         /**
1462          * Creates a new post.
1463          *
1464          * @param sone
1465          *            The Sone that creates the post
1466          * @param time
1467          *            The time of the post
1468          * @param text
1469          *            The text of the post
1470          * @return The created post
1471          */
1472         public Post createPost(Sone sone, long time, String text) {
1473                 return createPost(sone, null, time, text);
1474         }
1475
1476         /**
1477          * Creates a new post.
1478          *
1479          * @param sone
1480          *            The Sone that creates the post
1481          * @param recipient
1482          *            The recipient Sone, or {@code null} if this post does not have
1483          *            a recipient
1484          * @param text
1485          *            The text of the post
1486          * @return The created post
1487          */
1488         public Post createPost(Sone sone, Sone recipient, String text) {
1489                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1490         }
1491
1492         /**
1493          * Creates a new post.
1494          *
1495          * @param sone
1496          *            The Sone that creates the post
1497          * @param recipient
1498          *            The recipient Sone, or {@code null} if this post does not have
1499          *            a recipient
1500          * @param time
1501          *            The time of the post
1502          * @param text
1503          *            The text of the post
1504          * @return The created post
1505          */
1506         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1507                 if (!isLocalSone(sone)) {
1508                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1509                         return null;
1510                 }
1511                 final Post post = new Post(sone, time, text);
1512                 if (recipient != null) {
1513                         post.setRecipient(recipient);
1514                 }
1515                 synchronized (posts) {
1516                         posts.put(post.getId(), post);
1517                 }
1518                 synchronized (newPosts) {
1519                         newPosts.add(post.getId());
1520                         coreListenerManager.fireNewPostFound(post);
1521                 }
1522                 sone.addPost(post);
1523                 saveSone(sone);
1524                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1525
1526                         /**
1527                          * {@inheritDoc}
1528                          */
1529                         @Override
1530                         public void run() {
1531                                 markPostKnown(post);
1532                         }
1533                 }, "Mark " + post + " read.");
1534                 return post;
1535         }
1536
1537         /**
1538          * Deletes the given post.
1539          *
1540          * @param post
1541          *            The post to delete
1542          */
1543         public void deletePost(Post post) {
1544                 if (!isLocalSone(post.getSone())) {
1545                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1546                         return;
1547                 }
1548                 post.getSone().removePost(post);
1549                 synchronized (posts) {
1550                         posts.remove(post.getId());
1551                 }
1552                 coreListenerManager.firePostRemoved(post);
1553                 synchronized (newPosts) {
1554                         markPostKnown(post);
1555                         knownPosts.remove(post.getId());
1556                 }
1557                 saveSone(post.getSone());
1558         }
1559
1560         /**
1561          * Marks the given post as known, if it is currently a new post (according
1562          * to {@link #isNewPost(String)}).
1563          *
1564          * @param post
1565          *            The post to mark as known
1566          */
1567         public void markPostKnown(Post post) {
1568                 synchronized (newPosts) {
1569                         if (newPosts.remove(post.getId())) {
1570                                 knownPosts.add(post.getId());
1571                                 coreListenerManager.fireMarkPostKnown(post);
1572                                 saveConfiguration();
1573                         }
1574                 }
1575         }
1576
1577         /**
1578          * Bookmarks the given post.
1579          *
1580          * @param post
1581          *            The post to bookmark
1582          */
1583         public void bookmark(Post post) {
1584                 bookmarkPost(post.getId());
1585         }
1586
1587         /**
1588          * Bookmarks the post with the given ID.
1589          *
1590          * @param id
1591          *            The ID of the post to bookmark
1592          */
1593         public void bookmarkPost(String id) {
1594                 synchronized (bookmarkedPosts) {
1595                         bookmarkedPosts.add(id);
1596                 }
1597         }
1598
1599         /**
1600          * Removes the given post from the bookmarks.
1601          *
1602          * @param post
1603          *            The post to unbookmark
1604          */
1605         public void unbookmark(Post post) {
1606                 unbookmarkPost(post.getId());
1607         }
1608
1609         /**
1610          * Removes the post with the given ID from the bookmarks.
1611          *
1612          * @param id
1613          *            The ID of the post to unbookmark
1614          */
1615         public void unbookmarkPost(String id) {
1616                 synchronized (bookmarkedPosts) {
1617                         bookmarkedPosts.remove(id);
1618                 }
1619         }
1620
1621         /**
1622          * Creates a new reply.
1623          *
1624          * @param sone
1625          *            The Sone that creates the reply
1626          * @param post
1627          *            The post that this reply refers to
1628          * @param text
1629          *            The text of the reply
1630          * @return The created reply
1631          */
1632         public Reply createReply(Sone sone, Post post, String text) {
1633                 return createReply(sone, post, System.currentTimeMillis(), text);
1634         }
1635
1636         /**
1637          * Creates a new reply.
1638          *
1639          * @param sone
1640          *            The Sone that creates the reply
1641          * @param post
1642          *            The post that this reply refers to
1643          * @param time
1644          *            The time of the reply
1645          * @param text
1646          *            The text of the reply
1647          * @return The created reply
1648          */
1649         public Reply createReply(Sone sone, Post post, long time, String text) {
1650                 if (!isLocalSone(sone)) {
1651                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1652                         return null;
1653                 }
1654                 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1655                 synchronized (replies) {
1656                         replies.put(reply.getId(), reply);
1657                 }
1658                 synchronized (newReplies) {
1659                         newReplies.add(reply.getId());
1660                         coreListenerManager.fireNewReplyFound(reply);
1661                 }
1662                 sone.addReply(reply);
1663                 saveSone(sone);
1664                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1665
1666                         /**
1667                          * {@inheritDoc}
1668                          */
1669                         @Override
1670                         public void run() {
1671                                 markReplyKnown(reply);
1672                         }
1673                 }, "Mark " + reply + " read.");
1674                 return reply;
1675         }
1676
1677         /**
1678          * Deletes the given reply.
1679          *
1680          * @param reply
1681          *            The reply to delete
1682          */
1683         public void deleteReply(Reply reply) {
1684                 Sone sone = reply.getSone();
1685                 if (!isLocalSone(sone)) {
1686                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1687                         return;
1688                 }
1689                 synchronized (replies) {
1690                         replies.remove(reply.getId());
1691                 }
1692                 synchronized (newReplies) {
1693                         markReplyKnown(reply);
1694                         knownReplies.remove(reply.getId());
1695                 }
1696                 sone.removeReply(reply);
1697                 saveSone(sone);
1698         }
1699
1700         /**
1701          * Marks the given reply as known, if it is currently a new reply (according
1702          * to {@link #isNewReply(String)}).
1703          *
1704          * @param reply
1705          *            The reply to mark as known
1706          */
1707         public void markReplyKnown(Reply reply) {
1708                 synchronized (newReplies) {
1709                         if (newReplies.remove(reply.getId())) {
1710                                 knownReplies.add(reply.getId());
1711                                 coreListenerManager.fireMarkReplyKnown(reply);
1712                                 saveConfiguration();
1713                         }
1714                 }
1715         }
1716
1717         /**
1718          * Starts the core.
1719          */
1720         public void start() {
1721                 loadConfiguration();
1722                 updateChecker.addUpdateListener(this);
1723                 updateChecker.start();
1724         }
1725
1726         /**
1727          * Stops the core.
1728          */
1729         public void stop() {
1730                 synchronized (localSones) {
1731                         for (SoneInserter soneInserter : soneInserters.values()) {
1732                                 soneInserter.stop();
1733                         }
1734                         for (Sone localSone : localSones.values()) {
1735                                 saveSone(localSone);
1736                         }
1737                 }
1738                 updateChecker.stop();
1739                 updateChecker.removeUpdateListener(this);
1740                 soneDownloader.stop();
1741                 saveConfiguration();
1742                 stopped = true;
1743         }
1744
1745         /**
1746          * Saves the current options.
1747          */
1748         public void saveConfiguration() {
1749                 synchronized (configuration) {
1750                         if (storingConfiguration) {
1751                                 logger.log(Level.FINE, "Already storing configuration…");
1752                                 return;
1753                         }
1754                         storingConfiguration = true;
1755                 }
1756
1757                 /* store the options first. */
1758                 try {
1759                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1760                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1761                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1762                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1763                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1764                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1765                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1766                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1767                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1768                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1769                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1770                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1771                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1772
1773                         /* save known Sones. */
1774                         int soneCounter = 0;
1775                         synchronized (newSones) {
1776                                 for (String knownSoneId : knownSones) {
1777                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1778                                 }
1779                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1780                         }
1781
1782                         /* save known posts. */
1783                         int postCounter = 0;
1784                         synchronized (newPosts) {
1785                                 for (String knownPostId : knownPosts) {
1786                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1787                                 }
1788                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1789                         }
1790
1791                         /* save known replies. */
1792                         int replyCounter = 0;
1793                         synchronized (newReplies) {
1794                                 for (String knownReplyId : knownReplies) {
1795                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1796                                 }
1797                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1798                         }
1799
1800                         /* save bookmarked posts. */
1801                         int bookmarkedPostCounter = 0;
1802                         synchronized (bookmarkedPosts) {
1803                                 for (String bookmarkedPostId : bookmarkedPosts) {
1804                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1805                                 }
1806                         }
1807                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1808
1809                         /* now save it. */
1810                         configuration.save();
1811
1812                 } catch (ConfigurationException ce1) {
1813                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1814                 } finally {
1815                         synchronized (configuration) {
1816                                 storingConfiguration = false;
1817                         }
1818                 }
1819         }
1820
1821         //
1822         // PRIVATE METHODS
1823         //
1824
1825         /**
1826          * Loads the configuration.
1827          */
1828         @SuppressWarnings("unchecked")
1829         private void loadConfiguration() {
1830                 /* create options. */
1831                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1832
1833                         @Override
1834                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1835                                 SoneInserter.setInsertionDelay(newValue);
1836                         }
1837
1838                 }));
1839                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1840                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
1841                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1842                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1843                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1844                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1845                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1846
1847                         @Override
1848                         @SuppressWarnings("synthetic-access")
1849                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1850                                 fcpInterface.setActive(newValue);
1851                         }
1852                 }));
1853                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1854
1855                         @Override
1856                         @SuppressWarnings("synthetic-access")
1857                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1858                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1859                         }
1860
1861                 }));
1862                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1863                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1864                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1865
1866                 /* read options from configuration. */
1867                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1868                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1869                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1870                 options.getBooleanOption("ClearOnNextRestart").set(null);
1871                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1872                 if (clearConfiguration) {
1873                         /* stop loading the configuration. */
1874                         return;
1875                 }
1876
1877                 loadConfigurationValue("InsertionDelay");
1878                 loadConfigurationValue("PostsPerPage");
1879                 loadConfigurationValue("CharactersPerPost");
1880                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1881                 loadConfigurationValue("PositiveTrust");
1882                 loadConfigurationValue("NegativeTrust");
1883                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1884                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1885                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1886                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1887
1888                 /* load known Sones. */
1889                 int soneCounter = 0;
1890                 while (true) {
1891                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1892                         if (knownSoneId == null) {
1893                                 break;
1894                         }
1895                         synchronized (newSones) {
1896                                 knownSones.add(knownSoneId);
1897                         }
1898                 }
1899
1900                 /* load known posts. */
1901                 int postCounter = 0;
1902                 while (true) {
1903                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1904                         if (knownPostId == null) {
1905                                 break;
1906                         }
1907                         synchronized (newPosts) {
1908                                 knownPosts.add(knownPostId);
1909                         }
1910                 }
1911
1912                 /* load known replies. */
1913                 int replyCounter = 0;
1914                 while (true) {
1915                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1916                         if (knownReplyId == null) {
1917                                 break;
1918                         }
1919                         synchronized (newReplies) {
1920                                 knownReplies.add(knownReplyId);
1921                         }
1922                 }
1923
1924                 /* load bookmarked posts. */
1925                 int bookmarkedPostCounter = 0;
1926                 while (true) {
1927                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1928                         if (bookmarkedPostId == null) {
1929                                 break;
1930                         }
1931                         synchronized (bookmarkedPosts) {
1932                                 bookmarkedPosts.add(bookmarkedPostId);
1933                         }
1934                 }
1935
1936         }
1937
1938         /**
1939          * Loads an {@link Integer} configuration value for the option with the
1940          * given name, logging validation failures.
1941          *
1942          * @param optionName
1943          *            The name of the option to load
1944          */
1945         private void loadConfigurationValue(String optionName) {
1946                 try {
1947                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1948                 } catch (IllegalArgumentException iae1) {
1949                         logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1950                 }
1951         }
1952
1953         /**
1954          * Generate a Sone URI from the given URI and latest edition.
1955          *
1956          * @param uriString
1957          *            The URI to derive the Sone URI from
1958          * @return The derived URI
1959          */
1960         private FreenetURI getSoneUri(String uriString) {
1961                 try {
1962                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1963                         return uri;
1964                 } catch (MalformedURLException mue1) {
1965                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1966                         return null;
1967                 }
1968         }
1969
1970         //
1971         // INTERFACE IdentityListener
1972         //
1973
1974         /**
1975          * {@inheritDoc}
1976          */
1977         @Override
1978         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1979                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1980                 if (ownIdentity.hasContext("Sone")) {
1981                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1982                         addLocalSone(ownIdentity);
1983                 }
1984         }
1985
1986         /**
1987          * {@inheritDoc}
1988          */
1989         @Override
1990         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1991                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1992                 trustedIdentities.remove(ownIdentity);
1993         }
1994
1995         /**
1996          * {@inheritDoc}
1997          */
1998         @Override
1999         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2000                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2001                 trustedIdentities.get(ownIdentity).add(identity);
2002                 addRemoteSone(identity);
2003         }
2004
2005         /**
2006          * {@inheritDoc}
2007          */
2008         @Override
2009         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2010                 new Thread(new Runnable() {
2011
2012                         @Override
2013                         @SuppressWarnings("synthetic-access")
2014                         public void run() {
2015                                 Sone sone = getRemoteSone(identity.getId());
2016                                 sone.setIdentity(identity);
2017                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2018                                 soneDownloader.addSone(sone);
2019                                 soneDownloader.fetchSone(sone);
2020                         }
2021                 }).start();
2022         }
2023
2024         /**
2025          * {@inheritDoc}
2026          */
2027         @Override
2028         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2029                 trustedIdentities.get(ownIdentity).remove(identity);
2030                 boolean foundIdentity = false;
2031                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2032                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2033                                 continue;
2034                         }
2035                         if (trustedIdentity.getValue().contains(identity)) {
2036                                 foundIdentity = true;
2037                         }
2038                 }
2039                 if (foundIdentity) {
2040                         /* some local identity still trusts this identity, don’t remove. */
2041                         return;
2042                 }
2043                 Sone sone = getSone(identity.getId(), false);
2044                 if (sone == null) {
2045                         /* TODO - we don’t have the Sone anymore. should this happen? */
2046                         return;
2047                 }
2048                 synchronized (posts) {
2049                         synchronized (newPosts) {
2050                                 for (Post post : sone.getPosts()) {
2051                                         posts.remove(post.getId());
2052                                         newPosts.remove(post.getId());
2053                                         coreListenerManager.firePostRemoved(post);
2054                                 }
2055                         }
2056                 }
2057                 synchronized (replies) {
2058                         synchronized (newReplies) {
2059                                 for (Reply reply : sone.getReplies()) {
2060                                         replies.remove(reply.getId());
2061                                         newReplies.remove(reply.getId());
2062                                         coreListenerManager.fireReplyRemoved(reply);
2063                                 }
2064                         }
2065                 }
2066                 synchronized (remoteSones) {
2067                         remoteSones.remove(identity.getId());
2068                 }
2069                 synchronized (newSones) {
2070                         newSones.remove(identity.getId());
2071                         coreListenerManager.fireSoneRemoved(sone);
2072                 }
2073         }
2074
2075         //
2076         // INTERFACE UpdateListener
2077         //
2078
2079         /**
2080          * {@inheritDoc}
2081          */
2082         @Override
2083         public void updateFound(Version version, long releaseTime, long latestEdition) {
2084                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2085         }
2086
2087         /**
2088          * Convenience interface for external classes that want to access the core’s
2089          * configuration.
2090          *
2091          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2092          */
2093         public static class Preferences {
2094
2095                 /** The wrapped options. */
2096                 private final Options options;
2097
2098                 /**
2099                  * Creates a new preferences object wrapped around the given options.
2100                  *
2101                  * @param options
2102                  *            The options to wrap
2103                  */
2104                 public Preferences(Options options) {
2105                         this.options = options;
2106                 }
2107
2108                 /**
2109                  * Returns the insertion delay.
2110                  *
2111                  * @return The insertion delay
2112                  */
2113                 public int getInsertionDelay() {
2114                         return options.getIntegerOption("InsertionDelay").get();
2115                 }
2116
2117                 /**
2118                  * Validates the given insertion delay.
2119                  *
2120                  * @param insertionDelay
2121                  *            The insertion delay to validate
2122                  * @return {@code true} if the given insertion delay was valid, {@code
2123                  *         false} otherwise
2124                  */
2125                 public boolean validateInsertionDelay(Integer insertionDelay) {
2126                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2127                 }
2128
2129                 /**
2130                  * Sets the insertion delay
2131                  *
2132                  * @param insertionDelay
2133                  *            The new insertion delay, or {@code null} to restore it to
2134                  *            the default value
2135                  * @return This preferences
2136                  */
2137                 public Preferences setInsertionDelay(Integer insertionDelay) {
2138                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2139                         return this;
2140                 }
2141
2142                 /**
2143                  * Returns the number of posts to show per page.
2144                  *
2145                  * @return The number of posts to show per page
2146                  */
2147                 public int getPostsPerPage() {
2148                         return options.getIntegerOption("PostsPerPage").get();
2149                 }
2150
2151                 /**
2152                  * Validates the number of posts per page.
2153                  *
2154                  * @param postsPerPage
2155                  *            The number of posts per page
2156                  * @return {@code true} if the number of posts per page was valid,
2157                  *         {@code false} otherwise
2158                  */
2159                 public boolean validatePostsPerPage(Integer postsPerPage) {
2160                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2161                 }
2162
2163                 /**
2164                  * Sets the number of posts to show per page.
2165                  *
2166                  * @param postsPerPage
2167                  *            The number of posts to show per page
2168                  * @return This preferences object
2169                  */
2170                 public Preferences setPostsPerPage(Integer postsPerPage) {
2171                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2172                         return this;
2173                 }
2174
2175                 /**
2176                  * Returns the number of characters per post, or <code>-1</code> if the
2177                  * posts should not be cut off.
2178                  *
2179                  * @return The numbers of characters per post
2180                  */
2181                 public int getCharactersPerPost() {
2182                         return options.getIntegerOption("CharactersPerPost").get();
2183                 }
2184
2185                 /**
2186                  * Validates the number of characters per post.
2187                  *
2188                  * @param charactersPerPost
2189                  *            The number of characters per post
2190                  * @return {@code true} if the number of characters per post was valid,
2191                  *         {@code false} otherwise
2192                  */
2193                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2194                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2195                 }
2196
2197                 /**
2198                  * Sets the number of characters per post.
2199                  *
2200                  * @param charactersPerPost
2201                  *            The number of characters per post, or <code>-1</code> to
2202                  *            not cut off the posts
2203                  * @return This preferences objects
2204                  */
2205                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2206                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2207                         return this;
2208                 }
2209
2210                 /**
2211                  * Returns whether Sone requires full access to be even visible.
2212                  *
2213                  * @return {@code true} if Sone requires full access, {@code false}
2214                  *         otherwise
2215                  */
2216                 public boolean isRequireFullAccess() {
2217                         return options.getBooleanOption("RequireFullAccess").get();
2218                 }
2219
2220                 /**
2221                  * Sets whether Sone requires full access to be even visible.
2222                  *
2223                  * @param requireFullAccess
2224                  *            {@code true} if Sone requires full access, {@code false}
2225                  *            otherwise
2226                  */
2227                 public void setRequireFullAccess(Boolean requireFullAccess) {
2228                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2229                 }
2230
2231                 /**
2232                  * Returns the positive trust.
2233                  *
2234                  * @return The positive trust
2235                  */
2236                 public int getPositiveTrust() {
2237                         return options.getIntegerOption("PositiveTrust").get();
2238                 }
2239
2240                 /**
2241                  * Validates the positive trust.
2242                  *
2243                  * @param positiveTrust
2244                  *            The positive trust to validate
2245                  * @return {@code true} if the positive trust was valid, {@code false}
2246                  *         otherwise
2247                  */
2248                 public boolean validatePositiveTrust(Integer positiveTrust) {
2249                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2250                 }
2251
2252                 /**
2253                  * Sets the positive trust.
2254                  *
2255                  * @param positiveTrust
2256                  *            The new positive trust, or {@code null} to restore it to
2257                  *            the default vlaue
2258                  * @return This preferences
2259                  */
2260                 public Preferences setPositiveTrust(Integer positiveTrust) {
2261                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2262                         return this;
2263                 }
2264
2265                 /**
2266                  * Returns the negative trust.
2267                  *
2268                  * @return The negative trust
2269                  */
2270                 public int getNegativeTrust() {
2271                         return options.getIntegerOption("NegativeTrust").get();
2272                 }
2273
2274                 /**
2275                  * Validates the negative trust.
2276                  *
2277                  * @param negativeTrust
2278                  *            The negative trust to validate
2279                  * @return {@code true} if the negative trust was valid, {@code false}
2280                  *         otherwise
2281                  */
2282                 public boolean validateNegativeTrust(Integer negativeTrust) {
2283                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2284                 }
2285
2286                 /**
2287                  * Sets the negative trust.
2288                  *
2289                  * @param negativeTrust
2290                  *            The negative trust, or {@code null} to restore it to the
2291                  *            default value
2292                  * @return The preferences
2293                  */
2294                 public Preferences setNegativeTrust(Integer negativeTrust) {
2295                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2296                         return this;
2297                 }
2298
2299                 /**
2300                  * Returns the trust comment. This is the comment that is set in the web
2301                  * of trust when a trust value is assigned to an identity.
2302                  *
2303                  * @return The trust comment
2304                  */
2305                 public String getTrustComment() {
2306                         return options.getStringOption("TrustComment").get();
2307                 }
2308
2309                 /**
2310                  * Sets the trust comment.
2311                  *
2312                  * @param trustComment
2313                  *            The trust comment, or {@code null} to restore it to the
2314                  *            default value
2315                  * @return This preferences
2316                  */
2317                 public Preferences setTrustComment(String trustComment) {
2318                         options.getStringOption("TrustComment").set(trustComment);
2319                         return this;
2320                 }
2321
2322                 /**
2323                  * Returns whether the {@link FcpInterface FCP interface} is currently
2324                  * active.
2325                  *
2326                  * @see FcpInterface#setActive(boolean)
2327                  * @return {@code true} if the FCP interface is currently active,
2328                  *         {@code false} otherwise
2329                  */
2330                 public boolean isFcpInterfaceActive() {
2331                         return options.getBooleanOption("ActivateFcpInterface").get();
2332                 }
2333
2334                 /**
2335                  * Sets whether the {@link FcpInterface FCP interface} is currently
2336                  * active.
2337                  *
2338                  * @see FcpInterface#setActive(boolean)
2339                  * @param fcpInterfaceActive
2340                  *            {@code true} to activate the FCP interface, {@code false}
2341                  *            to deactivate the FCP interface
2342                  * @return This preferences object
2343                  */
2344                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2345                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2346                         return this;
2347                 }
2348
2349                 /**
2350                  * Returns the action level for which full access to the FCP interface
2351                  * is required.
2352                  *
2353                  * @return The action level for which full access to the FCP interface
2354                  *         is required
2355                  */
2356                 public FullAccessRequired getFcpFullAccessRequired() {
2357                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2358                 }
2359
2360                 /**
2361                  * Sets the action level for which full access to the FCP interface is
2362                  * required
2363                  *
2364                  * @param fcpFullAccessRequired
2365                  *            The action level
2366                  * @return This preferences
2367                  */
2368                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2369                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2370                         return this;
2371                 }
2372
2373                 /**
2374                  * Returns whether the rescue mode is active.
2375                  *
2376                  * @return {@code true} if the rescue mode is active, {@code false}
2377                  *         otherwise
2378                  */
2379                 public boolean isSoneRescueMode() {
2380                         return options.getBooleanOption("SoneRescueMode").get();
2381                 }
2382
2383                 /**
2384                  * Sets whether the rescue mode is active.
2385                  *
2386                  * @param soneRescueMode
2387                  *            {@code true} if the rescue mode is active, {@code false}
2388                  *            otherwise
2389                  * @return This preferences
2390                  */
2391                 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2392                         options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2393                         return this;
2394                 }
2395
2396                 /**
2397                  * Returns whether Sone should clear its settings on the next restart.
2398                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2399                  * to return {@code true} as well!
2400                  *
2401                  * @return {@code true} if Sone should clear its settings on the next
2402                  *         restart, {@code false} otherwise
2403                  */
2404                 public boolean isClearOnNextRestart() {
2405                         return options.getBooleanOption("ClearOnNextRestart").get();
2406                 }
2407
2408                 /**
2409                  * Sets whether Sone will clear its settings on the next restart.
2410                  *
2411                  * @param clearOnNextRestart
2412                  *            {@code true} if Sone should clear its settings on the next
2413                  *            restart, {@code false} otherwise
2414                  * @return This preferences
2415                  */
2416                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2417                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2418                         return this;
2419                 }
2420
2421                 /**
2422                  * Returns whether Sone should really clear its settings on next
2423                  * restart. This is a confirmation option that needs to be set in
2424                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2425                  * settings on the next restart.
2426                  *
2427                  * @return {@code true} if Sone should really clear its settings on the
2428                  *         next restart, {@code false} otherwise
2429                  */
2430                 public boolean isReallyClearOnNextRestart() {
2431                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2432                 }
2433
2434                 /**
2435                  * Sets whether Sone should really clear its settings on the next
2436                  * restart.
2437                  *
2438                  * @param reallyClearOnNextRestart
2439                  *            {@code true} if Sone should really clear its settings on
2440                  *            the next restart, {@code false} otherwise
2441                  * @return This preferences
2442                  */
2443                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2444                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2445                         return this;
2446                 }
2447
2448         }
2449
2450 }