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