Merge branch 'next' into profile-fields
[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.Map.Entry;
28 import java.util.Set;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sone.core.Options.DefaultOption;
33 import net.pterodactylus.sone.core.Options.Option;
34 import net.pterodactylus.sone.core.Options.OptionWatcher;
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         /**
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.getFieldNames().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(null);
1045                         if (fieldValue == null) {
1046                                 logger.log(Level.WARNING, "Invalid profile field found, aborting load!");
1047                                 return;
1048                         }
1049                         profile.addField(fieldName);
1050                         profile.setField(fieldName, fieldValue);
1051                 }
1052
1053                 /* load posts. */
1054                 Set<Post> posts = new HashSet<Post>();
1055                 while (true) {
1056                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1057                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1058                         if (postId == null) {
1059                                 break;
1060                         }
1061                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1062                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1063                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1064                         if ((postTime == 0) || (postText == null)) {
1065                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1066                                 return;
1067                         }
1068                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1069                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1070                                 post.setRecipient(getSone(postRecipientId));
1071                         }
1072                         posts.add(post);
1073                 }
1074
1075                 /* load replies. */
1076                 Set<Reply> replies = new HashSet<Reply>();
1077                 while (true) {
1078                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1079                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1080                         if (replyId == null) {
1081                                 break;
1082                         }
1083                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1084                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1085                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1086                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1087                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1088                                 return;
1089                         }
1090                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1091                 }
1092
1093                 /* load post likes. */
1094                 Set<String> likedPostIds = new HashSet<String>();
1095                 while (true) {
1096                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1097                         if (likedPostId == null) {
1098                                 break;
1099                         }
1100                         likedPostIds.add(likedPostId);
1101                 }
1102
1103                 /* load reply likes. */
1104                 Set<String> likedReplyIds = new HashSet<String>();
1105                 while (true) {
1106                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1107                         if (likedReplyId == null) {
1108                                 break;
1109                         }
1110                         likedReplyIds.add(likedReplyId);
1111                 }
1112
1113                 /* load friends. */
1114                 Set<String> friends = new HashSet<String>();
1115                 while (true) {
1116                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1117                         if (friendId == null) {
1118                                 break;
1119                         }
1120                         friends.add(friendId);
1121                 }
1122
1123                 /* if we’re still here, Sone was loaded successfully. */
1124                 synchronized (sone) {
1125                         sone.setTime(soneTime);
1126                         sone.setProfile(profile);
1127                         sone.setPosts(posts);
1128                         sone.setReplies(replies);
1129                         sone.setLikePostIds(likedPostIds);
1130                         sone.setLikeReplyIds(likedReplyIds);
1131                         sone.setFriends(friends);
1132                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1133                 }
1134                 synchronized (newSones) {
1135                         for (String friend : friends) {
1136                                 knownSones.add(friend);
1137                         }
1138                 }
1139                 synchronized (newPosts) {
1140                         for (Post post : posts) {
1141                                 knownPosts.add(post.getId());
1142                         }
1143                 }
1144                 synchronized (newReplies) {
1145                         for (Reply reply : replies) {
1146                                 knownReplies.add(reply.getId());
1147                         }
1148                 }
1149         }
1150
1151         /**
1152          * Saves the given Sone. This will persist all local settings for the given
1153          * Sone, such as the friends list and similar, private options.
1154          *
1155          * @param sone
1156          *            The Sone to save
1157          */
1158         public synchronized void saveSone(Sone sone) {
1159                 if (!isLocalSone(sone)) {
1160                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1161                         return;
1162                 }
1163                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1164                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1165                         return;
1166                 }
1167
1168                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1169                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1170                 try {
1171                         /* save Sone into configuration. */
1172                         String sonePrefix = "Sone/" + sone.getId();
1173                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1174                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1175
1176                         /* save profile. */
1177                         Profile profile = sone.getProfile();
1178                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1179                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1180                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1181                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1182                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1183                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1184
1185                         /* save profile fields. */
1186                         int fieldCounter = 0;
1187                         for (Entry<String, String> profileField : profile.getFields().entrySet()) {
1188                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1189                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getKey());
1190                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1191                         }
1192                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1193
1194                         /* save posts. */
1195                         int postCounter = 0;
1196                         for (Post post : sone.getPosts()) {
1197                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1198                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1199                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1200                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1201                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1202                         }
1203                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1204
1205                         /* save replies. */
1206                         int replyCounter = 0;
1207                         for (Reply reply : sone.getReplies()) {
1208                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1209                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1210                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1211                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1212                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1213                         }
1214                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1215
1216                         /* save post likes. */
1217                         int postLikeCounter = 0;
1218                         for (String postId : sone.getLikedPostIds()) {
1219                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1220                         }
1221                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1222
1223                         /* save reply likes. */
1224                         int replyLikeCounter = 0;
1225                         for (String replyId : sone.getLikedReplyIds()) {
1226                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1227                         }
1228                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1229
1230                         /* save friends. */
1231                         int friendCounter = 0;
1232                         for (String friendId : sone.getFriends()) {
1233                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1234                         }
1235                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1236
1237                         configuration.save();
1238                         logger.log(Level.INFO, "Sone %s saved.", sone);
1239                 } catch (ConfigurationException ce1) {
1240                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1241                 }
1242         }
1243
1244         /**
1245          * Creates a new post.
1246          *
1247          * @param sone
1248          *            The Sone that creates the post
1249          * @param text
1250          *            The text of the post
1251          * @return The created post
1252          */
1253         public Post createPost(Sone sone, String text) {
1254                 return createPost(sone, System.currentTimeMillis(), text);
1255         }
1256
1257         /**
1258          * Creates a new post.
1259          *
1260          * @param sone
1261          *            The Sone that creates the post
1262          * @param time
1263          *            The time of the post
1264          * @param text
1265          *            The text of the post
1266          * @return The created post
1267          */
1268         public Post createPost(Sone sone, long time, String text) {
1269                 return createPost(sone, null, time, text);
1270         }
1271
1272         /**
1273          * Creates a new post.
1274          *
1275          * @param sone
1276          *            The Sone that creates the post
1277          * @param recipient
1278          *            The recipient Sone, or {@code null} if this post does not have
1279          *            a recipient
1280          * @param text
1281          *            The text of the post
1282          * @return The created post
1283          */
1284         public Post createPost(Sone sone, Sone recipient, String text) {
1285                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1286         }
1287
1288         /**
1289          * Creates a new post.
1290          *
1291          * @param sone
1292          *            The Sone that creates the post
1293          * @param recipient
1294          *            The recipient Sone, or {@code null} if this post does not have
1295          *            a recipient
1296          * @param time
1297          *            The time of the post
1298          * @param text
1299          *            The text of the post
1300          * @return The created post
1301          */
1302         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1303                 if (!isLocalSone(sone)) {
1304                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1305                         return null;
1306                 }
1307                 Post post = new Post(sone, time, text);
1308                 if (recipient != null) {
1309                         post.setRecipient(recipient);
1310                 }
1311                 synchronized (posts) {
1312                         posts.put(post.getId(), post);
1313                 }
1314                 synchronized (newPosts) {
1315                         knownPosts.add(post.getId());
1316                 }
1317                 sone.addPost(post);
1318                 saveSone(sone);
1319                 return post;
1320         }
1321
1322         /**
1323          * Deletes the given post.
1324          *
1325          * @param post
1326          *            The post to delete
1327          */
1328         public void deletePost(Post post) {
1329                 if (!isLocalSone(post.getSone())) {
1330                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1331                         return;
1332                 }
1333                 post.getSone().removePost(post);
1334                 synchronized (posts) {
1335                         posts.remove(post.getId());
1336                 }
1337                 saveSone(post.getSone());
1338         }
1339
1340         /**
1341          * Marks the given post as known, if it is currently a new post (according
1342          * to {@link #isNewPost(String)}).
1343          *
1344          * @param post
1345          *            The post to mark as known
1346          */
1347         public void markPostKnown(Post post) {
1348                 synchronized (newPosts) {
1349                         if (newPosts.remove(post.getId())) {
1350                                 knownPosts.add(post.getId());
1351                                 coreListenerManager.fireMarkPostKnown(post);
1352                                 saveConfiguration();
1353                         }
1354                 }
1355         }
1356
1357         /**
1358          * Creates a new reply.
1359          *
1360          * @param sone
1361          *            The Sone that creates the reply
1362          * @param post
1363          *            The post that this reply refers to
1364          * @param text
1365          *            The text of the reply
1366          * @return The created reply
1367          */
1368         public Reply createReply(Sone sone, Post post, String text) {
1369                 return createReply(sone, post, System.currentTimeMillis(), text);
1370         }
1371
1372         /**
1373          * Creates a new reply.
1374          *
1375          * @param sone
1376          *            The Sone that creates the reply
1377          * @param post
1378          *            The post that this reply refers to
1379          * @param time
1380          *            The time of the reply
1381          * @param text
1382          *            The text of the reply
1383          * @return The created reply
1384          */
1385         public Reply createReply(Sone sone, Post post, long time, String text) {
1386                 if (!isLocalSone(sone)) {
1387                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1388                         return null;
1389                 }
1390                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1391                 synchronized (replies) {
1392                         replies.put(reply.getId(), reply);
1393                 }
1394                 synchronized (newReplies) {
1395                         knownReplies.add(reply.getId());
1396                 }
1397                 sone.addReply(reply);
1398                 saveSone(sone);
1399                 return reply;
1400         }
1401
1402         /**
1403          * Deletes the given reply.
1404          *
1405          * @param reply
1406          *            The reply to delete
1407          */
1408         public void deleteReply(Reply reply) {
1409                 Sone sone = reply.getSone();
1410                 if (!isLocalSone(sone)) {
1411                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1412                         return;
1413                 }
1414                 synchronized (replies) {
1415                         replies.remove(reply.getId());
1416                 }
1417                 sone.removeReply(reply);
1418                 saveSone(sone);
1419         }
1420
1421         /**
1422          * Marks the given reply as known, if it is currently a new reply (according
1423          * to {@link #isNewReply(String)}).
1424          *
1425          * @param reply
1426          *            The reply to mark as known
1427          */
1428         public void markReplyKnown(Reply reply) {
1429                 synchronized (newReplies) {
1430                         if (newReplies.remove(reply.getId())) {
1431                                 knownReplies.add(reply.getId());
1432                                 coreListenerManager.fireMarkReplyKnown(reply);
1433                                 saveConfiguration();
1434                         }
1435                 }
1436         }
1437
1438         /**
1439          * Starts the core.
1440          */
1441         public void start() {
1442                 loadConfiguration();
1443                 updateChecker.addUpdateListener(this);
1444                 updateChecker.start();
1445         }
1446
1447         /**
1448          * Stops the core.
1449          */
1450         public void stop() {
1451                 synchronized (localSones) {
1452                         for (SoneInserter soneInserter : soneInserters.values()) {
1453                                 soneInserter.stop();
1454                         }
1455                 }
1456                 updateChecker.stop();
1457                 updateChecker.removeUpdateListener(this);
1458                 soneDownloader.stop();
1459                 saveConfiguration();
1460                 stopped = true;
1461         }
1462
1463         /**
1464          * Saves the current options.
1465          */
1466         public void saveConfiguration() {
1467                 synchronized (configuration) {
1468                         if (storingConfiguration) {
1469                                 logger.log(Level.FINE, "Already storing configuration…");
1470                                 return;
1471                         }
1472                         storingConfiguration = true;
1473                 }
1474
1475                 /* store the options first. */
1476                 try {
1477                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1478                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1479                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1480                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1481                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1482
1483                         /* save known Sones. */
1484                         int soneCounter = 0;
1485                         synchronized (newSones) {
1486                                 for (String knownSoneId : knownSones) {
1487                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1488                                 }
1489                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1490                         }
1491
1492                         /* save known posts. */
1493                         int postCounter = 0;
1494                         synchronized (newPosts) {
1495                                 for (String knownPostId : knownPosts) {
1496                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1497                                 }
1498                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1499                         }
1500
1501                         /* save known replies. */
1502                         int replyCounter = 0;
1503                         synchronized (newReplies) {
1504                                 for (String knownReplyId : knownReplies) {
1505                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1506                                 }
1507                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1508                         }
1509
1510                         /* now save it. */
1511                         configuration.save();
1512
1513                 } catch (ConfigurationException ce1) {
1514                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1515                 } finally {
1516                         synchronized (configuration) {
1517                                 storingConfiguration = false;
1518                         }
1519                 }
1520         }
1521
1522         //
1523         // PRIVATE METHODS
1524         //
1525
1526         /**
1527          * Loads the configuration.
1528          */
1529         @SuppressWarnings("unchecked")
1530         private void loadConfiguration() {
1531                 /* create options. */
1532                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1533
1534                         @Override
1535                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1536                                 SoneInserter.setInsertionDelay(newValue);
1537                         }
1538
1539                 }));
1540                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1541                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1542                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1543
1544                 /* read options from configuration. */
1545                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1546                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1547                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1548                 options.getBooleanOption("ClearOnNextRestart").set(null);
1549                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1550                 if (clearConfiguration) {
1551                         /* stop loading the configuration. */
1552                         return;
1553                 }
1554
1555                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1556                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1557
1558                 /* load known Sones. */
1559                 int soneCounter = 0;
1560                 while (true) {
1561                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1562                         if (knownSoneId == null) {
1563                                 break;
1564                         }
1565                         synchronized (newSones) {
1566                                 knownSones.add(knownSoneId);
1567                         }
1568                 }
1569
1570                 /* load known posts. */
1571                 int postCounter = 0;
1572                 while (true) {
1573                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1574                         if (knownPostId == null) {
1575                                 break;
1576                         }
1577                         synchronized (newPosts) {
1578                                 knownPosts.add(knownPostId);
1579                         }
1580                 }
1581
1582                 /* load known replies. */
1583                 int replyCounter = 0;
1584                 while (true) {
1585                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1586                         if (knownReplyId == null) {
1587                                 break;
1588                         }
1589                         synchronized (newReplies) {
1590                                 knownReplies.add(knownReplyId);
1591                         }
1592                 }
1593
1594         }
1595
1596         /**
1597          * Generate a Sone URI from the given URI and latest edition.
1598          *
1599          * @param uriString
1600          *            The URI to derive the Sone URI from
1601          * @return The derived URI
1602          */
1603         private FreenetURI getSoneUri(String uriString) {
1604                 try {
1605                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1606                         return uri;
1607                 } catch (MalformedURLException mue1) {
1608                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1609                         return null;
1610                 }
1611         }
1612
1613         //
1614         // INTERFACE IdentityListener
1615         //
1616
1617         /**
1618          * {@inheritDoc}
1619          */
1620         @Override
1621         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1622                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1623                 if (ownIdentity.hasContext("Sone")) {
1624                         addLocalSone(ownIdentity);
1625                 }
1626         }
1627
1628         /**
1629          * {@inheritDoc}
1630          */
1631         @Override
1632         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1633                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1634         }
1635
1636         /**
1637          * {@inheritDoc}
1638          */
1639         @Override
1640         public void identityAdded(Identity identity) {
1641                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1642                 addRemoteSone(identity);
1643         }
1644
1645         /**
1646          * {@inheritDoc}
1647          */
1648         @Override
1649         public void identityUpdated(final Identity identity) {
1650                 new Thread(new Runnable() {
1651
1652                         @Override
1653                         @SuppressWarnings("synthetic-access")
1654                         public void run() {
1655                                 Sone sone = getRemoteSone(identity.getId());
1656                                 soneDownloader.fetchSone(sone);
1657                         }
1658                 }).start();
1659         }
1660
1661         /**
1662          * {@inheritDoc}
1663          */
1664         @Override
1665         public void identityRemoved(Identity identity) {
1666                 /* TODO */
1667         }
1668
1669         //
1670         // INTERFACE UpdateListener
1671         //
1672
1673         /**
1674          * {@inheritDoc}
1675          */
1676         @Override
1677         public void updateFound(Version version, long releaseTime) {
1678                 coreListenerManager.fireUpdateFound(version, releaseTime);
1679         }
1680
1681 }