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