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