Add method to get the trust between two Sones.
[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                         lockedSones.add(sone);
732                 }
733         }
734
735         /**
736          * Unlocks the given Sone.
737          *
738          * @see #lockSone(Sone)
739          * @param sone
740          *            The sone to unlock
741          */
742         public void unlockSone(Sone sone) {
743                 synchronized (lockedSones) {
744                         lockedSones.remove(sone);
745                 }
746         }
747
748         /**
749          * Adds a local Sone from the given ID which has to be the ID of an own
750          * identity.
751          *
752          * @param id
753          *            The ID of an own identity to add a Sone for
754          * @return The added (or already existing) Sone
755          */
756         public Sone addLocalSone(String id) {
757                 synchronized (localSones) {
758                         if (localSones.containsKey(id)) {
759                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
760                                 return localSones.get(id);
761                         }
762                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
763                         if (ownIdentity == null) {
764                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
765                                 return null;
766                         }
767                         return addLocalSone(ownIdentity);
768                 }
769         }
770
771         /**
772          * Adds a local Sone from the given own identity.
773          *
774          * @param ownIdentity
775          *            The own identity to create a Sone from
776          * @return The added (or already existing) Sone
777          */
778         public Sone addLocalSone(OwnIdentity ownIdentity) {
779                 if (ownIdentity == null) {
780                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
781                         return null;
782                 }
783                 synchronized (localSones) {
784                         final Sone sone;
785                         try {
786                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
787                         } catch (MalformedURLException mue1) {
788                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
789                                 return null;
790                         }
791                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
792                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
793                         /* TODO - load posts ’n stuff */
794                         localSones.put(ownIdentity.getId(), sone);
795                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
796                         soneInserters.put(sone, soneInserter);
797                         setSoneStatus(sone, SoneStatus.idle);
798                         loadSone(sone);
799                         if (!isSoneRescueMode()) {
800                                 soneInserter.start();
801                         }
802                         new Thread(new Runnable() {
803
804                                 @Override
805                                 @SuppressWarnings("synthetic-access")
806                                 public void run() {
807                                         if (!isSoneRescueMode()) {
808                                                 soneDownloader.fetchSone(sone);
809                                                 return;
810                                         }
811                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
812                                         coreListenerManager.fireRescuingSone(sone);
813                                         lockSone(sone);
814                                         long edition = sone.getLatestEdition();
815                                         while (!stopped && (edition >= 0) && isSoneRescueMode()) {
816                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
817                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
818                                                 --edition;
819                                         }
820                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
821                                         saveSone(sone);
822                                         coreListenerManager.fireRescuedSone(sone);
823                                         soneInserter.start();
824                                 }
825
826                         }, "Sone Downloader").start();
827                         return sone;
828                 }
829         }
830
831         /**
832          * Creates a new Sone for the given own identity.
833          *
834          * @param ownIdentity
835          *            The own identity to create a Sone for
836          * @return The created Sone
837          */
838         public Sone createSone(OwnIdentity ownIdentity) {
839                 try {
840                         ownIdentity.addContext("Sone");
841                 } catch (WebOfTrustException wote1) {
842                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
843                         return null;
844                 }
845                 Sone sone = addLocalSone(ownIdentity);
846                 return sone;
847         }
848
849         /**
850          * Adds the Sone of the given identity.
851          *
852          * @param identity
853          *            The identity whose Sone to add
854          * @return The added or already existing Sone
855          */
856         public Sone addRemoteSone(Identity identity) {
857                 if (identity == null) {
858                         logger.log(Level.WARNING, "Given Identity is null!");
859                         return null;
860                 }
861                 synchronized (remoteSones) {
862                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
863                         boolean newSone = sone.getRequestUri() == null;
864                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
865                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
866                         if (newSone) {
867                                 synchronized (newSones) {
868                                         newSone = !knownSones.contains(sone.getId());
869                                         if (newSone) {
870                                                 newSones.add(sone.getId());
871                                         }
872                                 }
873                                 if (newSone) {
874                                         coreListenerManager.fireNewSoneFound(sone);
875                                 }
876                         }
877                         remoteSones.put(identity.getId(), sone);
878                         soneDownloader.addSone(sone);
879                         setSoneStatus(sone, SoneStatus.unknown);
880                         new Thread(new Runnable() {
881
882                                 @Override
883                                 @SuppressWarnings("synthetic-access")
884                                 public void run() {
885                                         soneDownloader.fetchSone(sone);
886                                 }
887
888                         }, "Sone Downloader").start();
889                         return sone;
890                 }
891         }
892
893         /**
894          * Retrieves the trust relationship from the origin to the target.
895          *
896          * @param origin
897          *            The origin of the trust tree
898          * @param target
899          *            The target of the trust
900          * @return The trust relationship
901          */
902         public Trust getTrust(Sone origin, Sone target) {
903                 if (!isLocalSone(origin)) {
904                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
905                         return null;
906                 }
907                 try {
908                         return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
909                 } catch (WebOfTrustException wote1) {
910                         logger.log(Level.WARNING, "Could not get trust for Sone: " + target, wote1);
911                         return null;
912                 }
913         }
914
915         /**
916          * Updates the stores Sone with the given Sone.
917          *
918          * @param sone
919          *            The updated Sone
920          */
921         public void updateSone(Sone sone) {
922                 if (hasSone(sone.getId())) {
923                         boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
924                         Sone storedSone = getSone(sone.getId());
925                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
926                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
927                                 return;
928                         }
929                         synchronized (posts) {
930                                 if (!soneRescueMode) {
931                                         for (Post post : storedSone.getPosts()) {
932                                                 posts.remove(post.getId());
933                                                 if (!sone.getPosts().contains(post)) {
934                                                         coreListenerManager.firePostRemoved(post);
935                                                 }
936                                         }
937                                 }
938                                 synchronized (newPosts) {
939                                         for (Post post : sone.getPosts()) {
940                                                 post.setSone(getSone(post.getSone().getId()));
941                                                 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
942                                                         newPosts.add(post.getId());
943                                                         coreListenerManager.fireNewPostFound(post);
944                                                 }
945                                                 posts.put(post.getId(), post);
946                                         }
947                                 }
948                         }
949                         synchronized (replies) {
950                                 if (!soneRescueMode) {
951                                         for (Reply reply : storedSone.getReplies()) {
952                                                 replies.remove(reply.getId());
953                                                 if (!sone.getReplies().contains(reply)) {
954                                                         coreListenerManager.fireReplyRemoved(reply);
955                                                 }
956                                         }
957                                 }
958                                 synchronized (newReplies) {
959                                         for (Reply reply : sone.getReplies()) {
960                                                 reply.setSone(getSone(reply.getSone().getId()));
961                                                 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
962                                                         newReplies.add(reply.getId());
963                                                         coreListenerManager.fireNewReplyFound(reply);
964                                                 }
965                                                 replies.put(reply.getId(), reply);
966                                         }
967                                 }
968                         }
969                         synchronized (storedSone) {
970                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
971                                         storedSone.setTime(sone.getTime());
972                                 }
973                                 storedSone.setClient(sone.getClient());
974                                 storedSone.setProfile(sone.getProfile());
975                                 if (soneRescueMode) {
976                                         for (Post post : sone.getPosts()) {
977                                                 storedSone.addPost(post);
978                                         }
979                                         for (Reply reply : sone.getReplies()) {
980                                                 storedSone.addReply(reply);
981                                         }
982                                         for (String likedPostId : sone.getLikedPostIds()) {
983                                                 storedSone.addLikedPostId(likedPostId);
984                                         }
985                                         for (String likedReplyId : sone.getLikedReplyIds()) {
986                                                 storedSone.addLikedReplyId(likedReplyId);
987                                         }
988                                 } else {
989                                         storedSone.setPosts(sone.getPosts());
990                                         storedSone.setReplies(sone.getReplies());
991                                         storedSone.setLikePostIds(sone.getLikedPostIds());
992                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
993                                 }
994                                 storedSone.setLatestEdition(sone.getLatestEdition());
995                         }
996                 }
997         }
998
999         /**
1000          * Deletes the given Sone. This will remove the Sone from the
1001          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1002          * and remove the context from its identity.
1003          *
1004          * @param sone
1005          *            The Sone to delete
1006          */
1007         public void deleteSone(Sone sone) {
1008                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1009                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1010                         return;
1011                 }
1012                 synchronized (localSones) {
1013                         if (!localSones.containsKey(sone.getId())) {
1014                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1015                                 return;
1016                         }
1017                         localSones.remove(sone.getId());
1018                         soneInserters.remove(sone).stop();
1019                 }
1020                 try {
1021                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1022                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1023                 } catch (WebOfTrustException wote1) {
1024                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1025                 }
1026                 try {
1027                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1028                 } catch (ConfigurationException ce1) {
1029                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1030                 }
1031         }
1032
1033         /**
1034          * Loads and updates the given Sone from the configuration. If any error is
1035          * encountered, loading is aborted and the given Sone is not changed.
1036          *
1037          * @param sone
1038          *            The Sone to load and update
1039          */
1040         public void loadSone(Sone sone) {
1041                 if (!isLocalSone(sone)) {
1042                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1043                         return;
1044                 }
1045
1046                 /* load Sone. */
1047                 String sonePrefix = "Sone/" + sone.getId();
1048                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1049                 if (soneTime == null) {
1050                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1051                         return;
1052                 }
1053                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1054
1055                 /* load profile. */
1056                 Profile profile = new Profile();
1057                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1058                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1059                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1060                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1061                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1062                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1063
1064                 /* load posts. */
1065                 Set<Post> posts = new HashSet<Post>();
1066                 while (true) {
1067                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1068                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1069                         if (postId == null) {
1070                                 break;
1071                         }
1072                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1073                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1074                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1075                         if ((postTime == 0) || (postText == null)) {
1076                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1077                                 return;
1078                         }
1079                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1080                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1081                                 post.setRecipient(getSone(postRecipientId));
1082                         }
1083                         posts.add(post);
1084                 }
1085
1086                 /* load replies. */
1087                 Set<Reply> replies = new HashSet<Reply>();
1088                 while (true) {
1089                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1090                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1091                         if (replyId == null) {
1092                                 break;
1093                         }
1094                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1095                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1096                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1097                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1098                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1099                                 return;
1100                         }
1101                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1102                 }
1103
1104                 /* load post likes. */
1105                 Set<String> likedPostIds = new HashSet<String>();
1106                 while (true) {
1107                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1108                         if (likedPostId == null) {
1109                                 break;
1110                         }
1111                         likedPostIds.add(likedPostId);
1112                 }
1113
1114                 /* load reply likes. */
1115                 Set<String> likedReplyIds = new HashSet<String>();
1116                 while (true) {
1117                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1118                         if (likedReplyId == null) {
1119                                 break;
1120                         }
1121                         likedReplyIds.add(likedReplyId);
1122                 }
1123
1124                 /* load friends. */
1125                 Set<String> friends = new HashSet<String>();
1126                 while (true) {
1127                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1128                         if (friendId == null) {
1129                                 break;
1130                         }
1131                         friends.add(friendId);
1132                 }
1133
1134                 /* if we’re still here, Sone was loaded successfully. */
1135                 synchronized (sone) {
1136                         sone.setTime(soneTime);
1137                         sone.setProfile(profile);
1138                         sone.setPosts(posts);
1139                         sone.setReplies(replies);
1140                         sone.setLikePostIds(likedPostIds);
1141                         sone.setLikeReplyIds(likedReplyIds);
1142                         sone.setFriends(friends);
1143                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1144                 }
1145                 synchronized (newSones) {
1146                         for (String friend : friends) {
1147                                 knownSones.add(friend);
1148                         }
1149                 }
1150                 synchronized (newPosts) {
1151                         for (Post post : posts) {
1152                                 knownPosts.add(post.getId());
1153                         }
1154                 }
1155                 synchronized (newReplies) {
1156                         for (Reply reply : replies) {
1157                                 knownReplies.add(reply.getId());
1158                         }
1159                 }
1160         }
1161
1162         /**
1163          * Saves the given Sone. This will persist all local settings for the given
1164          * Sone, such as the friends list and similar, private options.
1165          *
1166          * @param sone
1167          *            The Sone to save
1168          */
1169         public void saveSone(Sone sone) {
1170                 if (!isLocalSone(sone)) {
1171                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1172                         return;
1173                 }
1174                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1175                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1176                         return;
1177                 }
1178
1179                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1180                 try {
1181                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1182
1183                         /* save Sone into configuration. */
1184                         String sonePrefix = "Sone/" + sone.getId();
1185                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1186                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1187
1188                         /* save profile. */
1189                         Profile profile = sone.getProfile();
1190                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1191                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1192                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1193                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1194                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1195                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1196
1197                         /* save posts. */
1198                         int postCounter = 0;
1199                         for (Post post : sone.getPosts()) {
1200                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1201                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1202                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1203                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1204                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1205                         }
1206                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1207
1208                         /* save replies. */
1209                         int replyCounter = 0;
1210                         for (Reply reply : sone.getReplies()) {
1211                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1212                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1213                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1214                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1215                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1216                         }
1217                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1218
1219                         /* save post likes. */
1220                         int postLikeCounter = 0;
1221                         for (String postId : sone.getLikedPostIds()) {
1222                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1223                         }
1224                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1225
1226                         /* save reply likes. */
1227                         int replyLikeCounter = 0;
1228                         for (String replyId : sone.getLikedReplyIds()) {
1229                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1230                         }
1231                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1232
1233                         /* save friends. */
1234                         int friendCounter = 0;
1235                         for (String friendId : sone.getFriends()) {
1236                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1237                         }
1238                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1239
1240                         logger.log(Level.INFO, "Sone %s saved.", sone);
1241                 } catch (ConfigurationException ce1) {
1242                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1243                 } catch (WebOfTrustException wote1) {
1244                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1245                 }
1246         }
1247
1248         /**
1249          * Creates a new post.
1250          *
1251          * @param sone
1252          *            The Sone that creates the post
1253          * @param text
1254          *            The text of the post
1255          * @return The created post
1256          */
1257         public Post createPost(Sone sone, String text) {
1258                 return createPost(sone, System.currentTimeMillis(), text);
1259         }
1260
1261         /**
1262          * Creates a new post.
1263          *
1264          * @param sone
1265          *            The Sone that creates the post
1266          * @param time
1267          *            The time of the post
1268          * @param text
1269          *            The text of the post
1270          * @return The created post
1271          */
1272         public Post createPost(Sone sone, long time, String text) {
1273                 return createPost(sone, null, time, text);
1274         }
1275
1276         /**
1277          * Creates a new post.
1278          *
1279          * @param sone
1280          *            The Sone that creates the post
1281          * @param recipient
1282          *            The recipient Sone, or {@code null} if this post does not have
1283          *            a recipient
1284          * @param text
1285          *            The text of the post
1286          * @return The created post
1287          */
1288         public Post createPost(Sone sone, Sone recipient, String text) {
1289                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1290         }
1291
1292         /**
1293          * Creates a new post.
1294          *
1295          * @param sone
1296          *            The Sone that creates the post
1297          * @param recipient
1298          *            The recipient Sone, or {@code null} if this post does not have
1299          *            a recipient
1300          * @param time
1301          *            The time of the post
1302          * @param text
1303          *            The text of the post
1304          * @return The created post
1305          */
1306         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1307                 if (!isLocalSone(sone)) {
1308                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1309                         return null;
1310                 }
1311                 Post post = new Post(sone, time, text);
1312                 if (recipient != null) {
1313                         post.setRecipient(recipient);
1314                 }
1315                 synchronized (posts) {
1316                         posts.put(post.getId(), post);
1317                 }
1318                 synchronized (newPosts) {
1319                         knownPosts.add(post.getId());
1320                 }
1321                 sone.addPost(post);
1322                 saveSone(sone);
1323                 return post;
1324         }
1325
1326         /**
1327          * Deletes the given post.
1328          *
1329          * @param post
1330          *            The post to delete
1331          */
1332         public void deletePost(Post post) {
1333                 if (!isLocalSone(post.getSone())) {
1334                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1335                         return;
1336                 }
1337                 post.getSone().removePost(post);
1338                 synchronized (posts) {
1339                         posts.remove(post.getId());
1340                 }
1341                 saveSone(post.getSone());
1342         }
1343
1344         /**
1345          * Marks the given post as known, if it is currently a new post (according
1346          * to {@link #isNewPost(String)}).
1347          *
1348          * @param post
1349          *            The post to mark as known
1350          */
1351         public void markPostKnown(Post post) {
1352                 synchronized (newPosts) {
1353                         if (newPosts.remove(post.getId())) {
1354                                 knownPosts.add(post.getId());
1355                                 coreListenerManager.fireMarkPostKnown(post);
1356                         }
1357                 }
1358         }
1359
1360         /**
1361          * Creates a new reply.
1362          *
1363          * @param sone
1364          *            The Sone that creates the reply
1365          * @param post
1366          *            The post that this reply refers to
1367          * @param text
1368          *            The text of the reply
1369          * @return The created reply
1370          */
1371         public Reply createReply(Sone sone, Post post, String text) {
1372                 return createReply(sone, post, System.currentTimeMillis(), text);
1373         }
1374
1375         /**
1376          * Creates a new reply.
1377          *
1378          * @param sone
1379          *            The Sone that creates the reply
1380          * @param post
1381          *            The post that this reply refers to
1382          * @param time
1383          *            The time of the reply
1384          * @param text
1385          *            The text of the reply
1386          * @return The created reply
1387          */
1388         public Reply createReply(Sone sone, Post post, long time, String text) {
1389                 if (!isLocalSone(sone)) {
1390                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1391                         return null;
1392                 }
1393                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1394                 synchronized (replies) {
1395                         replies.put(reply.getId(), reply);
1396                 }
1397                 synchronized (newReplies) {
1398                         knownReplies.add(reply.getId());
1399                 }
1400                 sone.addReply(reply);
1401                 saveSone(sone);
1402                 return reply;
1403         }
1404
1405         /**
1406          * Deletes the given reply.
1407          *
1408          * @param reply
1409          *            The reply to delete
1410          */
1411         public void deleteReply(Reply reply) {
1412                 Sone sone = reply.getSone();
1413                 if (!isLocalSone(sone)) {
1414                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1415                         return;
1416                 }
1417                 synchronized (replies) {
1418                         replies.remove(reply.getId());
1419                 }
1420                 sone.removeReply(reply);
1421                 saveSone(sone);
1422         }
1423
1424         /**
1425          * Marks the given reply as known, if it is currently a new reply (according
1426          * to {@link #isNewReply(String)}).
1427          *
1428          * @param reply
1429          *            The reply to mark as known
1430          */
1431         public void markReplyKnown(Reply reply) {
1432                 synchronized (newReplies) {
1433                         if (newReplies.remove(reply.getId())) {
1434                                 knownReplies.add(reply.getId());
1435                                 coreListenerManager.fireMarkReplyKnown(reply);
1436                         }
1437                 }
1438         }
1439
1440         /**
1441          * Starts the core.
1442          */
1443         public void start() {
1444                 loadConfiguration();
1445         }
1446
1447         /**
1448          * Stops the core.
1449          */
1450         public void stop() {
1451                 synchronized (localSones) {
1452                         for (SoneInserter soneInserter : soneInserters.values()) {
1453                                 soneInserter.stop();
1454                         }
1455                 }
1456                 saveConfiguration();
1457                 stopped = true;
1458         }
1459
1460         /**
1461          * Saves the current options.
1462          */
1463         public void saveConfiguration() {
1464                 /* store the options first. */
1465                 try {
1466                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1467                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1468                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1469                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1470
1471                         /* save known Sones. */
1472                         int soneCounter = 0;
1473                         synchronized (newSones) {
1474                                 for (String knownSoneId : knownSones) {
1475                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1476                                 }
1477                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1478                         }
1479
1480                         /* save known posts. */
1481                         int postCounter = 0;
1482                         synchronized (newPosts) {
1483                                 for (String knownPostId : knownPosts) {
1484                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1485                                 }
1486                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1487                         }
1488
1489                         /* save known replies. */
1490                         int replyCounter = 0;
1491                         synchronized (newReplies) {
1492                                 for (String knownReplyId : knownReplies) {
1493                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1494                                 }
1495                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1496                         }
1497
1498                         /* now save it. */
1499                         configuration.save();
1500
1501                 } catch (ConfigurationException ce1) {
1502                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1503                 }
1504         }
1505
1506         //
1507         // PRIVATE METHODS
1508         //
1509
1510         /**
1511          * Loads the configuration.
1512          */
1513         @SuppressWarnings("unchecked")
1514         private void loadConfiguration() {
1515                 /* create options. */
1516                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1517
1518                         @Override
1519                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1520                                 SoneInserter.setInsertionDelay(newValue);
1521                         }
1522
1523                 }));
1524                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1525                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1526                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1527
1528                 /* read options from configuration. */
1529                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1530                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1531                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1532                 options.getBooleanOption("ClearOnNextRestart").set(null);
1533                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1534                 if (clearConfiguration) {
1535                         /* stop loading the configuration. */
1536                         return;
1537                 }
1538
1539                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1540                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1541
1542                 /* load known Sones. */
1543                 int soneCounter = 0;
1544                 while (true) {
1545                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1546                         if (knownSoneId == null) {
1547                                 break;
1548                         }
1549                         synchronized (newSones) {
1550                                 knownSones.add(knownSoneId);
1551                         }
1552                 }
1553
1554                 /* load known posts. */
1555                 int postCounter = 0;
1556                 while (true) {
1557                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1558                         if (knownPostId == null) {
1559                                 break;
1560                         }
1561                         synchronized (newPosts) {
1562                                 knownPosts.add(knownPostId);
1563                         }
1564                 }
1565
1566                 /* load known replies. */
1567                 int replyCounter = 0;
1568                 while (true) {
1569                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1570                         if (knownReplyId == null) {
1571                                 break;
1572                         }
1573                         synchronized (newReplies) {
1574                                 knownReplies.add(knownReplyId);
1575                         }
1576                 }
1577
1578         }
1579
1580         /**
1581          * Generate a Sone URI from the given URI and latest edition.
1582          *
1583          * @param uriString
1584          *            The URI to derive the Sone URI from
1585          * @return The derived URI
1586          */
1587         private FreenetURI getSoneUri(String uriString) {
1588                 try {
1589                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1590                         return uri;
1591                 } catch (MalformedURLException mue1) {
1592                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1593                         return null;
1594                 }
1595         }
1596
1597         //
1598         // INTERFACE IdentityListener
1599         //
1600
1601         /**
1602          * {@inheritDoc}
1603          */
1604         @Override
1605         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1606                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1607                 if (ownIdentity.hasContext("Sone")) {
1608                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1609                         addLocalSone(ownIdentity);
1610                 }
1611         }
1612
1613         /**
1614          * {@inheritDoc}
1615          */
1616         @Override
1617         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1618                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1619                 trustedIdentities.remove(ownIdentity);
1620         }
1621
1622         /**
1623          * {@inheritDoc}
1624          */
1625         @Override
1626         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1627                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1628                 trustedIdentities.get(ownIdentity).add(identity);
1629                 addRemoteSone(identity);
1630         }
1631
1632         /**
1633          * {@inheritDoc}
1634          */
1635         @Override
1636         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1637                 new Thread(new Runnable() {
1638
1639                         @Override
1640                         @SuppressWarnings("synthetic-access")
1641                         public void run() {
1642                                 Sone sone = getRemoteSone(identity.getId());
1643                                 soneDownloader.fetchSone(sone);
1644                         }
1645                 }).start();
1646         }
1647
1648         /**
1649          * {@inheritDoc}
1650          */
1651         @Override
1652         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1653                 trustedIdentities.get(ownIdentity).remove(identity);
1654         }
1655
1656 }