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