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