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