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