Convert “Sone unlocked” into EventBus-based event.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2012 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.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.PostRemovedEvent;
45 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
46 import net.pterodactylus.sone.core.event.SoneLockedEvent;
47 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
48 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
49 import net.pterodactylus.sone.data.Album;
50 import net.pterodactylus.sone.data.Client;
51 import net.pterodactylus.sone.data.Image;
52 import net.pterodactylus.sone.data.Post;
53 import net.pterodactylus.sone.data.PostReply;
54 import net.pterodactylus.sone.data.Profile;
55 import net.pterodactylus.sone.data.Profile.Field;
56 import net.pterodactylus.sone.data.Reply;
57 import net.pterodactylus.sone.data.Sone;
58 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
59 import net.pterodactylus.sone.data.Sone.SoneStatus;
60 import net.pterodactylus.sone.data.TemporaryImage;
61 import net.pterodactylus.sone.data.impl.PostImpl;
62 import net.pterodactylus.sone.fcp.FcpInterface;
63 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
64 import net.pterodactylus.sone.freenet.wot.Identity;
65 import net.pterodactylus.sone.freenet.wot.IdentityListener;
66 import net.pterodactylus.sone.freenet.wot.IdentityManager;
67 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
68 import net.pterodactylus.sone.main.SonePlugin;
69 import net.pterodactylus.util.config.Configuration;
70 import net.pterodactylus.util.config.ConfigurationException;
71 import net.pterodactylus.util.logging.Logging;
72 import net.pterodactylus.util.number.Numbers;
73 import net.pterodactylus.util.service.AbstractService;
74 import net.pterodactylus.util.thread.NamedThreadFactory;
75 import net.pterodactylus.util.thread.Ticker;
76 import net.pterodactylus.util.validation.EqualityValidator;
77 import net.pterodactylus.util.validation.IntegerRangeValidator;
78 import net.pterodactylus.util.validation.OrValidator;
79 import net.pterodactylus.util.validation.Validation;
80 import net.pterodactylus.util.version.Version;
81
82 import com.google.common.base.Predicate;
83 import com.google.common.collect.Collections2;
84 import com.google.common.eventbus.EventBus;
85 import com.google.inject.Inject;
86
87 import freenet.keys.FreenetURI;
88
89 /**
90  * The Sone core.
91  *
92  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
93  */
94 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
95
96         /** The logger. */
97         private static final Logger logger = Logging.getLogger(Core.class);
98
99         /** The start time. */
100         private final long startupTime = System.currentTimeMillis();
101
102         /** The options. */
103         private final Options options = new Options();
104
105         /** The preferences. */
106         private final Preferences preferences = new Preferences(options);
107
108         /** The core listener manager. */
109         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
110
111         /** The event bus. */
112         private final EventBus eventBus;
113
114         /** The configuration. */
115         private Configuration configuration;
116
117         /** Whether we’re currently saving the configuration. */
118         private boolean storingConfiguration = false;
119
120         /** The identity manager. */
121         private final IdentityManager identityManager;
122
123         /** Interface to freenet. */
124         private final FreenetInterface freenetInterface;
125
126         /** The Sone downloader. */
127         private final SoneDownloader soneDownloader;
128
129         /** The image inserter. */
130         private final ImageInserter imageInserter;
131
132         /** Sone downloader thread-pool. */
133         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
134
135         /** The update checker. */
136         private final UpdateChecker updateChecker;
137
138         /** The trust updater. */
139         private final WebOfTrustUpdater webOfTrustUpdater;
140
141         /** The FCP interface. */
142         private volatile FcpInterface fcpInterface;
143
144         /** The times Sones were followed. */
145         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
146
147         /** Locked local Sones. */
148         /* synchronize on itself. */
149         private final Set<Sone> lockedSones = new HashSet<Sone>();
150
151         /** Sone inserters. */
152         /* synchronize access on this on sones. */
153         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
154
155         /** Sone rescuers. */
156         /* synchronize access on this on sones. */
157         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
158
159         /** All Sones. */
160         /* synchronize access on this on itself. */
161         private final Map<String, Sone> sones = new HashMap<String, Sone>();
162
163         /** All known Sones. */
164         private final Set<String> knownSones = new HashSet<String>();
165
166         /** All posts. */
167         private final Map<String, Post> posts = new HashMap<String, Post>();
168
169         /** All known posts. */
170         private final Set<String> knownPosts = new HashSet<String>();
171
172         /** All replies. */
173         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
174
175         /** All known replies. */
176         private final Set<String> knownReplies = new HashSet<String>();
177
178         /** All bookmarked posts. */
179         /* synchronize access on itself. */
180         private final Set<String> bookmarkedPosts = new HashSet<String>();
181
182         /** Trusted identities, sorted by own identities. */
183         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
184
185         /** All known albums. */
186         private final Map<String, Album> albums = new HashMap<String, Album>();
187
188         /** All known images. */
189         private final Map<String, Image> images = new HashMap<String, Image>();
190
191         /** All temporary images. */
192         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
193
194         /** Ticker for threads that mark own elements as known. */
195         private final Ticker localElementTicker = new Ticker();
196
197         /** The time the configuration was last touched. */
198         private volatile long lastConfigurationUpdate;
199
200         /**
201          * Creates a new core.
202          *
203          * @param configuration
204          *            The configuration of the core
205          * @param freenetInterface
206          *            The freenet interface
207          * @param identityManager
208          *            The identity manager
209          * @param webOfTrustUpdater
210          *            The WebOfTrust updater
211          * @param eventBus
212          *            The event bus
213          */
214         @Inject
215         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
216                 super("Sone Core");
217                 this.configuration = configuration;
218                 this.freenetInterface = freenetInterface;
219                 this.identityManager = identityManager;
220                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
221                 this.imageInserter = new ImageInserter(this, freenetInterface);
222                 this.updateChecker = new UpdateChecker(freenetInterface);
223                 this.webOfTrustUpdater = webOfTrustUpdater;
224                 this.eventBus = eventBus;
225         }
226
227         //
228         // LISTENER MANAGEMENT
229         //
230
231         /**
232          * Adds a new core listener.
233          *
234          * @param coreListener
235          *            The listener to add
236          */
237         public void addCoreListener(CoreListener coreListener) {
238                 coreListenerManager.addListener(coreListener);
239         }
240
241         /**
242          * Removes a core listener.
243          *
244          * @param coreListener
245          *            The listener to remove
246          */
247         public void removeCoreListener(CoreListener coreListener) {
248                 coreListenerManager.removeListener(coreListener);
249         }
250
251         //
252         // ACCESSORS
253         //
254
255         /**
256          * Returns the time Sone was started.
257          *
258          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
259          */
260         public long getStartupTime() {
261                 return startupTime;
262         }
263
264         /**
265          * Sets the configuration to use. This will automatically save the current
266          * configuration to the given configuration.
267          *
268          * @param configuration
269          *            The new configuration to use
270          */
271         public void setConfiguration(Configuration configuration) {
272                 this.configuration = configuration;
273                 touchConfiguration();
274         }
275
276         /**
277          * Returns the options used by the core.
278          *
279          * @return The options of the core
280          */
281         public Preferences getPreferences() {
282                 return preferences;
283         }
284
285         /**
286          * Returns the identity manager used by the core.
287          *
288          * @return The identity manager
289          */
290         public IdentityManager getIdentityManager() {
291                 return identityManager;
292         }
293
294         /**
295          * Returns the update checker.
296          *
297          * @return The update checker
298          */
299         public UpdateChecker getUpdateChecker() {
300                 return updateChecker;
301         }
302
303         /**
304          * Sets the FCP interface to use.
305          *
306          * @param fcpInterface
307          *            The FCP interface to use
308          */
309         public void setFcpInterface(FcpInterface fcpInterface) {
310                 this.fcpInterface = fcpInterface;
311         }
312
313         /**
314          * Returns the Sone rescuer for the given local Sone.
315          *
316          * @param sone
317          *            The local Sone to get the rescuer for
318          * @return The Sone rescuer for the given Sone
319          */
320         public SoneRescuer getSoneRescuer(Sone sone) {
321                 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
322                 synchronized (sones) {
323                         SoneRescuer soneRescuer = soneRescuers.get(sone);
324                         if (soneRescuer == null) {
325                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
326                                 soneRescuers.put(sone, soneRescuer);
327                                 soneRescuer.start();
328                         }
329                         return soneRescuer;
330                 }
331         }
332
333         /**
334          * Returns whether the given Sone is currently locked.
335          *
336          * @param sone
337          *            The sone to check
338          * @return {@code true} if the Sone is locked, {@code false} if it is not
339          */
340         public boolean isLocked(Sone sone) {
341                 synchronized (lockedSones) {
342                         return lockedSones.contains(sone);
343                 }
344         }
345
346         /**
347          * Returns all Sones, remote and local.
348          *
349          * @return All Sones
350          */
351         public Set<Sone> getSones() {
352                 return new HashSet<Sone>(sones.values());
353         }
354
355         /**
356          * Returns the Sone with the given ID, regardless whether it’s local or
357          * remote.
358          *
359          * @param id
360          *            The ID of the Sone to get
361          * @return The Sone with the given ID, or {@code null} if there is no such
362          *         Sone
363          */
364         public Sone getSone(String id) {
365                 return getSone(id, true);
366         }
367
368         /**
369          * Returns the Sone with the given ID, regardless whether it’s local or
370          * remote.
371          *
372          * @param id
373          *            The ID of the Sone to get
374          * @param create
375          *            {@code true} to create a new Sone if none exists,
376          *            {@code false} to return {@code null} if a Sone with the given
377          *            ID does not exist
378          * @return The Sone with the given ID, or {@code null} if there is no such
379          *         Sone
380          */
381         @Override
382         public Sone getSone(String id, boolean create) {
383                 synchronized (sones) {
384                         if (!sones.containsKey(id)) {
385                                 Sone sone = new Sone(id, false);
386                                 sones.put(id, sone);
387                         }
388                         return sones.get(id);
389                 }
390         }
391
392         /**
393          * Checks whether the core knows a Sone with the given ID.
394          *
395          * @param id
396          *            The ID of the Sone
397          * @return {@code true} if there is a Sone with the given ID, {@code false}
398          *         otherwise
399          */
400         public boolean hasSone(String id) {
401                 synchronized (sones) {
402                         return sones.containsKey(id);
403                 }
404         }
405
406         /**
407          * Returns all local Sones.
408          *
409          * @return All local Sones
410          */
411         public Collection<Sone> getLocalSones() {
412                 synchronized (sones) {
413                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
414
415                                 @Override
416                                 public boolean apply(Sone sone) {
417                                         return sone.isLocal();
418                                 }
419                         });
420                 }
421         }
422
423         /**
424          * Returns the local Sone with the given ID, optionally creating a new Sone.
425          *
426          * @param id
427          *            The ID of the Sone
428          * @param create
429          *            {@code true} to create a new Sone if none exists,
430          *            {@code false} to return null if none exists
431          * @return The Sone with the given ID, or {@code null}
432          */
433         public Sone getLocalSone(String id, boolean create) {
434                 synchronized (sones) {
435                         Sone sone = sones.get(id);
436                         if ((sone == null) && create) {
437                                 sone = new Sone(id, true);
438                                 sones.put(id, sone);
439                         }
440                         if ((sone != null) && !sone.isLocal()) {
441                                 sone = new Sone(id, true);
442                                 sones.put(id, sone);
443                         }
444                         return sone;
445                 }
446         }
447
448         /**
449          * Returns all remote Sones.
450          *
451          * @return All remote Sones
452          */
453         public Collection<Sone> getRemoteSones() {
454                 synchronized (sones) {
455                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
456
457                                 @Override
458                                 public boolean apply(Sone sone) {
459                                         return !sone.isLocal();
460                                 }
461                         });
462                 }
463         }
464
465         /**
466          * Returns the remote Sone with the given ID.
467          *
468          * @param id
469          *            The ID of the remote Sone to get
470          * @param create
471          *            {@code true} to always create a Sone, {@code false} to return
472          *            {@code null} if no Sone with the given ID exists
473          * @return The Sone with the given ID
474          */
475         public Sone getRemoteSone(String id, boolean create) {
476                 synchronized (sones) {
477                         Sone sone = sones.get(id);
478                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
479                                 sone = new Sone(id, false);
480                                 sones.put(id, sone);
481                         }
482                         return sone;
483                 }
484         }
485
486         /**
487          * Returns whether the given Sone has been modified.
488          *
489          * @param sone
490          *            The Sone to check for modifications
491          * @return {@code true} if a modification has been detected in the Sone,
492          *         {@code false} otherwise
493          */
494         public boolean isModifiedSone(Sone sone) {
495                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
496         }
497
498         /**
499          * Returns the time when the given was first followed by any local Sone.
500          *
501          * @param sone
502          *            The Sone to get the time for
503          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
504          *         been followed, or {@link Long#MAX_VALUE}
505          */
506         public long getSoneFollowingTime(Sone sone) {
507                 synchronized (soneFollowingTimes) {
508                         if (soneFollowingTimes.containsKey(sone)) {
509                                 return soneFollowingTimes.get(sone);
510                         }
511                         return Long.MAX_VALUE;
512                 }
513         }
514
515         /**
516          * Returns whether the target Sone is trusted by the origin Sone.
517          *
518          * @param origin
519          *            The origin Sone
520          * @param target
521          *            The target Sone
522          * @return {@code true} if the target Sone is trusted by the origin Sone
523          */
524         public boolean isSoneTrusted(Sone origin, Sone target) {
525                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
526                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
527         }
528
529         /**
530          * Returns the post with the given ID.
531          *
532          * @param postId
533          *            The ID of the post to get
534          * @return The post with the given ID, or a new post with the given ID
535          */
536         public Post getPost(String postId) {
537                 return getPost(postId, true);
538         }
539
540         /**
541          * Returns the post with the given ID, optionally creating a new post.
542          *
543          * @param postId
544          *            The ID of the post to get
545          * @param create
546          *            {@code true} it create a new post if no post with the given ID
547          *            exists, {@code false} to return {@code null}
548          * @return The post, or {@code null} if there is no such post
549          */
550         @Override
551         public Post getPost(String postId, boolean create) {
552                 synchronized (posts) {
553                         Post post = posts.get(postId);
554                         if ((post == null) && create) {
555                                 post = new PostImpl(postId);
556                                 posts.put(postId, post);
557                         }
558                         return post;
559                 }
560         }
561
562         /**
563          * Returns all posts that have the given Sone as recipient.
564          *
565          * @see Post#getRecipient()
566          * @param recipient
567          *            The recipient of the posts
568          * @return All posts that have the given Sone as recipient
569          */
570         public Set<Post> getDirectedPosts(Sone recipient) {
571                 Validation.begin().isNotNull("Recipient", recipient).check();
572                 Set<Post> directedPosts = new HashSet<Post>();
573                 synchronized (posts) {
574                         for (Post post : posts.values()) {
575                                 if (recipient.equals(post.getRecipient())) {
576                                         directedPosts.add(post);
577                                 }
578                         }
579                 }
580                 return directedPosts;
581         }
582
583         /**
584          * Returns the reply with the given ID. If there is no reply with the given
585          * ID yet, a new one is created, unless {@code create} is false in which
586          * case {@code null} is returned.
587          *
588          * @param replyId
589          *            The ID of the reply to get
590          * @param create
591          *            {@code true} to always return a {@link Reply}, {@code false}
592          *            to return {@code null} if no reply can be found
593          * @return The reply, or {@code null} if there is no such reply
594          */
595         public PostReply getPostReply(String replyId, boolean create) {
596                 synchronized (replies) {
597                         PostReply reply = replies.get(replyId);
598                         if (create && (reply == null)) {
599                                 reply = new PostReply(replyId);
600                                 replies.put(replyId, reply);
601                         }
602                         return reply;
603                 }
604         }
605
606         /**
607          * Returns all replies for the given post, order ascending by time.
608          *
609          * @param post
610          *            The post to get all replies for
611          * @return All replies for the given post
612          */
613         public List<PostReply> getReplies(Post post) {
614                 Set<Sone> sones = getSones();
615                 List<PostReply> replies = new ArrayList<PostReply>();
616                 for (Sone sone : sones) {
617                         for (PostReply reply : sone.getReplies()) {
618                                 if (reply.getPost().equals(post)) {
619                                         replies.add(reply);
620                                 }
621                         }
622                 }
623                 Collections.sort(replies, Reply.TIME_COMPARATOR);
624                 return replies;
625         }
626
627         /**
628          * Returns all Sones that have liked the given post.
629          *
630          * @param post
631          *            The post to get the liking Sones for
632          * @return The Sones that like the given post
633          */
634         public Set<Sone> getLikes(Post post) {
635                 Set<Sone> sones = new HashSet<Sone>();
636                 for (Sone sone : getSones()) {
637                         if (sone.getLikedPostIds().contains(post.getId())) {
638                                 sones.add(sone);
639                         }
640                 }
641                 return sones;
642         }
643
644         /**
645          * Returns all Sones that have liked the given reply.
646          *
647          * @param reply
648          *            The reply to get the liking Sones for
649          * @return The Sones that like the given reply
650          */
651         public Set<Sone> getLikes(PostReply reply) {
652                 Set<Sone> sones = new HashSet<Sone>();
653                 for (Sone sone : getSones()) {
654                         if (sone.getLikedReplyIds().contains(reply.getId())) {
655                                 sones.add(sone);
656                         }
657                 }
658                 return sones;
659         }
660
661         /**
662          * Returns whether the given post is bookmarked.
663          *
664          * @param post
665          *            The post to check
666          * @return {@code true} if the given post is bookmarked, {@code false}
667          *         otherwise
668          */
669         public boolean isBookmarked(Post post) {
670                 return isPostBookmarked(post.getId());
671         }
672
673         /**
674          * Returns whether the post with the given ID is bookmarked.
675          *
676          * @param id
677          *            The ID of the post to check
678          * @return {@code true} if the post with the given ID is bookmarked,
679          *         {@code false} otherwise
680          */
681         public boolean isPostBookmarked(String id) {
682                 synchronized (bookmarkedPosts) {
683                         return bookmarkedPosts.contains(id);
684                 }
685         }
686
687         /**
688          * Returns all currently known bookmarked posts.
689          *
690          * @return All bookmarked posts
691          */
692         public Set<Post> getBookmarkedPosts() {
693                 Set<Post> posts = new HashSet<Post>();
694                 synchronized (bookmarkedPosts) {
695                         for (String bookmarkedPostId : bookmarkedPosts) {
696                                 Post post = getPost(bookmarkedPostId, false);
697                                 if (post != null) {
698                                         posts.add(post);
699                                 }
700                         }
701                 }
702                 return posts;
703         }
704
705         /**
706          * Returns the album with the given ID, creating a new album if no album
707          * with the given ID can be found.
708          *
709          * @param albumId
710          *            The ID of the album
711          * @return The album with the given ID
712          */
713         public Album getAlbum(String albumId) {
714                 return getAlbum(albumId, true);
715         }
716
717         /**
718          * Returns the album with the given ID, optionally creating a new album if
719          * an album with the given ID can not be found.
720          *
721          * @param albumId
722          *            The ID of the album
723          * @param create
724          *            {@code true} to create a new album if none exists for the
725          *            given ID
726          * @return The album with the given ID, or {@code null} if no album with the
727          *         given ID exists and {@code create} is {@code false}
728          */
729         public Album getAlbum(String albumId, boolean create) {
730                 synchronized (albums) {
731                         Album album = albums.get(albumId);
732                         if (create && (album == null)) {
733                                 album = new Album(albumId);
734                                 albums.put(albumId, album);
735                         }
736                         return album;
737                 }
738         }
739
740         /**
741          * Returns the image with the given ID, creating it if necessary.
742          *
743          * @param imageId
744          *            The ID of the image
745          * @return The image with the given ID
746          */
747         public Image getImage(String imageId) {
748                 return getImage(imageId, true);
749         }
750
751         /**
752          * Returns the image with the given ID, optionally creating it if it does
753          * not exist.
754          *
755          * @param imageId
756          *            The ID of the image
757          * @param create
758          *            {@code true} to create an image if none exists with the given
759          *            ID
760          * @return The image with the given ID, or {@code null} if none exists and
761          *         none was created
762          */
763         public Image getImage(String imageId, boolean create) {
764                 synchronized (images) {
765                         Image image = images.get(imageId);
766                         if (create && (image == null)) {
767                                 image = new Image(imageId);
768                                 images.put(imageId, image);
769                         }
770                         return image;
771                 }
772         }
773
774         /**
775          * Returns the temporary image with the given ID.
776          *
777          * @param imageId
778          *            The ID of the temporary image
779          * @return The temporary image, or {@code null} if there is no temporary
780          *         image with the given ID
781          */
782         public TemporaryImage getTemporaryImage(String imageId) {
783                 synchronized (temporaryImages) {
784                         return temporaryImages.get(imageId);
785                 }
786         }
787
788         //
789         // ACTIONS
790         //
791
792         /**
793          * Locks the given Sone. A locked Sone will not be inserted by
794          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
795          * again.
796          *
797          * @param sone
798          *            The sone to lock
799          */
800         public void lockSone(Sone sone) {
801                 synchronized (lockedSones) {
802                         if (lockedSones.add(sone)) {
803                                 eventBus.post(new SoneLockedEvent(sone));
804                         }
805                 }
806         }
807
808         /**
809          * Unlocks the given Sone.
810          *
811          * @see #lockSone(Sone)
812          * @param sone
813          *            The sone to unlock
814          */
815         public void unlockSone(Sone sone) {
816                 synchronized (lockedSones) {
817                         if (lockedSones.remove(sone)) {
818                                 eventBus.post(new SoneUnlockedEvent(sone));
819                         }
820                 }
821         }
822
823         /**
824          * Adds a local Sone from the given own identity.
825          *
826          * @param ownIdentity
827          *            The own identity to create a Sone from
828          * @return The added (or already existing) Sone
829          */
830         public Sone addLocalSone(OwnIdentity ownIdentity) {
831                 if (ownIdentity == null) {
832                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
833                         return null;
834                 }
835                 synchronized (sones) {
836                         final Sone sone;
837                         try {
838                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
839                         } catch (MalformedURLException mue1) {
840                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
841                                 return null;
842                         }
843                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
844                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
845                         sone.setKnown(true);
846                         /* TODO - load posts ’n stuff */
847                         sones.put(ownIdentity.getId(), sone);
848                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
849                         soneInserter.addSoneInsertListener(this);
850                         soneInserters.put(sone, soneInserter);
851                         sone.setStatus(SoneStatus.idle);
852                         loadSone(sone);
853                         soneInserter.start();
854                         return sone;
855                 }
856         }
857
858         /**
859          * Creates a new Sone for the given own identity.
860          *
861          * @param ownIdentity
862          *            The own identity to create a Sone for
863          * @return The created Sone
864          */
865         public Sone createSone(OwnIdentity ownIdentity) {
866                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
867                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
868                         return null;
869                 }
870                 Sone sone = addLocalSone(ownIdentity);
871                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
872                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
873                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
874                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
875                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
876                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
877
878                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
879                 touchConfiguration();
880                 return sone;
881         }
882
883         /**
884          * Adds the Sone of the given identity.
885          *
886          * @param identity
887          *            The identity whose Sone to add
888          * @return The added or already existing Sone
889          */
890         public Sone addRemoteSone(Identity identity) {
891                 if (identity == null) {
892                         logger.log(Level.WARNING, "Given Identity is null!");
893                         return null;
894                 }
895                 synchronized (sones) {
896                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
897                         boolean newSone = sone.getRequestUri() == null;
898                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
899                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
900                         if (newSone) {
901                                 synchronized (knownSones) {
902                                         newSone = !knownSones.contains(sone.getId());
903                                 }
904                                 sone.setKnown(!newSone);
905                                 if (newSone) {
906                                         eventBus.post(new NewSoneFoundEvent(sone));
907                                         for (Sone localSone : getLocalSones()) {
908                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
909                                                         followSone(localSone, sone);
910                                                 }
911                                         }
912                                 }
913                         }
914                         soneDownloader.addSone(sone);
915                         soneDownloaders.execute(new Runnable() {
916
917                                 @Override
918                                 @SuppressWarnings("synthetic-access")
919                                 public void run() {
920                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
921                                 }
922
923                         });
924                         return sone;
925                 }
926         }
927
928         /**
929          * Lets the given local Sone follow the Sone with the given ID.
930          *
931          * @param sone
932          *            The local Sone that should follow another Sone
933          * @param soneId
934          *            The ID of the Sone to follow
935          */
936         public void followSone(Sone sone, String soneId) {
937                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
938                 Sone followedSone = getSone(soneId, true);
939                 if (followedSone == null) {
940                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
941                         return;
942                 }
943                 followSone(sone, getSone(soneId));
944         }
945
946         /**
947          * Lets the given local Sone follow the other given Sone. If the given Sone
948          * was not followed by any local Sone before, this will mark all elements of
949          * the followed Sone as read that have been created before the current
950          * moment.
951          *
952          * @param sone
953          *            The local Sone that should follow the other Sone
954          * @param followedSone
955          *            The Sone that should be followed
956          */
957         public void followSone(Sone sone, Sone followedSone) {
958                 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
959                 sone.addFriend(followedSone.getId());
960                 synchronized (soneFollowingTimes) {
961                         if (!soneFollowingTimes.containsKey(followedSone)) {
962                                 long now = System.currentTimeMillis();
963                                 soneFollowingTimes.put(followedSone, now);
964                                 for (Post post : followedSone.getPosts()) {
965                                         if (post.getTime() < now) {
966                                                 markPostKnown(post);
967                                         }
968                                 }
969                                 for (PostReply reply : followedSone.getReplies()) {
970                                         if (reply.getTime() < now) {
971                                                 markReplyKnown(reply);
972                                         }
973                                 }
974                         }
975                 }
976                 touchConfiguration();
977         }
978
979         /**
980          * Lets the given local Sone unfollow the Sone with the given ID.
981          *
982          * @param sone
983          *            The local Sone that should unfollow another Sone
984          * @param soneId
985          *            The ID of the Sone being unfollowed
986          */
987         public void unfollowSone(Sone sone, String soneId) {
988                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
989                 unfollowSone(sone, getSone(soneId, false));
990         }
991
992         /**
993          * Lets the given local Sone unfollow the other given Sone. If the given
994          * local Sone is the last local Sone that followed the given Sone, its
995          * following time will be removed.
996          *
997          * @param sone
998          *            The local Sone that should unfollow another Sone
999          * @param unfollowedSone
1000          *            The Sone being unfollowed
1001          */
1002         public void unfollowSone(Sone sone, Sone unfollowedSone) {
1003                 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1004                 sone.removeFriend(unfollowedSone.getId());
1005                 boolean unfollowedSoneStillFollowed = false;
1006                 for (Sone localSone : getLocalSones()) {
1007                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1008                 }
1009                 if (!unfollowedSoneStillFollowed) {
1010                         synchronized (soneFollowingTimes) {
1011                                 soneFollowingTimes.remove(unfollowedSone);
1012                         }
1013                 }
1014                 touchConfiguration();
1015         }
1016
1017         /**
1018          * Sets the trust value of the given origin Sone for the target Sone.
1019          *
1020          * @param origin
1021          *            The origin Sone
1022          * @param target
1023          *            The target Sone
1024          * @param trustValue
1025          *            The trust value (from {@code -100} to {@code 100})
1026          */
1027         public void setTrust(Sone origin, Sone target, int trustValue) {
1028                 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();
1029                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1030         }
1031
1032         /**
1033          * Removes any trust assignment for the given target Sone.
1034          *
1035          * @param origin
1036          *            The trust origin
1037          * @param target
1038          *            The trust target
1039          */
1040         public void removeTrust(Sone origin, Sone target) {
1041                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1042                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1043         }
1044
1045         /**
1046          * Assigns the configured positive trust value for the given target.
1047          *
1048          * @param origin
1049          *            The trust origin
1050          * @param target
1051          *            The trust target
1052          */
1053         public void trustSone(Sone origin, Sone target) {
1054                 setTrust(origin, target, preferences.getPositiveTrust());
1055         }
1056
1057         /**
1058          * Assigns the configured negative trust value for the given target.
1059          *
1060          * @param origin
1061          *            The trust origin
1062          * @param target
1063          *            The trust target
1064          */
1065         public void distrustSone(Sone origin, Sone target) {
1066                 setTrust(origin, target, preferences.getNegativeTrust());
1067         }
1068
1069         /**
1070          * Removes the trust assignment for the given target.
1071          *
1072          * @param origin
1073          *            The trust origin
1074          * @param target
1075          *            The trust target
1076          */
1077         public void untrustSone(Sone origin, Sone target) {
1078                 removeTrust(origin, target);
1079         }
1080
1081         /**
1082          * Updates the stored Sone with the given Sone.
1083          *
1084          * @param sone
1085          *            The updated Sone
1086          */
1087         public void updateSone(Sone sone) {
1088                 updateSone(sone, false);
1089         }
1090
1091         /**
1092          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1093          * {@code true}, an older Sone than the current Sone can be given to restore
1094          * an old state.
1095          *
1096          * @param sone
1097          *            The Sone to update
1098          * @param soneRescueMode
1099          *            {@code true} if the stored Sone should be updated regardless
1100          *            of the age of the given Sone
1101          */
1102         public void updateSone(Sone sone, boolean soneRescueMode) {
1103                 if (hasSone(sone.getId())) {
1104                         Sone storedSone = getSone(sone.getId());
1105                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1106                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1107                                 return;
1108                         }
1109                         synchronized (posts) {
1110                                 if (!soneRescueMode) {
1111                                         for (Post post : storedSone.getPosts()) {
1112                                                 posts.remove(post.getId());
1113                                                 if (!sone.getPosts().contains(post)) {
1114                                                         eventBus.post(new PostRemovedEvent(post));
1115                                                 }
1116                                         }
1117                                 }
1118                                 List<Post> storedPosts = storedSone.getPosts();
1119                                 synchronized (knownPosts) {
1120                                         for (Post post : sone.getPosts()) {
1121                                                 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1122                                                 if (!storedPosts.contains(post)) {
1123                                                         if (post.getTime() < getSoneFollowingTime(sone)) {
1124                                                                 knownPosts.add(post.getId());
1125                                                                 post.setKnown(true);
1126                                                         } else if (!knownPosts.contains(post.getId())) {
1127                                                                 eventBus.post(new NewPostFoundEvent(post));
1128                                                         }
1129                                                 }
1130                                                 posts.put(post.getId(), post);
1131                                         }
1132                                 }
1133                         }
1134                         synchronized (replies) {
1135                                 if (!soneRescueMode) {
1136                                         for (PostReply reply : storedSone.getReplies()) {
1137                                                 replies.remove(reply.getId());
1138                                                 if (!sone.getReplies().contains(reply)) {
1139                                                         eventBus.post(new PostReplyRemovedEvent(reply));
1140                                                 }
1141                                         }
1142                                 }
1143                                 Set<PostReply> storedReplies = storedSone.getReplies();
1144                                 synchronized (knownReplies) {
1145                                         for (PostReply reply : sone.getReplies()) {
1146                                                 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1147                                                 if (!storedReplies.contains(reply)) {
1148                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1149                                                                 knownReplies.add(reply.getId());
1150                                                                 reply.setKnown(true);
1151                                                         } else if (!knownReplies.contains(reply.getId())) {
1152                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1153                                                         }
1154                                                 }
1155                                                 replies.put(reply.getId(), reply);
1156                                         }
1157                                 }
1158                         }
1159                         synchronized (albums) {
1160                                 synchronized (images) {
1161                                         for (Album album : storedSone.getAlbums()) {
1162                                                 albums.remove(album.getId());
1163                                                 for (Image image : album.getImages()) {
1164                                                         images.remove(image.getId());
1165                                                 }
1166                                         }
1167                                         for (Album album : sone.getAlbums()) {
1168                                                 albums.put(album.getId(), album);
1169                                                 for (Image image : album.getImages()) {
1170                                                         images.put(image.getId(), image);
1171                                                 }
1172                                         }
1173                                 }
1174                         }
1175                         synchronized (storedSone) {
1176                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1177                                         storedSone.setTime(sone.getTime());
1178                                 }
1179                                 storedSone.setClient(sone.getClient());
1180                                 storedSone.setProfile(sone.getProfile());
1181                                 if (soneRescueMode) {
1182                                         for (Post post : sone.getPosts()) {
1183                                                 storedSone.addPost(post);
1184                                         }
1185                                         for (PostReply reply : sone.getReplies()) {
1186                                                 storedSone.addReply(reply);
1187                                         }
1188                                         for (String likedPostId : sone.getLikedPostIds()) {
1189                                                 storedSone.addLikedPostId(likedPostId);
1190                                         }
1191                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1192                                                 storedSone.addLikedReplyId(likedReplyId);
1193                                         }
1194                                         for (Album album : sone.getAlbums()) {
1195                                                 storedSone.addAlbum(album);
1196                                         }
1197                                 } else {
1198                                         storedSone.setPosts(sone.getPosts());
1199                                         storedSone.setReplies(sone.getReplies());
1200                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1201                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1202                                         storedSone.setAlbums(sone.getAlbums());
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 #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1212          * 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, String.format("Tried to delete Sone of non-own identity: %s", sone));
1220                         return;
1221                 }
1222                 synchronized (sones) {
1223                         if (!getLocalSones().contains(sone)) {
1224                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1225                                 return;
1226                         }
1227                         sones.remove(sone.getId());
1228                         SoneInserter soneInserter = soneInserters.remove(sone);
1229                         soneInserter.removeSoneInsertListener(this);
1230                         soneInserter.stop();
1231                 }
1232                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1233                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1234                 try {
1235                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1236                 } catch (ConfigurationException ce1) {
1237                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1238                 }
1239         }
1240
1241         /**
1242          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1243          * known} before, a {@link MarkSoneKnownEvent} is fired.
1244          *
1245          * @param sone
1246          *            The Sone to mark as known
1247          */
1248         public void markSoneKnown(Sone sone) {
1249                 if (!sone.isKnown()) {
1250                         sone.setKnown(true);
1251                         synchronized (knownSones) {
1252                                 knownSones.add(sone.getId());
1253                         }
1254                         eventBus.post(new MarkSoneKnownEvent(sone));
1255                         touchConfiguration();
1256                 }
1257         }
1258
1259         /**
1260          * Loads and updates the given Sone from the configuration. If any error is
1261          * encountered, loading is aborted and the given Sone is not changed.
1262          *
1263          * @param sone
1264          *            The Sone to load and update
1265          */
1266         public void loadSone(Sone sone) {
1267                 if (!sone.isLocal()) {
1268                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1269                         return;
1270                 }
1271
1272                 /* initialize options. */
1273                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1274                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1275                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1276                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1277                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1278                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1279
1280                 /* load Sone. */
1281                 String sonePrefix = "Sone/" + sone.getId();
1282                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1283                 if (soneTime == null) {
1284                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1285                         return;
1286                 }
1287                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1288
1289                 /* load profile. */
1290                 Profile profile = new Profile(sone);
1291                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1292                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1293                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1294                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1295                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1296                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1297
1298                 /* load profile fields. */
1299                 while (true) {
1300                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1301                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1302                         if (fieldName == null) {
1303                                 break;
1304                         }
1305                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1306                         profile.addField(fieldName).setValue(fieldValue);
1307                 }
1308
1309                 /* load posts. */
1310                 Set<Post> posts = new HashSet<Post>();
1311                 while (true) {
1312                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1313                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1314                         if (postId == null) {
1315                                 break;
1316                         }
1317                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1318                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1319                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1320                         if ((postTime == 0) || (postText == null)) {
1321                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1322                                 return;
1323                         }
1324                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1325                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1326                                 post.setRecipient(getSone(postRecipientId));
1327                         }
1328                         posts.add(post);
1329                 }
1330
1331                 /* load replies. */
1332                 Set<PostReply> replies = new HashSet<PostReply>();
1333                 while (true) {
1334                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1335                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1336                         if (replyId == null) {
1337                                 break;
1338                         }
1339                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1340                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1341                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1342                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1343                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1344                                 return;
1345                         }
1346                         replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1347                 }
1348
1349                 /* load post likes. */
1350                 Set<String> likedPostIds = new HashSet<String>();
1351                 while (true) {
1352                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1353                         if (likedPostId == null) {
1354                                 break;
1355                         }
1356                         likedPostIds.add(likedPostId);
1357                 }
1358
1359                 /* load reply likes. */
1360                 Set<String> likedReplyIds = new HashSet<String>();
1361                 while (true) {
1362                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1363                         if (likedReplyId == null) {
1364                                 break;
1365                         }
1366                         likedReplyIds.add(likedReplyId);
1367                 }
1368
1369                 /* load friends. */
1370                 Set<String> friends = new HashSet<String>();
1371                 while (true) {
1372                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1373                         if (friendId == null) {
1374                                 break;
1375                         }
1376                         friends.add(friendId);
1377                 }
1378
1379                 /* load albums. */
1380                 List<Album> topLevelAlbums = new ArrayList<Album>();
1381                 int albumCounter = 0;
1382                 while (true) {
1383                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1384                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1385                         if (albumId == null) {
1386                                 break;
1387                         }
1388                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1389                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1390                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1391                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1392                         if ((albumTitle == null) || (albumDescription == null)) {
1393                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1394                                 return;
1395                         }
1396                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1397                         if (albumParentId != null) {
1398                                 Album parentAlbum = getAlbum(albumParentId, false);
1399                                 if (parentAlbum == null) {
1400                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1401                                         return;
1402                                 }
1403                                 parentAlbum.addAlbum(album);
1404                         } else {
1405                                 if (!topLevelAlbums.contains(album)) {
1406                                         topLevelAlbums.add(album);
1407                                 }
1408                         }
1409                 }
1410
1411                 /* load images. */
1412                 int imageCounter = 0;
1413                 while (true) {
1414                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1415                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1416                         if (imageId == null) {
1417                                 break;
1418                         }
1419                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1420                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1421                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1422                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1423                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1424                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1425                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1426                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1427                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1428                                 return;
1429                         }
1430                         Album album = getAlbum(albumId, false);
1431                         if (album == null) {
1432                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1433                                 return;
1434                         }
1435                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1436                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1437                         album.addImage(image);
1438                 }
1439
1440                 /* load avatar. */
1441                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1442                 if (avatarId != null) {
1443                         profile.setAvatar(getImage(avatarId, false));
1444                 }
1445
1446                 /* load options. */
1447                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1448                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1449                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1450                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1451                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1452                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1453
1454                 /* if we’re still here, Sone was loaded successfully. */
1455                 synchronized (sone) {
1456                         sone.setTime(soneTime);
1457                         sone.setProfile(profile);
1458                         sone.setPosts(posts);
1459                         sone.setReplies(replies);
1460                         sone.setLikePostIds(likedPostIds);
1461                         sone.setLikeReplyIds(likedReplyIds);
1462                         for (String friendId : friends) {
1463                                 followSone(sone, friendId);
1464                         }
1465                         sone.setAlbums(topLevelAlbums);
1466                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1467                 }
1468                 synchronized (knownSones) {
1469                         for (String friend : friends) {
1470                                 knownSones.add(friend);
1471                         }
1472                 }
1473                 synchronized (knownPosts) {
1474                         for (Post post : posts) {
1475                                 knownPosts.add(post.getId());
1476                         }
1477                 }
1478                 synchronized (knownReplies) {
1479                         for (PostReply reply : replies) {
1480                                 knownReplies.add(reply.getId());
1481                         }
1482                 }
1483         }
1484
1485         /**
1486          * Creates a new post.
1487          *
1488          * @param sone
1489          *            The Sone that creates the post
1490          * @param text
1491          *            The text of the post
1492          * @return The created post
1493          */
1494         public Post createPost(Sone sone, String text) {
1495                 return createPost(sone, System.currentTimeMillis(), text);
1496         }
1497
1498         /**
1499          * Creates a new post.
1500          *
1501          * @param sone
1502          *            The Sone that creates the post
1503          * @param time
1504          *            The time of the post
1505          * @param text
1506          *            The text of the post
1507          * @return The created post
1508          */
1509         public Post createPost(Sone sone, long time, String text) {
1510                 return createPost(sone, null, time, text);
1511         }
1512
1513         /**
1514          * Creates a new post.
1515          *
1516          * @param sone
1517          *            The Sone that creates the post
1518          * @param recipient
1519          *            The recipient Sone, or {@code null} if this post does not have
1520          *            a recipient
1521          * @param text
1522          *            The text of the post
1523          * @return The created post
1524          */
1525         public Post createPost(Sone sone, Sone recipient, String text) {
1526                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1527         }
1528
1529         /**
1530          * Creates a new post.
1531          *
1532          * @param sone
1533          *            The Sone that creates the post
1534          * @param recipient
1535          *            The recipient Sone, or {@code null} if this post does not have
1536          *            a recipient
1537          * @param time
1538          *            The time of the post
1539          * @param text
1540          *            The text of the post
1541          * @return The created post
1542          */
1543         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1544                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1545                 if (!sone.isLocal()) {
1546                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1547                         return null;
1548                 }
1549                 final Post post = new PostImpl(sone, time, text);
1550                 if (recipient != null) {
1551                         post.setRecipient(recipient);
1552                 }
1553                 synchronized (posts) {
1554                         posts.put(post.getId(), post);
1555                 }
1556                 eventBus.post(new NewPostFoundEvent(post));
1557                 sone.addPost(post);
1558                 touchConfiguration();
1559                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1560
1561                         /**
1562                          * {@inheritDoc}
1563                          */
1564                         @Override
1565                         public void run() {
1566                                 markPostKnown(post);
1567                         }
1568                 }, "Mark " + post + " read.");
1569                 return post;
1570         }
1571
1572         /**
1573          * Deletes the given post.
1574          *
1575          * @param post
1576          *            The post to delete
1577          */
1578         public void deletePost(Post post) {
1579                 if (!post.getSone().isLocal()) {
1580                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1581                         return;
1582                 }
1583                 post.getSone().removePost(post);
1584                 synchronized (posts) {
1585                         posts.remove(post.getId());
1586                 }
1587                 eventBus.post(new PostRemovedEvent(post));
1588                 markPostKnown(post);
1589                 touchConfiguration();
1590         }
1591
1592         /**
1593          * Marks the given post as known, if it is currently not a known post
1594          * (according to {@link Post#isKnown()}).
1595          *
1596          * @param post
1597          *            The post to mark as known
1598          */
1599         public void markPostKnown(Post post) {
1600                 post.setKnown(true);
1601                 synchronized (knownPosts) {
1602                         eventBus.post(new MarkPostKnownEvent(post));
1603                         if (knownPosts.add(post.getId())) {
1604                                 touchConfiguration();
1605                         }
1606                 }
1607                 for (PostReply reply : getReplies(post)) {
1608                         markReplyKnown(reply);
1609                 }
1610         }
1611
1612         /**
1613          * Bookmarks the given post.
1614          *
1615          * @param post
1616          *            The post to bookmark
1617          */
1618         public void bookmark(Post post) {
1619                 bookmarkPost(post.getId());
1620         }
1621
1622         /**
1623          * Bookmarks the post with the given ID.
1624          *
1625          * @param id
1626          *            The ID of the post to bookmark
1627          */
1628         public void bookmarkPost(String id) {
1629                 synchronized (bookmarkedPosts) {
1630                         bookmarkedPosts.add(id);
1631                 }
1632         }
1633
1634         /**
1635          * Removes the given post from the bookmarks.
1636          *
1637          * @param post
1638          *            The post to unbookmark
1639          */
1640         public void unbookmark(Post post) {
1641                 unbookmarkPost(post.getId());
1642         }
1643
1644         /**
1645          * Removes the post with the given ID from the bookmarks.
1646          *
1647          * @param id
1648          *            The ID of the post to unbookmark
1649          */
1650         public void unbookmarkPost(String id) {
1651                 synchronized (bookmarkedPosts) {
1652                         bookmarkedPosts.remove(id);
1653                 }
1654         }
1655
1656         /**
1657          * Creates a new reply.
1658          *
1659          * @param sone
1660          *            The Sone that creates the reply
1661          * @param post
1662          *            The post that this reply refers to
1663          * @param text
1664          *            The text of the reply
1665          * @return The created reply
1666          */
1667         public PostReply createReply(Sone sone, Post post, String text) {
1668                 return createReply(sone, post, System.currentTimeMillis(), text);
1669         }
1670
1671         /**
1672          * Creates a new reply.
1673          *
1674          * @param sone
1675          *            The Sone that creates the reply
1676          * @param post
1677          *            The post that this reply refers to
1678          * @param time
1679          *            The time of the reply
1680          * @param text
1681          *            The text of the reply
1682          * @return The created reply
1683          */
1684         public PostReply createReply(Sone sone, Post post, long time, String text) {
1685                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1686                 if (!sone.isLocal()) {
1687                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1688                         return null;
1689                 }
1690                 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1691                 synchronized (replies) {
1692                         replies.put(reply.getId(), reply);
1693                 }
1694                 synchronized (knownReplies) {
1695                         eventBus.post(new NewPostReplyFoundEvent(reply));
1696                 }
1697                 sone.addReply(reply);
1698                 touchConfiguration();
1699                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1700
1701                         /**
1702                          * {@inheritDoc}
1703                          */
1704                         @Override
1705                         public void run() {
1706                                 markReplyKnown(reply);
1707                         }
1708                 }, "Mark " + reply + " read.");
1709                 return reply;
1710         }
1711
1712         /**
1713          * Deletes the given reply.
1714          *
1715          * @param reply
1716          *            The reply to delete
1717          */
1718         public void deleteReply(PostReply reply) {
1719                 Sone sone = reply.getSone();
1720                 if (!sone.isLocal()) {
1721                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1722                         return;
1723                 }
1724                 synchronized (replies) {
1725                         replies.remove(reply.getId());
1726                 }
1727                 synchronized (knownReplies) {
1728                         markReplyKnown(reply);
1729                         knownReplies.remove(reply.getId());
1730                 }
1731                 sone.removeReply(reply);
1732                 touchConfiguration();
1733         }
1734
1735         /**
1736          * Marks the given reply as known, if it is currently not a known reply
1737          * (according to {@link Reply#isKnown()}).
1738          *
1739          * @param reply
1740          *            The reply to mark as known
1741          */
1742         public void markReplyKnown(PostReply reply) {
1743                 reply.setKnown(true);
1744                 synchronized (knownReplies) {
1745                         eventBus.post(new MarkPostReplyKnownEvent(reply));
1746                         if (knownReplies.add(reply.getId())) {
1747                                 touchConfiguration();
1748                         }
1749                 }
1750         }
1751
1752         /**
1753          * Creates a new top-level album for the given Sone.
1754          *
1755          * @param sone
1756          *            The Sone to create the album for
1757          * @return The new album
1758          */
1759         public Album createAlbum(Sone sone) {
1760                 return createAlbum(sone, null);
1761         }
1762
1763         /**
1764          * Creates a new album for the given Sone.
1765          *
1766          * @param sone
1767          *            The Sone to create the album for
1768          * @param parent
1769          *            The parent of the album (may be {@code null} to create a
1770          *            top-level album)
1771          * @return The new album
1772          */
1773         public Album createAlbum(Sone sone, Album parent) {
1774                 Album album = new Album();
1775                 synchronized (albums) {
1776                         albums.put(album.getId(), album);
1777                 }
1778                 album.setSone(sone);
1779                 if (parent != null) {
1780                         parent.addAlbum(album);
1781                 } else {
1782                         sone.addAlbum(album);
1783                 }
1784                 return album;
1785         }
1786
1787         /**
1788          * Deletes the given album. The owner of the album has to be a local Sone,
1789          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1790          *
1791          * @param album
1792          *            The album to remove
1793          */
1794         public void deleteAlbum(Album album) {
1795                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1796                 if (!album.isEmpty()) {
1797                         return;
1798                 }
1799                 if (album.getParent() == null) {
1800                         album.getSone().removeAlbum(album);
1801                 } else {
1802                         album.getParent().removeAlbum(album);
1803                 }
1804                 synchronized (albums) {
1805                         albums.remove(album.getId());
1806                 }
1807                 touchConfiguration();
1808         }
1809
1810         /**
1811          * Creates a new image.
1812          *
1813          * @param sone
1814          *            The Sone creating the image
1815          * @param album
1816          *            The album the image will be inserted into
1817          * @param temporaryImage
1818          *            The temporary image to create the image from
1819          * @return The newly created image
1820          */
1821         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1822                 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1823                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1824                 album.addImage(image);
1825                 synchronized (images) {
1826                         images.put(image.getId(), image);
1827                 }
1828                 imageInserter.insertImage(temporaryImage, image);
1829                 return image;
1830         }
1831
1832         /**
1833          * Deletes the given image. This method will also delete a matching
1834          * temporary image.
1835          *
1836          * @see #deleteTemporaryImage(TemporaryImage)
1837          * @param image
1838          *            The image to delete
1839          */
1840         public void deleteImage(Image image) {
1841                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1842                 deleteTemporaryImage(image.getId());
1843                 image.getAlbum().removeImage(image);
1844                 synchronized (images) {
1845                         images.remove(image.getId());
1846                 }
1847                 touchConfiguration();
1848         }
1849
1850         /**
1851          * Creates a new temporary image.
1852          *
1853          * @param mimeType
1854          *            The MIME type of the temporary image
1855          * @param imageData
1856          *            The encoded data of the image
1857          * @return The temporary image
1858          */
1859         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1860                 TemporaryImage temporaryImage = new TemporaryImage();
1861                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1862                 synchronized (temporaryImages) {
1863                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1864                 }
1865                 return temporaryImage;
1866         }
1867
1868         /**
1869          * Deletes the given temporary image.
1870          *
1871          * @param temporaryImage
1872          *            The temporary image to delete
1873          */
1874         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1875                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1876                 deleteTemporaryImage(temporaryImage.getId());
1877         }
1878
1879         /**
1880          * Deletes the temporary image with the given ID.
1881          *
1882          * @param imageId
1883          *            The ID of the temporary image to delete
1884          */
1885         public void deleteTemporaryImage(String imageId) {
1886                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1887                 synchronized (temporaryImages) {
1888                         temporaryImages.remove(imageId);
1889                 }
1890                 Image image = getImage(imageId, false);
1891                 if (image != null) {
1892                         imageInserter.cancelImageInsert(image);
1893                 }
1894         }
1895
1896         /**
1897          * Notifies the core that the configuration, either of the core or of a
1898          * single local Sone, has changed, and that the configuration should be
1899          * saved.
1900          */
1901         public void touchConfiguration() {
1902                 lastConfigurationUpdate = System.currentTimeMillis();
1903         }
1904
1905         //
1906         // SERVICE METHODS
1907         //
1908
1909         /**
1910          * Starts the core.
1911          */
1912         @Override
1913         public void serviceStart() {
1914                 loadConfiguration();
1915                 updateChecker.addUpdateListener(this);
1916                 updateChecker.start();
1917                 identityManager.addIdentityListener(this);
1918                 identityManager.start();
1919                 webOfTrustUpdater.init();
1920                 webOfTrustUpdater.start();
1921         }
1922
1923         /**
1924          * {@inheritDoc}
1925          */
1926         @Override
1927         public void serviceRun() {
1928                 long lastSaved = System.currentTimeMillis();
1929                 while (!shouldStop()) {
1930                         sleep(1000);
1931                         long now = System.currentTimeMillis();
1932                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1933                                 for (Sone localSone : getLocalSones()) {
1934                                         saveSone(localSone);
1935                                 }
1936                                 saveConfiguration();
1937                                 lastSaved = now;
1938                         }
1939                 }
1940         }
1941
1942         /**
1943          * Stops the core.
1944          */
1945         @Override
1946         public void serviceStop() {
1947                 synchronized (sones) {
1948                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1949                                 soneInserter.getValue().removeSoneInsertListener(this);
1950                                 soneInserter.getValue().stop();
1951                                 saveSone(soneInserter.getKey());
1952                         }
1953                 }
1954                 saveConfiguration();
1955                 webOfTrustUpdater.stop();
1956                 updateChecker.stop();
1957                 updateChecker.removeUpdateListener(this);
1958                 soneDownloader.stop();
1959                 identityManager.removeIdentityListener(this);
1960                 identityManager.stop();
1961         }
1962
1963         //
1964         // PRIVATE METHODS
1965         //
1966
1967         /**
1968          * Saves the given Sone. This will persist all local settings for the given
1969          * Sone, such as the friends list and similar, private options.
1970          *
1971          * @param sone
1972          *            The Sone to save
1973          */
1974         private synchronized void saveSone(Sone sone) {
1975                 if (!sone.isLocal()) {
1976                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1977                         return;
1978                 }
1979                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1980                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1981                         return;
1982                 }
1983
1984                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1985                 try {
1986                         /* save Sone into configuration. */
1987                         String sonePrefix = "Sone/" + sone.getId();
1988                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1989                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1990
1991                         /* save profile. */
1992                         Profile profile = sone.getProfile();
1993                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1994                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1995                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1996                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1997                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1998                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1999                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2000
2001                         /* save profile fields. */
2002                         int fieldCounter = 0;
2003                         for (Field profileField : profile.getFields()) {
2004                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2005                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2006                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2007                         }
2008                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2009
2010                         /* save posts. */
2011                         int postCounter = 0;
2012                         for (Post post : sone.getPosts()) {
2013                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2014                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2015                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2016                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2017                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2018                         }
2019                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2020
2021                         /* save replies. */
2022                         int replyCounter = 0;
2023                         for (PostReply reply : sone.getReplies()) {
2024                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2025                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2026                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2027                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2028                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2029                         }
2030                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2031
2032                         /* save post likes. */
2033                         int postLikeCounter = 0;
2034                         for (String postId : sone.getLikedPostIds()) {
2035                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2036                         }
2037                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2038
2039                         /* save reply likes. */
2040                         int replyLikeCounter = 0;
2041                         for (String replyId : sone.getLikedReplyIds()) {
2042                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2043                         }
2044                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2045
2046                         /* save friends. */
2047                         int friendCounter = 0;
2048                         for (String friendId : sone.getFriends()) {
2049                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2050                         }
2051                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2052
2053                         /* save albums. first, collect in a flat structure, top-level first. */
2054                         List<Album> albums = sone.getAllAlbums();
2055
2056                         int albumCounter = 0;
2057                         for (Album album : albums) {
2058                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2059                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2060                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2061                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2062                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2063                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2064                         }
2065                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2066
2067                         /* save images. */
2068                         int imageCounter = 0;
2069                         for (Album album : albums) {
2070                                 for (Image image : album.getImages()) {
2071                                         if (!image.isInserted()) {
2072                                                 continue;
2073                                         }
2074                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2075                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2076                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2077                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2078                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2079                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2080                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2081                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2082                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2083                                 }
2084                         }
2085                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2086
2087                         /* save options. */
2088                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2089                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2090                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2091                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2092                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2093                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2094
2095                         configuration.save();
2096
2097                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2098
2099                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2100                 } catch (ConfigurationException ce1) {
2101                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2102                 }
2103         }
2104
2105         /**
2106          * Saves the current options.
2107          */
2108         private void saveConfiguration() {
2109                 synchronized (configuration) {
2110                         if (storingConfiguration) {
2111                                 logger.log(Level.FINE, "Already storing configuration…");
2112                                 return;
2113                         }
2114                         storingConfiguration = true;
2115                 }
2116
2117                 /* store the options first. */
2118                 try {
2119                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2120                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2121                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2122                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2123                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2124                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2125                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2126                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2127                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2128                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2129                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2130                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2131
2132                         /* save known Sones. */
2133                         int soneCounter = 0;
2134                         synchronized (knownSones) {
2135                                 for (String knownSoneId : knownSones) {
2136                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2137                                 }
2138                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2139                         }
2140
2141                         /* save Sone following times. */
2142                         soneCounter = 0;
2143                         synchronized (soneFollowingTimes) {
2144                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2145                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2146                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2147                                         ++soneCounter;
2148                                 }
2149                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2150                         }
2151
2152                         /* save known posts. */
2153                         int postCounter = 0;
2154                         synchronized (knownPosts) {
2155                                 for (String knownPostId : knownPosts) {
2156                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2157                                 }
2158                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2159                         }
2160
2161                         /* save known replies. */
2162                         int replyCounter = 0;
2163                         synchronized (knownReplies) {
2164                                 for (String knownReplyId : knownReplies) {
2165                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2166                                 }
2167                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2168                         }
2169
2170                         /* save bookmarked posts. */
2171                         int bookmarkedPostCounter = 0;
2172                         synchronized (bookmarkedPosts) {
2173                                 for (String bookmarkedPostId : bookmarkedPosts) {
2174                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2175                                 }
2176                         }
2177                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2178
2179                         /* now save it. */
2180                         configuration.save();
2181
2182                 } catch (ConfigurationException ce1) {
2183                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2184                 } finally {
2185                         synchronized (configuration) {
2186                                 storingConfiguration = false;
2187                         }
2188                 }
2189         }
2190
2191         /**
2192          * Loads the configuration.
2193          */
2194         @SuppressWarnings("unchecked")
2195         private void loadConfiguration() {
2196                 /* create options. */
2197                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2198
2199                         @Override
2200                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2201                                 SoneInserter.setInsertionDelay(newValue);
2202                         }
2203
2204                 }));
2205                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2206                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2207                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2208                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2209                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2210                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2211                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2212                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2213                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2214
2215                         @Override
2216                         @SuppressWarnings("synthetic-access")
2217                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2218                                 fcpInterface.setActive(newValue);
2219                         }
2220                 }));
2221                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2222
2223                         @Override
2224                         @SuppressWarnings("synthetic-access")
2225                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2226                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2227                         }
2228
2229                 }));
2230
2231                 loadConfigurationValue("InsertionDelay");
2232                 loadConfigurationValue("PostsPerPage");
2233                 loadConfigurationValue("ImagesPerPage");
2234                 loadConfigurationValue("CharactersPerPost");
2235                 loadConfigurationValue("PostCutOffLength");
2236                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2237                 loadConfigurationValue("PositiveTrust");
2238                 loadConfigurationValue("NegativeTrust");
2239                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2240                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2241                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2242
2243                 /* load known Sones. */
2244                 int soneCounter = 0;
2245                 while (true) {
2246                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2247                         if (knownSoneId == null) {
2248                                 break;
2249                         }
2250                         synchronized (knownSones) {
2251                                 knownSones.add(knownSoneId);
2252                         }
2253                 }
2254
2255                 /* load Sone following times. */
2256                 soneCounter = 0;
2257                 while (true) {
2258                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2259                         if (soneId == null) {
2260                                 break;
2261                         }
2262                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2263                         Sone followedSone = getSone(soneId);
2264                         if (followedSone == null) {
2265                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2266                         } else {
2267                                 synchronized (soneFollowingTimes) {
2268                                         soneFollowingTimes.put(getSone(soneId), time);
2269                                 }
2270                         }
2271                         ++soneCounter;
2272                 }
2273
2274                 /* load known posts. */
2275                 int postCounter = 0;
2276                 while (true) {
2277                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2278                         if (knownPostId == null) {
2279                                 break;
2280                         }
2281                         synchronized (knownPosts) {
2282                                 knownPosts.add(knownPostId);
2283                         }
2284                 }
2285
2286                 /* load known replies. */
2287                 int replyCounter = 0;
2288                 while (true) {
2289                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2290                         if (knownReplyId == null) {
2291                                 break;
2292                         }
2293                         synchronized (knownReplies) {
2294                                 knownReplies.add(knownReplyId);
2295                         }
2296                 }
2297
2298                 /* load bookmarked posts. */
2299                 int bookmarkedPostCounter = 0;
2300                 while (true) {
2301                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2302                         if (bookmarkedPostId == null) {
2303                                 break;
2304                         }
2305                         synchronized (bookmarkedPosts) {
2306                                 bookmarkedPosts.add(bookmarkedPostId);
2307                         }
2308                 }
2309
2310         }
2311
2312         /**
2313          * Loads an {@link Integer} configuration value for the option with the
2314          * given name, logging validation failures.
2315          *
2316          * @param optionName
2317          *            The name of the option to load
2318          */
2319         private void loadConfigurationValue(String optionName) {
2320                 try {
2321                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2322                 } catch (IllegalArgumentException iae1) {
2323                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2324                 }
2325         }
2326
2327         /**
2328          * Generate a Sone URI from the given URI and latest edition.
2329          *
2330          * @param uriString
2331          *            The URI to derive the Sone URI from
2332          * @return The derived URI
2333          */
2334         private static FreenetURI getSoneUri(String uriString) {
2335                 try {
2336                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2337                         return uri;
2338                 } catch (MalformedURLException mue1) {
2339                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2340                         return null;
2341                 }
2342         }
2343
2344         //
2345         // INTERFACE IdentityListener
2346         //
2347
2348         /**
2349          * {@inheritDoc}
2350          */
2351         @Override
2352         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2353                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2354                 if (ownIdentity.hasContext("Sone")) {
2355                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2356                         addLocalSone(ownIdentity);
2357                 }
2358         }
2359
2360         /**
2361          * {@inheritDoc}
2362          */
2363         @Override
2364         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2365                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2366                 trustedIdentities.remove(ownIdentity);
2367         }
2368
2369         /**
2370          * {@inheritDoc}
2371          */
2372         @Override
2373         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2374                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2375                 trustedIdentities.get(ownIdentity).add(identity);
2376                 addRemoteSone(identity);
2377         }
2378
2379         /**
2380          * {@inheritDoc}
2381          */
2382         @Override
2383         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2384                 soneDownloaders.execute(new Runnable() {
2385
2386                         @Override
2387                         @SuppressWarnings("synthetic-access")
2388                         public void run() {
2389                                 Sone sone = getRemoteSone(identity.getId(), false);
2390                                 sone.setIdentity(identity);
2391                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2392                                 soneDownloader.addSone(sone);
2393                                 soneDownloader.fetchSone(sone);
2394                         }
2395                 });
2396         }
2397
2398         /**
2399          * {@inheritDoc}
2400          */
2401         @Override
2402         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2403                 trustedIdentities.get(ownIdentity).remove(identity);
2404                 boolean foundIdentity = false;
2405                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2406                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2407                                 continue;
2408                         }
2409                         if (trustedIdentity.getValue().contains(identity)) {
2410                                 foundIdentity = true;
2411                         }
2412                 }
2413                 if (foundIdentity) {
2414                         /* some local identity still trusts this identity, don’t remove. */
2415                         return;
2416                 }
2417                 Sone sone = getSone(identity.getId(), false);
2418                 if (sone == null) {
2419                         /* TODO - we don’t have the Sone anymore. should this happen? */
2420                         return;
2421                 }
2422                 synchronized (posts) {
2423                         synchronized (knownPosts) {
2424                                 for (Post post : sone.getPosts()) {
2425                                         posts.remove(post.getId());
2426                                         eventBus.post(new PostRemovedEvent(post));
2427                                 }
2428                         }
2429                 }
2430                 synchronized (replies) {
2431                         synchronized (knownReplies) {
2432                                 for (PostReply reply : sone.getReplies()) {
2433                                         replies.remove(reply.getId());
2434                                         eventBus.post(new PostReplyRemovedEvent(reply));
2435                                 }
2436                         }
2437                 }
2438                 synchronized (sones) {
2439                         sones.remove(identity.getId());
2440                 }
2441                 eventBus.post(new SoneRemovedEvent(sone));
2442         }
2443
2444         //
2445         // INTERFACE UpdateListener
2446         //
2447
2448         /**
2449          * {@inheritDoc}
2450          */
2451         @Override
2452         public void updateFound(Version version, long releaseTime, long latestEdition) {
2453                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2454         }
2455
2456         //
2457         // INTERFACE ImageInsertListener
2458         //
2459
2460         /**
2461          * {@inheritDoc}
2462          */
2463         @Override
2464         public void insertStarted(Sone sone) {
2465                 coreListenerManager.fireSoneInserting(sone);
2466         }
2467
2468         /**
2469          * {@inheritDoc}
2470          */
2471         @Override
2472         public void insertFinished(Sone sone, long insertDuration) {
2473                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2474         }
2475
2476         /**
2477          * {@inheritDoc}
2478          */
2479         @Override
2480         public void insertAborted(Sone sone, Throwable cause) {
2481                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2482         }
2483
2484         //
2485         // SONEINSERTLISTENER METHODS
2486         //
2487
2488         /**
2489          * {@inheritDoc}
2490          */
2491         @Override
2492         public void imageInsertStarted(Image image) {
2493                 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2494                 coreListenerManager.fireImageInsertStarted(image);
2495         }
2496
2497         /**
2498          * {@inheritDoc}
2499          */
2500         @Override
2501         public void imageInsertAborted(Image image) {
2502                 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2503                 coreListenerManager.fireImageInsertAborted(image);
2504         }
2505
2506         /**
2507          * {@inheritDoc}
2508          */
2509         @Override
2510         public void imageInsertFinished(Image image, FreenetURI key) {
2511                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2512                 image.setKey(key.toString());
2513                 deleteTemporaryImage(image.getId());
2514                 touchConfiguration();
2515                 coreListenerManager.fireImageInsertFinished(image);
2516         }
2517
2518         /**
2519          * {@inheritDoc}
2520          */
2521         @Override
2522         public void imageInsertFailed(Image image, Throwable cause) {
2523                 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2524                 coreListenerManager.fireImageInsertFailed(image, cause);
2525         }
2526
2527         /**
2528          * Convenience interface for external classes that want to access the core’s
2529          * configuration.
2530          *
2531          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2532          */
2533         public static class Preferences {
2534
2535                 /** The wrapped options. */
2536                 private final Options options;
2537
2538                 /**
2539                  * Creates a new preferences object wrapped around the given options.
2540                  *
2541                  * @param options
2542                  *            The options to wrap
2543                  */
2544                 public Preferences(Options options) {
2545                         this.options = options;
2546                 }
2547
2548                 /**
2549                  * Returns the insertion delay.
2550                  *
2551                  * @return The insertion delay
2552                  */
2553                 public int getInsertionDelay() {
2554                         return options.getIntegerOption("InsertionDelay").get();
2555                 }
2556
2557                 /**
2558                  * Validates the given insertion delay.
2559                  *
2560                  * @param insertionDelay
2561                  *            The insertion delay to validate
2562                  * @return {@code true} if the given insertion delay was valid,
2563                  *         {@code false} otherwise
2564                  */
2565                 public boolean validateInsertionDelay(Integer insertionDelay) {
2566                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2567                 }
2568
2569                 /**
2570                  * Sets the insertion delay
2571                  *
2572                  * @param insertionDelay
2573                  *            The new insertion delay, or {@code null} to restore it to
2574                  *            the default value
2575                  * @return This preferences
2576                  */
2577                 public Preferences setInsertionDelay(Integer insertionDelay) {
2578                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2579                         return this;
2580                 }
2581
2582                 /**
2583                  * Returns the number of posts to show per page.
2584                  *
2585                  * @return The number of posts to show per page
2586                  */
2587                 public int getPostsPerPage() {
2588                         return options.getIntegerOption("PostsPerPage").get();
2589                 }
2590
2591                 /**
2592                  * Validates the number of posts per page.
2593                  *
2594                  * @param postsPerPage
2595                  *            The number of posts per page
2596                  * @return {@code true} if the number of posts per page was valid,
2597                  *         {@code false} otherwise
2598                  */
2599                 public boolean validatePostsPerPage(Integer postsPerPage) {
2600                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2601                 }
2602
2603                 /**
2604                  * Sets the number of posts to show per page.
2605                  *
2606                  * @param postsPerPage
2607                  *            The number of posts to show per page
2608                  * @return This preferences object
2609                  */
2610                 public Preferences setPostsPerPage(Integer postsPerPage) {
2611                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2612                         return this;
2613                 }
2614
2615                 /**
2616                  * Returns the number of images to show per page.
2617                  *
2618                  * @return The number of images to show per page
2619                  */
2620                 public int getImagesPerPage() {
2621                         return options.getIntegerOption("ImagesPerPage").get();
2622                 }
2623
2624                 /**
2625                  * Validates the number of images per page.
2626                  *
2627                  * @param imagesPerPage
2628                  *            The number of images per page
2629                  * @return {@code true} if the number of images per page was valid,
2630                  *         {@code false} otherwise
2631                  */
2632                 public boolean validateImagesPerPage(Integer imagesPerPage) {
2633                         return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2634                 }
2635
2636                 /**
2637                  * Sets the number of images per page.
2638                  *
2639                  * @param imagesPerPage
2640                  *            The number of images per page
2641                  * @return This preferences object
2642                  */
2643                 public Preferences setImagesPerPage(Integer imagesPerPage) {
2644                         options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2645                         return this;
2646                 }
2647
2648                 /**
2649                  * Returns the number of characters per post, or <code>-1</code> if the
2650                  * posts should not be cut off.
2651                  *
2652                  * @return The numbers of characters per post
2653                  */
2654                 public int getCharactersPerPost() {
2655                         return options.getIntegerOption("CharactersPerPost").get();
2656                 }
2657
2658                 /**
2659                  * Validates the number of characters per post.
2660                  *
2661                  * @param charactersPerPost
2662                  *            The number of characters per post
2663                  * @return {@code true} if the number of characters per post was valid,
2664                  *         {@code false} otherwise
2665                  */
2666                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2667                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2668                 }
2669
2670                 /**
2671                  * Sets the number of characters per post.
2672                  *
2673                  * @param charactersPerPost
2674                  *            The number of characters per post, or <code>-1</code> to
2675                  *            not cut off the posts
2676                  * @return This preferences objects
2677                  */
2678                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2679                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2680                         return this;
2681                 }
2682
2683                 /**
2684                  * Returns the number of characters the shortened post should have.
2685                  *
2686                  * @return The number of characters of the snippet
2687                  */
2688                 public int getPostCutOffLength() {
2689                         return options.getIntegerOption("PostCutOffLength").get();
2690                 }
2691
2692                 /**
2693                  * Validates the number of characters after which to cut off the post.
2694                  *
2695                  * @param postCutOffLength
2696                  *            The number of characters of the snippet
2697                  * @return {@code true} if the number of characters of the snippet is
2698                  *         valid, {@code false} otherwise
2699                  */
2700                 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2701                         return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2702                 }
2703
2704                 /**
2705                  * Sets the number of characters the shortened post should have.
2706                  *
2707                  * @param postCutOffLength
2708                  *            The number of characters of the snippet
2709                  * @return This preferences
2710                  */
2711                 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2712                         options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2713                         return this;
2714                 }
2715
2716                 /**
2717                  * Returns whether Sone requires full access to be even visible.
2718                  *
2719                  * @return {@code true} if Sone requires full access, {@code false}
2720                  *         otherwise
2721                  */
2722                 public boolean isRequireFullAccess() {
2723                         return options.getBooleanOption("RequireFullAccess").get();
2724                 }
2725
2726                 /**
2727                  * Sets whether Sone requires full access to be even visible.
2728                  *
2729                  * @param requireFullAccess
2730                  *            {@code true} if Sone requires full access, {@code false}
2731                  *            otherwise
2732                  */
2733                 public void setRequireFullAccess(Boolean requireFullAccess) {
2734                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2735                 }
2736
2737                 /**
2738                  * Returns the positive trust.
2739                  *
2740                  * @return The positive trust
2741                  */
2742                 public int getPositiveTrust() {
2743                         return options.getIntegerOption("PositiveTrust").get();
2744                 }
2745
2746                 /**
2747                  * Validates the positive trust.
2748                  *
2749                  * @param positiveTrust
2750                  *            The positive trust to validate
2751                  * @return {@code true} if the positive trust was valid, {@code false}
2752                  *         otherwise
2753                  */
2754                 public boolean validatePositiveTrust(Integer positiveTrust) {
2755                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2756                 }
2757
2758                 /**
2759                  * Sets the positive trust.
2760                  *
2761                  * @param positiveTrust
2762                  *            The new positive trust, or {@code null} to restore it to
2763                  *            the default vlaue
2764                  * @return This preferences
2765                  */
2766                 public Preferences setPositiveTrust(Integer positiveTrust) {
2767                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2768                         return this;
2769                 }
2770
2771                 /**
2772                  * Returns the negative trust.
2773                  *
2774                  * @return The negative trust
2775                  */
2776                 public int getNegativeTrust() {
2777                         return options.getIntegerOption("NegativeTrust").get();
2778                 }
2779
2780                 /**
2781                  * Validates the negative trust.
2782                  *
2783                  * @param negativeTrust
2784                  *            The negative trust to validate
2785                  * @return {@code true} if the negative trust was valid, {@code false}
2786                  *         otherwise
2787                  */
2788                 public boolean validateNegativeTrust(Integer negativeTrust) {
2789                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2790                 }
2791
2792                 /**
2793                  * Sets the negative trust.
2794                  *
2795                  * @param negativeTrust
2796                  *            The negative trust, or {@code null} to restore it to the
2797                  *            default value
2798                  * @return The preferences
2799                  */
2800                 public Preferences setNegativeTrust(Integer negativeTrust) {
2801                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2802                         return this;
2803                 }
2804
2805                 /**
2806                  * Returns the trust comment. This is the comment that is set in the web
2807                  * of trust when a trust value is assigned to an identity.
2808                  *
2809                  * @return The trust comment
2810                  */
2811                 public String getTrustComment() {
2812                         return options.getStringOption("TrustComment").get();
2813                 }
2814
2815                 /**
2816                  * Sets the trust comment.
2817                  *
2818                  * @param trustComment
2819                  *            The trust comment, or {@code null} to restore it to the
2820                  *            default value
2821                  * @return This preferences
2822                  */
2823                 public Preferences setTrustComment(String trustComment) {
2824                         options.getStringOption("TrustComment").set(trustComment);
2825                         return this;
2826                 }
2827
2828                 /**
2829                  * Returns whether the {@link FcpInterface FCP interface} is currently
2830                  * active.
2831                  *
2832                  * @see FcpInterface#setActive(boolean)
2833                  * @return {@code true} if the FCP interface is currently active,
2834                  *         {@code false} otherwise
2835                  */
2836                 public boolean isFcpInterfaceActive() {
2837                         return options.getBooleanOption("ActivateFcpInterface").get();
2838                 }
2839
2840                 /**
2841                  * Sets whether the {@link FcpInterface FCP interface} is currently
2842                  * active.
2843                  *
2844                  * @see FcpInterface#setActive(boolean)
2845                  * @param fcpInterfaceActive
2846                  *            {@code true} to activate the FCP interface, {@code false}
2847                  *            to deactivate the FCP interface
2848                  * @return This preferences object
2849                  */
2850                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2851                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2852                         return this;
2853                 }
2854
2855                 /**
2856                  * Returns the action level for which full access to the FCP interface
2857                  * is required.
2858                  *
2859                  * @return The action level for which full access to the FCP interface
2860                  *         is required
2861                  */
2862                 public FullAccessRequired getFcpFullAccessRequired() {
2863                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2864                 }
2865
2866                 /**
2867                  * Sets the action level for which full access to the FCP interface is
2868                  * required
2869                  *
2870                  * @param fcpFullAccessRequired
2871                  *            The action level
2872                  * @return This preferences
2873                  */
2874                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2875                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2876                         return this;
2877                 }
2878
2879         }
2880
2881 }