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