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