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