Load and save images when loading and saving Sones.
[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 images. */
1369                 int imageCounter = 0;
1370                 while (true) {
1371                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1372                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1373                         if (imageId == null) {
1374                                 break;
1375                         }
1376                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1377                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1378                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1379                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1380                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1381                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1382                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1383                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1384                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1385                                 return;
1386                         }
1387                         Album album = getAlbum(albumId, false);
1388                         if (album == null) {
1389                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1390                                 return;
1391                         }
1392                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1393                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1394                         album.addImage(image);
1395                 }
1396
1397                 /* load options. */
1398                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1399                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1400
1401                 /* if we’re still here, Sone was loaded successfully. */
1402                 synchronized (sone) {
1403                         sone.setTime(soneTime);
1404                         sone.setProfile(profile);
1405                         sone.setPosts(posts);
1406                         sone.setReplies(replies);
1407                         sone.setLikePostIds(likedPostIds);
1408                         sone.setLikeReplyIds(likedReplyIds);
1409                         sone.setFriends(friends);
1410                         sone.setAlbums(topLevelAlbums);
1411                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1412                 }
1413                 synchronized (newSones) {
1414                         for (String friend : friends) {
1415                                 knownSones.add(friend);
1416                         }
1417                 }
1418                 synchronized (newPosts) {
1419                         for (Post post : posts) {
1420                                 knownPosts.add(post.getId());
1421                         }
1422                 }
1423                 synchronized (newReplies) {
1424                         for (Reply reply : replies) {
1425                                 knownReplies.add(reply.getId());
1426                         }
1427                 }
1428         }
1429
1430         /**
1431          * Saves the given Sone. This will persist all local settings for the given
1432          * Sone, such as the friends list and similar, private options.
1433          *
1434          * @param sone
1435          *            The Sone to save
1436          */
1437         public synchronized void saveSone(Sone sone) {
1438                 if (!isLocalSone(sone)) {
1439                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1440                         return;
1441                 }
1442                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1443                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1444                         return;
1445                 }
1446
1447                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1448                 try {
1449                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1450
1451                         /* save Sone into configuration. */
1452                         String sonePrefix = "Sone/" + sone.getId();
1453                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1454                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1455
1456                         /* save profile. */
1457                         Profile profile = sone.getProfile();
1458                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1459                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1460                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1461                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1462                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1463                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1464
1465                         /* save profile fields. */
1466                         int fieldCounter = 0;
1467                         for (Field profileField : profile.getFields()) {
1468                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1469                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1470                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1471                         }
1472                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1473
1474                         /* save posts. */
1475                         int postCounter = 0;
1476                         for (Post post : sone.getPosts()) {
1477                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1478                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1479                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1480                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1481                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1482                         }
1483                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1484
1485                         /* save replies. */
1486                         int replyCounter = 0;
1487                         for (Reply reply : sone.getReplies()) {
1488                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1489                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1490                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1491                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1492                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1493                         }
1494                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1495
1496                         /* save post likes. */
1497                         int postLikeCounter = 0;
1498                         for (String postId : sone.getLikedPostIds()) {
1499                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1500                         }
1501                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1502
1503                         /* save reply likes. */
1504                         int replyLikeCounter = 0;
1505                         for (String replyId : sone.getLikedReplyIds()) {
1506                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1507                         }
1508                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1509
1510                         /* save friends. */
1511                         int friendCounter = 0;
1512                         for (String friendId : sone.getFriends()) {
1513                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1514                         }
1515                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1516
1517                         /* save albums. first, collect in a flat structure, top-level first. */
1518                         List<Album> albums = new ArrayList<Album>();
1519                         albums.addAll(sone.getAlbums());
1520                         int lastAlbumIndex = 0;
1521                         while (lastAlbumIndex < albums.size()) {
1522                                 int previousAlbumCount = albums.size();
1523                                 for (Album album : new ArrayList<Album>(albums.subList(lastAlbumIndex, albums.size()))) {
1524                                         albums.addAll(album.getAlbums());
1525                                 }
1526                                 lastAlbumIndex = previousAlbumCount;
1527                         }
1528
1529                         int albumCounter = 0;
1530                         for (Album album : albums) {
1531                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1532                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1533                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1534                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1535                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1536                         }
1537                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1538
1539                         /* save images. */
1540                         int imageCounter = 0;
1541                         for (Album album : albums) {
1542                                 for (Image image : album.getImages()) {
1543                                         if (!image.isInserted()) {
1544                                                 continue;
1545                                         }
1546                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1547                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1548                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1549                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1550                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1551                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1552                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1553                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1554                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1555                                 }
1556                         }
1557                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1558
1559                         /* save options. */
1560                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1561
1562                         configuration.save();
1563                         logger.log(Level.INFO, "Sone %s saved.", sone);
1564                 } catch (ConfigurationException ce1) {
1565                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1566                 } catch (WebOfTrustException wote1) {
1567                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1568                 }
1569         }
1570
1571         /**
1572          * Creates a new post.
1573          *
1574          * @param sone
1575          *            The Sone that creates the post
1576          * @param text
1577          *            The text of the post
1578          * @return The created post
1579          */
1580         public Post createPost(Sone sone, String text) {
1581                 return createPost(sone, System.currentTimeMillis(), text);
1582         }
1583
1584         /**
1585          * Creates a new post.
1586          *
1587          * @param sone
1588          *            The Sone that creates the post
1589          * @param time
1590          *            The time of the post
1591          * @param text
1592          *            The text of the post
1593          * @return The created post
1594          */
1595         public Post createPost(Sone sone, long time, String text) {
1596                 return createPost(sone, null, time, text);
1597         }
1598
1599         /**
1600          * Creates a new post.
1601          *
1602          * @param sone
1603          *            The Sone that creates the post
1604          * @param recipient
1605          *            The recipient Sone, or {@code null} if this post does not have
1606          *            a recipient
1607          * @param text
1608          *            The text of the post
1609          * @return The created post
1610          */
1611         public Post createPost(Sone sone, Sone recipient, String text) {
1612                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1613         }
1614
1615         /**
1616          * Creates a new post.
1617          *
1618          * @param sone
1619          *            The Sone that creates the post
1620          * @param recipient
1621          *            The recipient Sone, or {@code null} if this post does not have
1622          *            a recipient
1623          * @param time
1624          *            The time of the post
1625          * @param text
1626          *            The text of the post
1627          * @return The created post
1628          */
1629         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1630                 if (!isLocalSone(sone)) {
1631                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1632                         return null;
1633                 }
1634                 Post post = new Post(sone, time, text);
1635                 if (recipient != null) {
1636                         post.setRecipient(recipient);
1637                 }
1638                 synchronized (posts) {
1639                         posts.put(post.getId(), post);
1640                 }
1641                 synchronized (newPosts) {
1642                         knownPosts.add(post.getId());
1643                 }
1644                 sone.addPost(post);
1645                 saveSone(sone);
1646                 return post;
1647         }
1648
1649         /**
1650          * Deletes the given post.
1651          *
1652          * @param post
1653          *            The post to delete
1654          */
1655         public void deletePost(Post post) {
1656                 if (!isLocalSone(post.getSone())) {
1657                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1658                         return;
1659                 }
1660                 post.getSone().removePost(post);
1661                 synchronized (posts) {
1662                         posts.remove(post.getId());
1663                 }
1664                 saveSone(post.getSone());
1665         }
1666
1667         /**
1668          * Marks the given post as known, if it is currently a new post (according
1669          * to {@link #isNewPost(String)}).
1670          *
1671          * @param post
1672          *            The post to mark as known
1673          */
1674         public void markPostKnown(Post post) {
1675                 synchronized (newPosts) {
1676                         if (newPosts.remove(post.getId())) {
1677                                 knownPosts.add(post.getId());
1678                                 coreListenerManager.fireMarkPostKnown(post);
1679                                 saveConfiguration();
1680                         }
1681                 }
1682         }
1683
1684         /**
1685          * Bookmarks the given post.
1686          *
1687          * @param post
1688          *            The post to bookmark
1689          */
1690         public void bookmark(Post post) {
1691                 bookmarkPost(post.getId());
1692         }
1693
1694         /**
1695          * Bookmarks the post with the given ID.
1696          *
1697          * @param id
1698          *            The ID of the post to bookmark
1699          */
1700         public void bookmarkPost(String id) {
1701                 synchronized (bookmarkedPosts) {
1702                         bookmarkedPosts.add(id);
1703                 }
1704         }
1705
1706         /**
1707          * Removes the given post from the bookmarks.
1708          *
1709          * @param post
1710          *            The post to unbookmark
1711          */
1712         public void unbookmark(Post post) {
1713                 unbookmarkPost(post.getId());
1714         }
1715
1716         /**
1717          * Removes the post with the given ID from the bookmarks.
1718          *
1719          * @param id
1720          *            The ID of the post to unbookmark
1721          */
1722         public void unbookmarkPost(String id) {
1723                 synchronized (bookmarkedPosts) {
1724                         bookmarkedPosts.remove(id);
1725                 }
1726         }
1727
1728         /**
1729          * Creates a new reply.
1730          *
1731          * @param sone
1732          *            The Sone that creates the reply
1733          * @param post
1734          *            The post that this reply refers to
1735          * @param text
1736          *            The text of the reply
1737          * @return The created reply
1738          */
1739         public Reply createReply(Sone sone, Post post, String text) {
1740                 return createReply(sone, post, System.currentTimeMillis(), text);
1741         }
1742
1743         /**
1744          * Creates a new reply.
1745          *
1746          * @param sone
1747          *            The Sone that creates the reply
1748          * @param post
1749          *            The post that this reply refers to
1750          * @param time
1751          *            The time of the reply
1752          * @param text
1753          *            The text of the reply
1754          * @return The created reply
1755          */
1756         public Reply createReply(Sone sone, Post post, long time, String text) {
1757                 if (!isLocalSone(sone)) {
1758                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1759                         return null;
1760                 }
1761                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1762                 synchronized (replies) {
1763                         replies.put(reply.getId(), reply);
1764                 }
1765                 synchronized (newReplies) {
1766                         knownReplies.add(reply.getId());
1767                 }
1768                 sone.addReply(reply);
1769                 saveSone(sone);
1770                 return reply;
1771         }
1772
1773         /**
1774          * Deletes the given reply.
1775          *
1776          * @param reply
1777          *            The reply to delete
1778          */
1779         public void deleteReply(Reply reply) {
1780                 Sone sone = reply.getSone();
1781                 if (!isLocalSone(sone)) {
1782                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1783                         return;
1784                 }
1785                 synchronized (replies) {
1786                         replies.remove(reply.getId());
1787                 }
1788                 sone.removeReply(reply);
1789                 saveSone(sone);
1790         }
1791
1792         /**
1793          * Marks the given reply as known, if it is currently a new reply (according
1794          * to {@link #isNewReply(String)}).
1795          *
1796          * @param reply
1797          *            The reply to mark as known
1798          */
1799         public void markReplyKnown(Reply reply) {
1800                 synchronized (newReplies) {
1801                         if (newReplies.remove(reply.getId())) {
1802                                 knownReplies.add(reply.getId());
1803                                 coreListenerManager.fireMarkReplyKnown(reply);
1804                                 saveConfiguration();
1805                         }
1806                 }
1807         }
1808
1809         /**
1810          * Creates a new top-level album for the given Sone.
1811          *
1812          * @param sone
1813          *            The Sone to create the album for
1814          * @return The new album
1815          */
1816         public Album createAlbum(Sone sone) {
1817                 return createAlbum(sone, null);
1818         }
1819
1820         /**
1821          * Creates a new album for the given Sone.
1822          *
1823          * @param sone
1824          *            The Sone to create the album for
1825          * @param parent
1826          *            The parent of the album (may be {@code null} to create a
1827          *            top-level album)
1828          * @return The new album
1829          */
1830         public Album createAlbum(Sone sone, Album parent) {
1831                 Album album = new Album();
1832                 synchronized (albums) {
1833                         albums.put(album.getId(), album);
1834                 }
1835                 album.setSone(sone);
1836                 if (parent != null) {
1837                         parent.addAlbum(album);
1838                 } else {
1839                         sone.addAlbum(album);
1840                 }
1841                 return album;
1842         }
1843
1844         /**
1845          * Creates a new image.
1846          *
1847          * @param sone
1848          *            The Sone creating the image
1849          * @param album
1850          *            The album the image will be inserted into
1851          * @param temporaryImage
1852          *            The temporary image to create the image from
1853          * @return The newly created image
1854          */
1855         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1856                 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1857                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1858                 album.addImage(image);
1859                 synchronized (images) {
1860                         images.put(image.getId(), image);
1861                 }
1862                 return image;
1863         }
1864
1865         /**
1866          * Creates a new temporary image.
1867          *
1868          * @param mimeType
1869          *            The MIME type of the temporary image
1870          * @param imageData
1871          *            The encoded data of the image
1872          * @return The temporary image
1873          */
1874         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1875                 TemporaryImage temporaryImage = new TemporaryImage();
1876                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1877                 synchronized (temporaryImages) {
1878                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1879                 }
1880                 return temporaryImage;
1881         }
1882
1883         /**
1884          * Deletes the given temporary image.
1885          *
1886          * @param temporaryImage
1887          *            The temporary image to delete
1888          */
1889         public void deteleTemporaryImage(TemporaryImage temporaryImage) {
1890                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1891                 deleteTemporaryImage(temporaryImage.getId());
1892         }
1893
1894         /**
1895          * Deletes the temporary image with the given ID.
1896          *
1897          * @param imageId
1898          *            The ID of the temporary image to delete
1899          */
1900         public void deleteTemporaryImage(String imageId) {
1901                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1902                 synchronized (temporaryImages) {
1903                         temporaryImages.remove(imageId);
1904                 }
1905         }
1906
1907         /**
1908          * Starts the core.
1909          */
1910         public void start() {
1911                 loadConfiguration();
1912                 updateChecker.addUpdateListener(this);
1913                 updateChecker.start();
1914         }
1915
1916         /**
1917          * Stops the core.
1918          */
1919         public void stop() {
1920                 synchronized (localSones) {
1921                         for (SoneInserter soneInserter : soneInserters.values()) {
1922                                 soneInserter.stop();
1923                         }
1924                 }
1925                 updateChecker.stop();
1926                 updateChecker.removeUpdateListener(this);
1927                 soneDownloader.stop();
1928                 saveConfiguration();
1929                 stopped = true;
1930         }
1931
1932         /**
1933          * Saves the current options.
1934          */
1935         public void saveConfiguration() {
1936                 synchronized (configuration) {
1937                         if (storingConfiguration) {
1938                                 logger.log(Level.FINE, "Already storing configuration…");
1939                                 return;
1940                         }
1941                         storingConfiguration = true;
1942                 }
1943
1944                 /* store the options first. */
1945                 try {
1946                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1947                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1948                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1949                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1950                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1951                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1952                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1953                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1954
1955                         /* save known Sones. */
1956                         int soneCounter = 0;
1957                         synchronized (newSones) {
1958                                 for (String knownSoneId : knownSones) {
1959                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1960                                 }
1961                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1962                         }
1963
1964                         /* save known posts. */
1965                         int postCounter = 0;
1966                         synchronized (newPosts) {
1967                                 for (String knownPostId : knownPosts) {
1968                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1969                                 }
1970                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1971                         }
1972
1973                         /* save known replies. */
1974                         int replyCounter = 0;
1975                         synchronized (newReplies) {
1976                                 for (String knownReplyId : knownReplies) {
1977                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1978                                 }
1979                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1980                         }
1981
1982                         /* save bookmarked posts. */
1983                         int bookmarkedPostCounter = 0;
1984                         synchronized (bookmarkedPosts) {
1985                                 for (String bookmarkedPostId : bookmarkedPosts) {
1986                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1987                                 }
1988                         }
1989                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1990
1991                         /* now save it. */
1992                         configuration.save();
1993
1994                 } catch (ConfigurationException ce1) {
1995                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1996                 } finally {
1997                         synchronized (configuration) {
1998                                 storingConfiguration = false;
1999                         }
2000                 }
2001         }
2002
2003         //
2004         // PRIVATE METHODS
2005         //
2006
2007         /**
2008          * Loads the configuration.
2009          */
2010         @SuppressWarnings("unchecked")
2011         private void loadConfiguration() {
2012                 /* create options. */
2013                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
2014
2015                         @Override
2016                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2017                                 SoneInserter.setInsertionDelay(newValue);
2018                         }
2019
2020                 }));
2021                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
2022                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
2023                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2024                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2025                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2026                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2027
2028                 /* read options from configuration. */
2029                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2030                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2031                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2032                 options.getBooleanOption("ClearOnNextRestart").set(null);
2033                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2034                 if (clearConfiguration) {
2035                         /* stop loading the configuration. */
2036                         return;
2037                 }
2038
2039                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
2040                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
2041                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
2042                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2043                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2044
2045                 /* load known Sones. */
2046                 int soneCounter = 0;
2047                 while (true) {
2048                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2049                         if (knownSoneId == null) {
2050                                 break;
2051                         }
2052                         synchronized (newSones) {
2053                                 knownSones.add(knownSoneId);
2054                         }
2055                 }
2056
2057                 /* load known posts. */
2058                 int postCounter = 0;
2059                 while (true) {
2060                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2061                         if (knownPostId == null) {
2062                                 break;
2063                         }
2064                         synchronized (newPosts) {
2065                                 knownPosts.add(knownPostId);
2066                         }
2067                 }
2068
2069                 /* load known replies. */
2070                 int replyCounter = 0;
2071                 while (true) {
2072                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2073                         if (knownReplyId == null) {
2074                                 break;
2075                         }
2076                         synchronized (newReplies) {
2077                                 knownReplies.add(knownReplyId);
2078                         }
2079                 }
2080
2081                 /* load bookmarked posts. */
2082                 int bookmarkedPostCounter = 0;
2083                 while (true) {
2084                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2085                         if (bookmarkedPostId == null) {
2086                                 break;
2087                         }
2088                         synchronized (bookmarkedPosts) {
2089                                 bookmarkedPosts.add(bookmarkedPostId);
2090                         }
2091                 }
2092
2093         }
2094
2095         /**
2096          * Generate a Sone URI from the given URI and latest edition.
2097          *
2098          * @param uriString
2099          *            The URI to derive the Sone URI from
2100          * @return The derived URI
2101          */
2102         private FreenetURI getSoneUri(String uriString) {
2103                 try {
2104                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2105                         return uri;
2106                 } catch (MalformedURLException mue1) {
2107                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2108                         return null;
2109                 }
2110         }
2111
2112         //
2113         // INTERFACE IdentityListener
2114         //
2115
2116         /**
2117          * {@inheritDoc}
2118          */
2119         @Override
2120         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2121                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2122                 if (ownIdentity.hasContext("Sone")) {
2123                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2124                         addLocalSone(ownIdentity);
2125                 }
2126         }
2127
2128         /**
2129          * {@inheritDoc}
2130          */
2131         @Override
2132         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2133                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2134                 trustedIdentities.remove(ownIdentity);
2135         }
2136
2137         /**
2138          * {@inheritDoc}
2139          */
2140         @Override
2141         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2142                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2143                 trustedIdentities.get(ownIdentity).add(identity);
2144                 addRemoteSone(identity);
2145         }
2146
2147         /**
2148          * {@inheritDoc}
2149          */
2150         @Override
2151         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2152                 new Thread(new Runnable() {
2153
2154                         @Override
2155                         @SuppressWarnings("synthetic-access")
2156                         public void run() {
2157                                 Sone sone = getRemoteSone(identity.getId());
2158                                 sone.setIdentity(identity);
2159                                 soneDownloader.addSone(sone);
2160                                 soneDownloader.fetchSone(sone);
2161                         }
2162                 }).start();
2163         }
2164
2165         /**
2166          * {@inheritDoc}
2167          */
2168         @Override
2169         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2170                 trustedIdentities.get(ownIdentity).remove(identity);
2171         }
2172
2173         //
2174         // INTERFACE UpdateListener
2175         //
2176
2177         /**
2178          * {@inheritDoc}
2179          */
2180         @Override
2181         public void updateFound(Version version, long releaseTime, long latestEdition) {
2182                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2183         }
2184
2185         /**
2186          * Convenience interface for external classes that want to access the core’s
2187          * configuration.
2188          *
2189          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2190          */
2191         public static class Preferences {
2192
2193                 /** The wrapped options. */
2194                 private final Options options;
2195
2196                 /**
2197                  * Creates a new preferences object wrapped around the given options.
2198                  *
2199                  * @param options
2200                  *            The options to wrap
2201                  */
2202                 public Preferences(Options options) {
2203                         this.options = options;
2204                 }
2205
2206                 /**
2207                  * Returns the insertion delay.
2208                  *
2209                  * @return The insertion delay
2210                  */
2211                 public int getInsertionDelay() {
2212                         return options.getIntegerOption("InsertionDelay").get();
2213                 }
2214
2215                 /**
2216                  * Sets the insertion delay
2217                  *
2218                  * @param insertionDelay
2219                  *            The new insertion delay, or {@code null} to restore it to
2220                  *            the default value
2221                  * @return This preferences
2222                  */
2223                 public Preferences setInsertionDelay(Integer insertionDelay) {
2224                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2225                         return this;
2226                 }
2227
2228                 /**
2229                  * Returns the positive trust.
2230                  *
2231                  * @return The positive trust
2232                  */
2233                 public int getPositiveTrust() {
2234                         return options.getIntegerOption("PositiveTrust").get();
2235                 }
2236
2237                 /**
2238                  * Sets the positive trust.
2239                  *
2240                  * @param positiveTrust
2241                  *            The new positive trust, or {@code null} to restore it to
2242                  *            the default vlaue
2243                  * @return This preferences
2244                  */
2245                 public Preferences setPositiveTrust(Integer positiveTrust) {
2246                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2247                         return this;
2248                 }
2249
2250                 /**
2251                  * Returns the negative trust.
2252                  *
2253                  * @return The negative trust
2254                  */
2255                 public int getNegativeTrust() {
2256                         return options.getIntegerOption("NegativeTrust").get();
2257                 }
2258
2259                 /**
2260                  * Sets the negative trust.
2261                  *
2262                  * @param negativeTrust
2263                  *            The negative trust, or {@code null} to restore it to the
2264                  *            default value
2265                  * @return The preferences
2266                  */
2267                 public Preferences setNegativeTrust(Integer negativeTrust) {
2268                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2269                         return this;
2270                 }
2271
2272                 /**
2273                  * Returns the trust comment. This is the comment that is set in the web
2274                  * of trust when a trust value is assigned to an identity.
2275                  *
2276                  * @return The trust comment
2277                  */
2278                 public String getTrustComment() {
2279                         return options.getStringOption("TrustComment").get();
2280                 }
2281
2282                 /**
2283                  * Sets the trust comment.
2284                  *
2285                  * @param trustComment
2286                  *            The trust comment, or {@code null} to restore it to the
2287                  *            default value
2288                  * @return This preferences
2289                  */
2290                 public Preferences setTrustComment(String trustComment) {
2291                         options.getStringOption("TrustComment").set(trustComment);
2292                         return this;
2293                 }
2294
2295                 /**
2296                  * Returns whether the rescue mode is active.
2297                  *
2298                  * @return {@code true} if the rescue mode is active, {@code false}
2299                  *         otherwise
2300                  */
2301                 public boolean isSoneRescueMode() {
2302                         return options.getBooleanOption("SoneRescueMode").get();
2303                 }
2304
2305                 /**
2306                  * Sets whether the rescue mode is active.
2307                  *
2308                  * @param soneRescueMode
2309                  *            {@code true} if the rescue mode is active, {@code false}
2310                  *            otherwise
2311                  * @return This preferences
2312                  */
2313                 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2314                         options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2315                         return this;
2316                 }
2317
2318                 /**
2319                  * Returns whether Sone should clear its settings on the next restart.
2320                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2321                  * to return {@code true} as well!
2322                  *
2323                  * @return {@code true} if Sone should clear its settings on the next
2324                  *         restart, {@code false} otherwise
2325                  */
2326                 public boolean isClearOnNextRestart() {
2327                         return options.getBooleanOption("ClearOnNextRestart").get();
2328                 }
2329
2330                 /**
2331                  * Sets whether Sone will clear its settings on the next restart.
2332                  *
2333                  * @param clearOnNextRestart
2334                  *            {@code true} if Sone should clear its settings on the next
2335                  *            restart, {@code false} otherwise
2336                  * @return This preferences
2337                  */
2338                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2339                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2340                         return this;
2341                 }
2342
2343                 /**
2344                  * Returns whether Sone should really clear its settings on next
2345                  * restart. This is a confirmation option that needs to be set in
2346                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2347                  * settings on the next restart.
2348                  *
2349                  * @return {@code true} if Sone should really clear its settings on the
2350                  *         next restart, {@code false} otherwise
2351                  */
2352                 public boolean isReallyClearOnNextRestart() {
2353                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2354                 }
2355
2356                 /**
2357                  * Sets whether Sone should really clear its settings on the next
2358                  * restart.
2359                  *
2360                  * @param reallyClearOnNextRestart
2361                  *            {@code true} if Sone should really clear its settings on
2362                  *            the next restart, {@code false} otherwise
2363                  * @return This preferences
2364                  */
2365                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2366                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2367                         return this;
2368                 }
2369
2370         }
2371
2372 }