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