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