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