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