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