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