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