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