Use static import for String.format.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2013 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 static com.google.common.base.Optional.of;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.collect.FluentIterable.from;
25 import static java.lang.String.format;
26 import static net.pterodactylus.sone.data.Identified.GET_ID;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
29
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Set;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
43
44 import net.pterodactylus.sone.core.Options.DefaultOption;
45 import net.pterodactylus.sone.core.Options.Option;
46 import net.pterodactylus.sone.core.Options.OptionWatcher;
47 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
48 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
49 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
51 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
52 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
53 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
54 import net.pterodactylus.sone.core.event.PostRemovedEvent;
55 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneLockedEvent;
57 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
58 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
59 import net.pterodactylus.sone.data.Album;
60 import net.pterodactylus.sone.data.Client;
61 import net.pterodactylus.sone.data.Image;
62 import net.pterodactylus.sone.data.Post;
63 import net.pterodactylus.sone.data.PostReply;
64 import net.pterodactylus.sone.data.Profile;
65 import net.pterodactylus.sone.data.Profile.Field;
66 import net.pterodactylus.sone.data.Reply.Modifier.ReplyUpdated;
67 import net.pterodactylus.sone.data.Sone;
68 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
69 import net.pterodactylus.sone.data.Sone.SoneStatus;
70 import net.pterodactylus.sone.data.TemporaryImage;
71 import net.pterodactylus.sone.database.Database;
72 import net.pterodactylus.sone.database.DatabaseException;
73 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
74 import net.pterodactylus.sone.database.PostBuilder;
75 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
76 import net.pterodactylus.sone.database.PostReplyBuilder;
77 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
78 import net.pterodactylus.sone.database.SoneBuilder.SoneCreated;
79 import net.pterodactylus.sone.database.SoneProvider;
80 import net.pterodactylus.sone.fcp.FcpInterface;
81 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
82 import net.pterodactylus.sone.freenet.wot.Identity;
83 import net.pterodactylus.sone.freenet.wot.IdentityManager;
84 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
85 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
90 import net.pterodactylus.sone.main.SonePlugin;
91 import net.pterodactylus.sone.utils.IntegerRangePredicate;
92 import net.pterodactylus.util.config.Configuration;
93 import net.pterodactylus.util.config.ConfigurationException;
94 import net.pterodactylus.util.logging.Logging;
95 import net.pterodactylus.util.number.Numbers;
96 import net.pterodactylus.util.service.AbstractService;
97 import net.pterodactylus.util.thread.NamedThreadFactory;
98
99 import com.google.common.base.Function;
100 import com.google.common.base.Optional;
101 import com.google.common.base.Predicate;
102 import com.google.common.base.Predicates;
103 import com.google.common.collect.HashMultimap;
104 import com.google.common.collect.ImmutableSet;
105 import com.google.common.collect.Maps;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
111
112 /**
113  * The Sone core.
114  *
115  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
116  */
117 public class Core extends AbstractService implements SoneProvider {
118
119         /** The logger. */
120         private static final Logger logger = Logging.getLogger(Core.class);
121
122         /** The options. */
123         private final Options options = new Options();
124
125         /** The preferences. */
126         private final Preferences preferences = new Preferences(options);
127
128         /** The event bus. */
129         private final EventBus eventBus;
130
131         /** The configuration. */
132         private Configuration configuration;
133
134         /** Whether we’re currently saving the configuration. */
135         private boolean storingConfiguration = false;
136
137         /** The identity manager. */
138         private final IdentityManager identityManager;
139
140         /** Interface to freenet. */
141         private final FreenetInterface freenetInterface;
142
143         /** The Sone downloader. */
144         private final SoneDownloader soneDownloader;
145
146         /** The image inserter. */
147         private final ImageInserter imageInserter;
148
149         /** Sone downloader thread-pool. */
150         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151
152         /** The update checker. */
153         private final UpdateChecker updateChecker;
154
155         /** The trust updater. */
156         private final WebOfTrustUpdater webOfTrustUpdater;
157
158         /** The FCP interface. */
159         private volatile FcpInterface fcpInterface;
160
161         /** The times Sones were followed. */
162         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163
164         /** Locked local Sones. */
165         /* synchronize on itself. */
166         private final Set<Sone> lockedSones = new HashSet<Sone>();
167
168         /** Sone inserters. */
169         /* synchronize access on this on sones. */
170         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171
172         /** Sone rescuers. */
173         /* synchronize access on this on sones. */
174         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175
176         /** All known Sones. */
177         private final Set<String> knownSones = new HashSet<String>();
178
179         /** The post database. */
180         private final Database database;
181
182         /** All bookmarked posts. */
183         /* synchronize access on itself. */
184         private final Set<String> bookmarkedPosts = new HashSet<String>();
185
186         /** Trusted identities, sorted by own identities. */
187         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
188
189         /** All temporary images. */
190         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
191
192         /** Ticker for threads that mark own elements as known. */
193         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
194
195         /** The time the configuration was last touched. */
196         private volatile long lastConfigurationUpdate;
197
198         /**
199          * Creates a new core.
200          *
201          * @param configuration
202          *              The configuration of the core
203          * @param freenetInterface
204          *              The freenet interface
205          * @param identityManager
206          *              The identity manager
207          * @param webOfTrustUpdater
208          *              The WebOfTrust updater
209          * @param eventBus
210          *              The event bus
211          * @param database
212          *              The database
213          */
214         @Inject
215         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
216                 super("Sone Core");
217                 this.configuration = configuration;
218                 this.freenetInterface = freenetInterface;
219                 this.identityManager = identityManager;
220                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
221                 this.imageInserter = new ImageInserter(freenetInterface);
222                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
223                 this.webOfTrustUpdater = webOfTrustUpdater;
224                 this.eventBus = eventBus;
225                 this.database = database;
226         }
227
228         //
229         // ACCESSORS
230         //
231
232         /**
233          * Sets the configuration to use. This will automatically save the current
234          * configuration to the given configuration.
235          *
236          * @param configuration
237          *              The new configuration to use
238          */
239         public void setConfiguration(Configuration configuration) {
240                 this.configuration = configuration;
241                 touchConfiguration();
242         }
243
244         /**
245          * Returns the options used by the core.
246          *
247          * @return The options of the core
248          */
249         public Preferences getPreferences() {
250                 return preferences;
251         }
252
253         /**
254          * Returns the identity manager used by the core.
255          *
256          * @return The identity manager
257          */
258         public IdentityManager getIdentityManager() {
259                 return identityManager;
260         }
261
262         /**
263          * Returns the update checker.
264          *
265          * @return The update checker
266          */
267         public UpdateChecker getUpdateChecker() {
268                 return updateChecker;
269         }
270
271         /**
272          * Sets the FCP interface to use.
273          *
274          * @param fcpInterface
275          *              The FCP interface to use
276          */
277         public void setFcpInterface(FcpInterface fcpInterface) {
278                 this.fcpInterface = fcpInterface;
279         }
280
281         public Database getDatabase() {
282                 return database;
283         }
284
285         /**
286          * Returns the Sone rescuer for the given local Sone.
287          *
288          * @param sone
289          *              The local Sone to get the rescuer for
290          * @return The Sone rescuer for the given Sone
291          */
292         public SoneRescuer getSoneRescuer(Sone sone) {
293                 checkNotNull(sone, "sone must not be null");
294                 checkArgument(sone.isLocal(), "sone must be local");
295                 synchronized (soneRescuers) {
296                         SoneRescuer soneRescuer = soneRescuers.get(sone);
297                         if (soneRescuer == null) {
298                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
299                                 soneRescuers.put(sone, soneRescuer);
300                                 soneRescuer.start();
301                         }
302                         return soneRescuer;
303                 }
304         }
305
306         /**
307          * Returns whether the given Sone is currently locked.
308          *
309          * @param sone
310          *              The sone to check
311          * @return {@code true} if the Sone is locked, {@code false} if it is not
312          */
313         public boolean isLocked(Sone sone) {
314                 synchronized (lockedSones) {
315                         return lockedSones.contains(sone);
316                 }
317         }
318
319         @Override
320         public Collection<Sone> getSones() {
321                 return database.getSones();
322         }
323
324         @Override
325         public Function<String, Optional<Sone>> getSone() {
326                 return database.getSone();
327         }
328
329         @Override
330         public Optional<Sone> getSone(String id) {
331                 return database.getSone(id);
332         }
333
334         @Override
335         public Collection<Sone> getLocalSones() {
336                 return database.getLocalSones();
337         }
338
339         /**
340          * Returns the local Sone with the given ID, optionally creating a new Sone.
341          *
342          * @param id
343          *              The ID of the Sone
344          * @return The Sone with the given ID, or {@code null}
345          */
346         public Optional<Sone> getLocalSone(String id) {
347                 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
348         }
349
350         @Override
351         public Collection<Sone> getRemoteSones() {
352                 return database.getRemoteSones();
353         }
354
355         /**
356          * Returns the remote Sone with the given ID.
357          *
358          * @param id
359          *              The ID of the remote Sone to get
360          * @return The Sone with the given ID
361          */
362         public Optional<Sone> getRemoteSone(String id) {
363                 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
364         }
365
366         /**
367          * Returns whether the given Sone has been modified.
368          *
369          * @param sone
370          *              The Sone to check for modifications
371          * @return {@code true} if a modification has been detected in the Sone, {@code
372          *         false} otherwise
373          */
374         public boolean isModifiedSone(Sone sone) {
375                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
376         }
377
378         /**
379          * Returns the time when the given was first followed by any local Sone.
380          *
381          * @param sone
382          *              The Sone to get the time for
383          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
384          *         followed, or {@link Long#MAX_VALUE}
385          */
386         public long getSoneFollowingTime(Sone sone) {
387                 synchronized (soneFollowingTimes) {
388                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
389                 }
390         }
391
392         /**
393          * Returns whether the given post is bookmarked.
394          *
395          * @param post
396          *              The post to check
397          * @return {@code true} if the given post is bookmarked, {@code false}
398          *         otherwise
399          */
400         public boolean isBookmarked(Post post) {
401                 return isPostBookmarked(post.getId());
402         }
403
404         /**
405          * Returns whether the post with the given ID is bookmarked.
406          *
407          * @param id
408          *              The ID of the post to check
409          * @return {@code true} if the post with the given ID is bookmarked, {@code
410          *         false} otherwise
411          */
412         public boolean isPostBookmarked(String id) {
413                 synchronized (bookmarkedPosts) {
414                         return bookmarkedPosts.contains(id);
415                 }
416         }
417
418         /**
419          * Returns all currently known bookmarked posts.
420          *
421          * @return All bookmarked posts
422          */
423         public Set<Post> getBookmarkedPosts() {
424                 Set<Post> posts = new HashSet<Post>();
425                 synchronized (bookmarkedPosts) {
426                         for (String bookmarkedPostId : bookmarkedPosts) {
427                                 Optional<Post> post = database.getPost(bookmarkedPostId);
428                                 if (post.isPresent()) {
429                                         posts.add(post.get());
430                                 }
431                         }
432                 }
433                 return posts;
434         }
435
436         public Optional<Album> getAlbum(String albumId) {
437                 return database.getAlbum(albumId);
438         }
439
440         public Optional<Image> getImage(String imageId) {
441                 return database.getImage(imageId);
442         }
443
444         /**
445          * Returns the temporary image with the given ID.
446          *
447          * @param imageId
448          *              The ID of the temporary image
449          * @return The temporary image, or {@code null} if there is no temporary image
450          *         with the given ID
451          */
452         public TemporaryImage getTemporaryImage(String imageId) {
453                 synchronized (temporaryImages) {
454                         return temporaryImages.get(imageId);
455                 }
456         }
457
458         //
459         // ACTIONS
460         //
461
462         /**
463          * Locks the given Sone. A locked Sone will not be inserted by {@link
464          * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
465          *
466          * @param sone
467          *              The sone to lock
468          */
469         public void lockSone(Sone sone) {
470                 synchronized (lockedSones) {
471                         if (lockedSones.add(sone)) {
472                                 eventBus.post(new SoneLockedEvent(sone));
473                         }
474                 }
475         }
476
477         /**
478          * Unlocks the given Sone.
479          *
480          * @param sone
481          *              The sone to unlock
482          * @see #lockSone(Sone)
483          */
484         public void unlockSone(Sone sone) {
485                 synchronized (lockedSones) {
486                         if (lockedSones.remove(sone)) {
487                                 eventBus.post(new SoneUnlockedEvent(sone));
488                         }
489                 }
490         }
491
492         /**
493          * Adds a local Sone from the given own identity.
494          *
495          * @param ownIdentity
496          *              The own identity to create a Sone from
497          * @return The added (or already existing) Sone
498          */
499         public Sone addLocalSone(OwnIdentity ownIdentity) {
500                 if (ownIdentity == null) {
501                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
502                         return null;
503                 }
504                 logger.info(format("Adding Sone from OwnIdentity: %s", ownIdentity));
505                 synchronized (soneRescuers) {
506                         final Sone sone;
507                         sone = database.newSoneBuilder().by(ownIdentity.getId()).local().using(new Client("Sone", SonePlugin.VERSION.toString())).build(Optional.<SoneCreated>absent());
508                         sone.modify().setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0)).update();
509                         sone.setKnown(true);
510                         /* TODO - load posts ’n stuff */
511                         database.storeSone(sone);
512                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
513                         soneInserters.put(sone, soneInserter);
514                         sone.setStatus(SoneStatus.idle);
515                         loadSone(sone);
516                         soneInserter.start();
517                         return sone;
518                 }
519         }
520
521         /**
522          * Creates a new Sone for the given own identity.
523          *
524          * @param ownIdentity
525          *              The own identity to create a Sone for
526          * @return The created Sone
527          */
528         public Sone createSone(OwnIdentity ownIdentity) {
529                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
530                         logger.log(Level.SEVERE, format("Could not add “Sone” context to own identity: %s", ownIdentity));
531                         return null;
532                 }
533                 Sone sone = addLocalSone(ownIdentity);
534                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
535                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
536                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
537                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
538                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
539                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
540
541                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
542                 touchConfiguration();
543                 return sone;
544         }
545
546         /**
547          * Adds the Sone of the given identity.
548          *
549          * @param identity
550          *              The identity whose Sone to add
551          * @return The added or already existing Sone
552          */
553         public Sone addRemoteSone(Identity identity) {
554                 if (identity == null) {
555                         logger.log(Level.WARNING, "Given Identity is null!");
556                         return null;
557                 }
558                 synchronized (soneRescuers) {
559                         Optional<Sone> existingSone = database.getSone(identity.getId());
560                         if (existingSone.isPresent() && existingSone.get().isLocal()) {
561                                 return existingSone.get();
562                         }
563                         boolean newSone = !existingSone.isPresent();
564                         final Sone sone = newSone ? database.newSoneBuilder().by(identity.getId()).using(new Client("Sone", SonePlugin.VERSION.toString())).build(Optional.<SoneCreated>absent()) : existingSone.get();
565                         sone.modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0)).update();
566                         if (newSone) {
567                                 synchronized (knownSones) {
568                                         newSone = !knownSones.contains(sone.getId());
569                                 }
570                                 sone.setKnown(!newSone);
571                                 if (newSone) {
572                                         eventBus.post(new NewSoneFoundEvent(sone));
573                                         for (Sone localSone : getLocalSones()) {
574                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
575                                                         followSone(localSone, sone.getId());
576                                                 }
577                                         }
578                                 }
579                         }
580                         soneDownloader.addSone(sone);
581                         soneDownloaders.execute(new Runnable() {
582
583                                 @Override
584                                 @SuppressWarnings("synthetic-access")
585                                 public void run() {
586                                         soneDownloader.fetchSone(sone, TO_FREENET_URI.apply(sone));
587                                 }
588
589                         });
590                         return sone;
591                 }
592         }
593
594         /**
595          * Lets the given local Sone follow the Sone with the given ID.
596          *
597          * @param sone
598          *              The local Sone that should follow another Sone
599          * @param soneId
600          *              The ID of the Sone to follow
601          */
602         public void followSone(Sone sone, String soneId) {
603                 checkNotNull(sone, "sone must not be null");
604                 checkNotNull(soneId, "soneId must not be null");
605                 sone.addFriend(soneId);
606                 synchronized (soneFollowingTimes) {
607                         if (!soneFollowingTimes.containsKey(soneId)) {
608                                 long now = System.currentTimeMillis();
609                                 soneFollowingTimes.put(soneId, now);
610                                 Optional<Sone> followedSone = getSone(soneId);
611                                 if (!followedSone.isPresent()) {
612                                         return;
613                                 }
614                                 for (Post post : followedSone.get().getPosts()) {
615                                         if (post.getTime() < now) {
616                                                 markPostKnown(post);
617                                         }
618                                 }
619                                 for (PostReply reply : followedSone.get().getReplies()) {
620                                         if (reply.getTime() < now) {
621                                                 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
622                                         }
623                                 }
624                         }
625                 }
626                 touchConfiguration();
627         }
628
629         /**
630          * Lets the given local Sone unfollow the Sone with the given ID.
631          *
632          * @param sone
633          *              The local Sone that should unfollow another Sone
634          * @param soneId
635          *              The ID of the Sone being unfollowed
636          */
637         public void unfollowSone(Sone sone, String soneId) {
638                 checkNotNull(sone, "sone must not be null");
639                 checkNotNull(soneId, "soneId must not be null");
640                 sone.removeFriend(soneId);
641                 boolean unfollowedSoneStillFollowed = false;
642                 for (Sone localSone : getLocalSones()) {
643                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
644                 }
645                 if (!unfollowedSoneStillFollowed) {
646                         synchronized (soneFollowingTimes) {
647                                 soneFollowingTimes.remove(soneId);
648                         }
649                 }
650                 touchConfiguration();
651         }
652
653         /**
654          * Sets the trust value of the given origin Sone for the target Sone.
655          *
656          * @param origin
657          *              The origin Sone
658          * @param target
659          *              The target Sone
660          * @param trustValue
661          *              The trust value (from {@code -100} to {@code 100})
662          */
663         public void setTrust(Sone origin, Sone target, int trustValue) {
664                 checkNotNull(origin, "origin must not be null");
665                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
666                 checkNotNull(target, "target must not be null");
667                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
668                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
669         }
670
671         /**
672          * Removes any trust assignment for the given target Sone.
673          *
674          * @param origin
675          *              The trust origin
676          * @param target
677          *              The trust target
678          */
679         public void removeTrust(Sone origin, Sone target) {
680                 checkNotNull(origin, "origin must not be null");
681                 checkNotNull(target, "target must not be null");
682                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
683                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
684         }
685
686         /**
687          * Assigns the configured positive trust value for the given target.
688          *
689          * @param origin
690          *              The trust origin
691          * @param target
692          *              The trust target
693          */
694         public void trustSone(Sone origin, Sone target) {
695                 setTrust(origin, target, preferences.getPositiveTrust());
696         }
697
698         /**
699          * Assigns the configured negative trust value for the given target.
700          *
701          * @param origin
702          *              The trust origin
703          * @param target
704          *              The trust target
705          */
706         public void distrustSone(Sone origin, Sone target) {
707                 setTrust(origin, target, preferences.getNegativeTrust());
708         }
709
710         /**
711          * Removes the trust assignment for the given target.
712          *
713          * @param origin
714          *              The trust origin
715          * @param target
716          *              The trust target
717          */
718         public void untrustSone(Sone origin, Sone target) {
719                 removeTrust(origin, target);
720         }
721
722         /**
723          * Updates the stored Sone with the given Sone.
724          *
725          * @param sone
726          *              The updated Sone
727          */
728         public void updateSone(Sone sone) {
729                 updateSone(sone, false);
730         }
731
732         /**
733          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
734          * {@code true}, an older Sone than the current Sone can be given to restore an
735          * old state.
736          *
737          * @param sone
738          *              The Sone to update
739          * @param soneRescueMode
740          *              {@code true} if the stored Sone should be updated regardless of the age of
741          *              the given Sone
742          */
743         public void updateSone(Sone sone, boolean soneRescueMode) {
744                 Optional<Sone> storedSone = getSone(sone.getId());
745                 if (storedSone.isPresent()) {
746                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
747                                 logger.log(Level.FINE, format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
748                                 return;
749                         }
750                         /* find removed posts. */
751                         Collection<Post> existingPosts = database.getPosts(sone.getId());
752                         for (Post oldPost : existingPosts) {
753                                 if (!sone.getPosts().contains(oldPost)) {
754                                         eventBus.post(new PostRemovedEvent(oldPost));
755                                 }
756                         }
757                         /* find new posts. */
758                         for (Post newPost : sone.getPosts()) {
759                                 if (existingPosts.contains(newPost)) {
760                                         continue;
761                                 }
762                                 if (newPost.getTime() < getSoneFollowingTime(sone)) {
763                                         newPost.setKnown();
764                                 } else if (!newPost.isKnown()) {
765                                         eventBus.post(new NewPostFoundEvent(newPost));
766                                 }
767                         }
768                         /* store posts. */
769                         database.storePosts(sone, sone.getPosts());
770                         if (!soneRescueMode) {
771                                 for (PostReply reply : storedSone.get().getReplies()) {
772                                         if (!sone.getReplies().contains(reply)) {
773                                                 eventBus.post(new PostReplyRemovedEvent(reply));
774                                         }
775                                 }
776                         }
777                         Set<PostReply> storedReplies = storedSone.get().getReplies();
778                         for (PostReply reply : sone.getReplies()) {
779                                 if (storedReplies.contains(reply)) {
780                                         continue;
781                                 }
782                                 if (reply.getTime() < getSoneFollowingTime(sone)) {
783                                         reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
784                                 } else if (!reply.isKnown()) {
785                                         eventBus.post(new NewPostReplyFoundEvent(reply));
786                                 }
787                         }
788                         database.storePostReplies(sone, sone.getReplies());
789                         for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
790                                 database.removeAlbum(album);
791                                 for (Image image : album.getImages()) {
792                                         database.removeImage(image);
793                                 }
794                         }
795                         for (Album album : sone.getRootAlbum().getAlbums()) {
796                                 database.storeAlbum(album);
797                                 for (Image image : album.getImages()) {
798                                         database.storeImage(image);
799                                 }
800                         }
801                         synchronized (soneRescuers) {
802                                 sone.setOptions(storedSone.get().getOptions());
803                                 sone.setKnown(storedSone.get().isKnown());
804                                 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
805                                 if (sone.isLocal()) {
806                                         soneInserters.get(storedSone.get()).setSone(sone);
807                                         touchConfiguration();
808                                 }
809                                 database.storeSone(sone);
810                         }
811                 }
812         }
813
814         /**
815          * Deletes the given Sone. This will remove the Sone from the {@link
816          * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
817          * context from its identity.
818          *
819          * @param sone
820          *              The Sone to delete
821          */
822         public void deleteSone(Sone sone) {
823                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
824                         logger.log(Level.WARNING, format("Tried to delete Sone of non-own identity: %s", sone));
825                         return;
826                 }
827                 synchronized (soneRescuers) {
828                         if (!getLocalSones().contains(sone)) {
829                                 logger.log(Level.WARNING, format("Tried to delete non-local Sone: %s", sone));
830                                 return;
831                         }
832                         SoneInserter soneInserter = soneInserters.remove(sone);
833                         soneInserter.stop();
834                 }
835                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
836                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
837                 try {
838                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
839                 } catch (ConfigurationException ce1) {
840                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
841                 }
842         }
843
844         /**
845          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
846          * known} before, a {@link MarkSoneKnownEvent} is fired.
847          *
848          * @param sone
849          *              The Sone to mark as known
850          */
851         public void markSoneKnown(Sone sone) {
852                 if (!sone.isKnown()) {
853                         sone.setKnown(true);
854                         synchronized (knownSones) {
855                                 knownSones.add(sone.getId());
856                         }
857                         eventBus.post(new MarkSoneKnownEvent(sone));
858                         touchConfiguration();
859                 }
860         }
861
862         /**
863          * Loads and updates the given Sone from the configuration. If any error is
864          * encountered, loading is aborted and the given Sone is not changed.
865          *
866          * @param sone
867          *              The Sone to load and update
868          */
869         public void loadSone(Sone sone) {
870                 if (!sone.isLocal()) {
871                         logger.log(Level.FINE, format("Tried to load non-local Sone: %s", sone));
872                         return;
873                 }
874                 logger.info(format("Loading local Sone: %s", sone));
875
876                 /* initialize options. */
877                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
878                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
879                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
880                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
881                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
882                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
883
884                 /* load Sone. */
885                 String sonePrefix = "Sone/" + sone.getId();
886                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
887                 if (soneTime == null) {
888                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
889                         return;
890                 }
891                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
892
893                 /* load profile. */
894                 Profile profile = new Profile(sone);
895                 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
896                 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
897                 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
898                 profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
899                 Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
900                 Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
901                 Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
902                 profile.modify().setBirthYear(birthYear).setBirthMonth(birthMonth).setBirthDay(birthDay).update();
903
904                 /* load profile fields. */
905                 while (true) {
906                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
907                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
908                         if (fieldName == null) {
909                                 break;
910                         }
911                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
912                         profile.setField(profile.addField(fieldName), fieldValue);
913                 }
914
915                 /* load posts. */
916                 Set<Post> posts = new HashSet<Post>();
917                 while (true) {
918                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
919                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
920                         if (postId == null) {
921                                 break;
922                         }
923                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
924                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
925                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
926                         if ((postTime == 0) || (postText == null)) {
927                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
928                                 return;
929                         }
930                         PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
931                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
932                                 postBuilder.to(of(postRecipientId));
933                         }
934                         posts.add(postBuilder.build(Optional.<PostCreated>absent()));
935                 }
936
937                 /* load replies. */
938                 Set<PostReply> replies = new HashSet<PostReply>();
939                 while (true) {
940                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
941                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
942                         if (replyId == null) {
943                                 break;
944                         }
945                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
946                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
947                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
948                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
949                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
950                                 return;
951                         }
952                         PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
953                         replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
954                 }
955
956                 /* load post likes. */
957                 Set<String> likedPostIds = new HashSet<String>();
958                 while (true) {
959                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
960                         if (likedPostId == null) {
961                                 break;
962                         }
963                         likedPostIds.add(likedPostId);
964                 }
965
966                 /* load reply likes. */
967                 Set<String> likedReplyIds = new HashSet<String>();
968                 while (true) {
969                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
970                         if (likedReplyId == null) {
971                                 break;
972                         }
973                         likedReplyIds.add(likedReplyId);
974                 }
975
976                 /* load friends. */
977                 Set<String> friends = new HashSet<String>();
978                 while (true) {
979                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
980                         if (friendId == null) {
981                                 break;
982                         }
983                         friends.add(friendId);
984                 }
985
986                 /* load albums. */
987                 Map<String, Album> albums = Maps.newHashMap();
988                 int albumCounter = 0;
989                 while (true) {
990                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
991                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
992                         if (albumId == null) {
993                                 break;
994                         }
995                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
996                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
997                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
998                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
999                         if ((albumTitle == null) || (albumDescription == null)) {
1000                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1001                                 return;
1002                         }
1003                         Album parentAlbum = sone.getRootAlbum();
1004                         if (albumParentId != null) {
1005                                 parentAlbum = albums.get(albumParentId);
1006                         }
1007                         Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1008                         albums.put(album.getId(), album);
1009                 }
1010
1011                 /* load images. */
1012                 int imageCounter = 0;
1013                 while (true) {
1014                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1015                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1016                         if (imageId == null) {
1017                                 break;
1018                         }
1019                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1020                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1021                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1022                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1023                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1024                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1025                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1026                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1027                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1028                                 return;
1029                         }
1030                         Album album = albums.get(albumId);
1031                         if (album == null) {
1032                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1033                                 return;
1034                         }
1035                         album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1036                 }
1037
1038                 /* load avatar. */
1039                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1040                 if (avatarId != null) {
1041                         profile.setAvatar(getImage(avatarId).transform(GET_ID));
1042                 }
1043
1044                 /* load options. */
1045                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1046                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1047                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1048                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1049                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1050                 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1051
1052                 /* if we’re still here, Sone was loaded successfully. */
1053                 synchronized (sone) {
1054                         sone.setTime(soneTime);
1055                         sone.setProfile(profile);
1056                         sone.setPosts(posts);
1057                         sone.setReplies(replies);
1058                         sone.setLikePostIds(likedPostIds);
1059                         sone.setLikeReplyIds(likedReplyIds);
1060                         for (String friendId : friends) {
1061                                 followSone(sone, friendId);
1062                         }
1063                         for (Album album : sone.getRootAlbum().getAlbums()) {
1064                                 album.remove();
1065                         }
1066                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1067                 }
1068                 synchronized (knownSones) {
1069                         for (String friend : friends) {
1070                                 knownSones.add(friend);
1071                         }
1072                 }
1073                 database.storePosts(sone, posts);
1074                 for (Post post : posts) {
1075                         post.setKnown();
1076                 }
1077                 database.storePostReplies(sone, replies);
1078                 for (PostReply reply : replies) {
1079                         reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
1080                 }
1081
1082                 logger.info(format("Sone loaded successfully: %s", sone));
1083         }
1084
1085         /**
1086          * Deletes the given post.
1087          *
1088          * @param post
1089          *              The post to delete
1090          */
1091         public void deletePost(Post post) {
1092                 if (!post.getSone().isLocal()) {
1093                         logger.log(Level.WARNING, format("Tried to delete post of non-local Sone: %s", post.getSone()));
1094                         return;
1095                 }
1096                 database.removePost(post);
1097                 eventBus.post(new PostRemovedEvent(post));
1098                 markPostKnown(post);
1099                 touchConfiguration();
1100         }
1101
1102         /**
1103          * Marks the given post as known, if it is currently not a known post
1104          * (according to {@link Post#isKnown()}).
1105          *
1106          * @param post
1107          *              The post to mark as known
1108          */
1109         public void markPostKnown(Post post) {
1110                 post.setKnown();
1111                 eventBus.post(new MarkPostKnownEvent(post));
1112                 touchConfiguration();
1113                 for (PostReply reply : post.getReplies()) {
1114                         reply.modify().setKnown().update(postReplyUpdated());
1115                 }
1116         }
1117
1118         /**
1119          * Bookmarks the post with the given ID.
1120          *
1121          * @param id
1122          *              The ID of the post to bookmark
1123          */
1124         public void bookmarkPost(String id) {
1125                 synchronized (bookmarkedPosts) {
1126                         bookmarkedPosts.add(id);
1127                 }
1128         }
1129
1130         /**
1131          * Removes the given post from the bookmarks.
1132          *
1133          * @param post
1134          *              The post to unbookmark
1135          */
1136         public void unbookmark(Post post) {
1137                 unbookmarkPost(post.getId());
1138         }
1139
1140         /**
1141          * Removes the post with the given ID from the bookmarks.
1142          *
1143          * @param id
1144          *              The ID of the post to unbookmark
1145          */
1146         public void unbookmarkPost(String id) {
1147                 synchronized (bookmarkedPosts) {
1148                         bookmarkedPosts.remove(id);
1149                 }
1150         }
1151
1152         /**
1153          * Deletes the given reply.
1154          *
1155          * @param reply
1156          *              The reply to delete
1157          */
1158         public void deleteReply(PostReply reply) {
1159                 Sone sone = reply.getSone();
1160                 if (!sone.isLocal()) {
1161                         logger.log(Level.FINE, format("Tried to delete non-local reply: %s", reply));
1162                         return;
1163                 }
1164                 postReplyUpdated().get().replyUpdated(reply);
1165                 database.removePostReply(reply);
1166                 touchConfiguration();
1167         }
1168
1169         /**
1170          * Creates a new image.
1171          *
1172          * @param sone
1173          *              The Sone creating the image
1174          * @param album
1175          *              The album the image will be inserted into
1176          * @param temporaryImage
1177          *              The temporary image to create the image from
1178          * @return The newly created image
1179          */
1180         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1181                 checkNotNull(sone, "sone must not be null");
1182                 checkNotNull(album, "album must not be null");
1183                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1184                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1185                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1186                 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1187                 imageInserter.insertImage(temporaryImage, image);
1188                 return image;
1189         }
1190
1191         /**
1192          * Deletes the given image. This method will also delete a matching temporary
1193          * image.
1194          *
1195          * @param image
1196          *              The image to delete
1197          * @see #deleteTemporaryImage(String)
1198          */
1199         public void deleteImage(Image image) {
1200                 checkNotNull(image, "image must not be null");
1201                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1202                 deleteTemporaryImage(image.getId());
1203                 image.remove();
1204                 touchConfiguration();
1205         }
1206
1207         /**
1208          * Creates a new temporary image.
1209          *
1210          * @param mimeType
1211          *              The MIME type of the temporary image
1212          * @param imageData
1213          *              The encoded data of the image
1214          * @return The temporary image
1215          */
1216         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1217                 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1218                 synchronized (temporaryImages) {
1219                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1220                 }
1221                 return temporaryImage;
1222         }
1223
1224         /**
1225          * Deletes the temporary image with the given ID.
1226          *
1227          * @param imageId
1228          *              The ID of the temporary image to delete
1229          */
1230         public void deleteTemporaryImage(String imageId) {
1231                 checkNotNull(imageId, "imageId must not be null");
1232                 synchronized (temporaryImages) {
1233                         temporaryImages.remove(imageId);
1234                 }
1235                 Optional<Image> image = getImage(imageId);
1236                 if (image.isPresent()) {
1237                         imageInserter.cancelImageInsert(image.get());
1238                 }
1239         }
1240
1241         /**
1242          * Notifies the core that the configuration, either of the core or of a single
1243          * local Sone, has changed, and that the configuration should be saved.
1244          */
1245         public void touchConfiguration() {
1246                 lastConfigurationUpdate = System.currentTimeMillis();
1247         }
1248
1249         //
1250         // SERVICE METHODS
1251         //
1252
1253         @Override
1254         public void serviceStart() {
1255                 loadConfiguration();
1256                 updateChecker.start();
1257                 identityManager.start();
1258                 webOfTrustUpdater.init();
1259                 webOfTrustUpdater.start();
1260                 database.start();
1261         }
1262
1263         @Override
1264         public void serviceRun() {
1265                 long lastSaved = System.currentTimeMillis();
1266                 while (!shouldStop()) {
1267                         sleep(1000);
1268                         long now = System.currentTimeMillis();
1269                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1270                                 for (Sone localSone : getLocalSones()) {
1271                                         saveSone(localSone);
1272                                 }
1273                                 saveConfiguration();
1274                                 lastSaved = now;
1275                         }
1276                 }
1277         }
1278
1279         @Override
1280         public void serviceStop() {
1281                 localElementTicker.shutdownNow();
1282                 synchronized (soneRescuers) {
1283                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1284                                 soneInserter.getValue().stop();
1285                                 saveSone(soneInserter.getKey());
1286                         }
1287                 }
1288                 saveConfiguration();
1289                 database.stop();
1290                 webOfTrustUpdater.stop();
1291                 updateChecker.stop();
1292                 soneDownloader.stop();
1293                 identityManager.stop();
1294                 soneDownloaders.shutdownNow();
1295         }
1296
1297         //
1298         // PRIVATE METHODS
1299         //
1300
1301         /**
1302          * Saves the given Sone. This will persist all local settings for the given
1303          * Sone, such as the friends list and similar, private options.
1304          *
1305          * @param sone
1306          *              The Sone to save
1307          */
1308         private synchronized void saveSone(Sone sone) {
1309                 if (!sone.isLocal()) {
1310                         logger.log(Level.FINE, format("Tried to save non-local Sone: %s", sone));
1311                         return;
1312                 }
1313                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1314                         logger.log(Level.WARNING, format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1315                         return;
1316                 }
1317
1318                 logger.log(Level.INFO, format("Saving Sone: %s", sone));
1319                 try {
1320                         /* save Sone into configuration. */
1321                         String sonePrefix = "Sone/" + sone.getId();
1322                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1323                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1324
1325                         /* save profile. */
1326                         Profile profile = sone.getProfile();
1327                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1328                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1329                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1330                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1331                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1332                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1333                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1334
1335                         /* save profile fields. */
1336                         int fieldCounter = 0;
1337                         for (Field profileField : profile.getFields()) {
1338                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1339                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1340                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1341                         }
1342                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1343
1344                         /* save posts. */
1345                         int postCounter = 0;
1346                         for (Post post : sone.getPosts()) {
1347                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1348                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1349                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1350                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1351                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1352                         }
1353                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1354
1355                         /* save replies. */
1356                         int replyCounter = 0;
1357                         for (PostReply reply : sone.getReplies()) {
1358                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1359                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1360                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1361                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1362                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1363                         }
1364                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1365
1366                         /* save post likes. */
1367                         int postLikeCounter = 0;
1368                         for (String postId : sone.getLikedPostIds()) {
1369                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1370                         }
1371                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1372
1373                         /* save reply likes. */
1374                         int replyLikeCounter = 0;
1375                         for (String replyId : sone.getLikedReplyIds()) {
1376                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1377                         }
1378                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1379
1380                         /* save friends. */
1381                         int friendCounter = 0;
1382                         for (String friendId : sone.getFriends()) {
1383                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1384                         }
1385                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1386
1387                         /* save albums. first, collect in a flat structure, top-level first. */
1388                         List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1389
1390                         int albumCounter = 0;
1391                         for (Album album : albums) {
1392                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1393                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1394                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1395                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1396                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1397                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1398                         }
1399                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1400
1401                         /* save images. */
1402                         int imageCounter = 0;
1403                         for (Album album : albums) {
1404                                 for (Image image : album.getImages()) {
1405                                         if (!image.isInserted()) {
1406                                                 continue;
1407                                         }
1408                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1409                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1410                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1411                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1412                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1413                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1414                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1415                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1416                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1417                                 }
1418                         }
1419                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1420
1421                         /* save options. */
1422                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1423                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1424                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1425                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1426                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1427                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1428
1429                         configuration.save();
1430
1431                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1432
1433                         logger.log(Level.INFO, format("Sone %s saved.", sone));
1434                 } catch (ConfigurationException ce1) {
1435                         logger.log(Level.WARNING, format("Could not save Sone: %s", sone), ce1);
1436                 }
1437         }
1438
1439         /** Saves the current options. */
1440         private void saveConfiguration() {
1441                 synchronized (configuration) {
1442                         if (storingConfiguration) {
1443                                 logger.log(Level.FINE, "Already storing configuration…");
1444                                 return;
1445                         }
1446                         storingConfiguration = true;
1447                 }
1448
1449                 /* store the options first. */
1450                 try {
1451                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1452                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1453                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1454                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1455                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1456                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1457                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1458                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1459                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1460                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1461                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1462                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1463
1464                         /* save known Sones. */
1465                         int soneCounter = 0;
1466                         synchronized (knownSones) {
1467                                 for (String knownSoneId : knownSones) {
1468                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1469                                 }
1470                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1471                         }
1472
1473                         /* save Sone following times. */
1474                         soneCounter = 0;
1475                         synchronized (soneFollowingTimes) {
1476                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1477                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1478                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1479                                         ++soneCounter;
1480                                 }
1481                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1482                         }
1483
1484                         /* save bookmarked posts. */
1485                         int bookmarkedPostCounter = 0;
1486                         synchronized (bookmarkedPosts) {
1487                                 for (String bookmarkedPostId : bookmarkedPosts) {
1488                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1489                                 }
1490                         }
1491                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1492
1493                         /* now save it. */
1494                         configuration.save();
1495
1496                 } catch (ConfigurationException ce1) {
1497                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1498                 } finally {
1499                         synchronized (configuration) {
1500                                 storingConfiguration = false;
1501                         }
1502                 }
1503         }
1504
1505         /** Loads the configuration. */
1506         private void loadConfiguration() {
1507                 /* create options. */
1508                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1509
1510                         @Override
1511                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1512                                 SoneInserter.setInsertionDelay(newValue);
1513                         }
1514
1515                 }));
1516                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1517                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1518                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1519                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1520                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1521                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1522                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1523                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1524                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1525
1526                         @Override
1527                         @SuppressWarnings("synthetic-access")
1528                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1529                                 fcpInterface.setActive(newValue);
1530                         }
1531                 }));
1532                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1533
1534                         @Override
1535                         @SuppressWarnings("synthetic-access")
1536                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1537                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1538                         }
1539
1540                 }));
1541
1542                 loadConfigurationValue("InsertionDelay");
1543                 loadConfigurationValue("PostsPerPage");
1544                 loadConfigurationValue("ImagesPerPage");
1545                 loadConfigurationValue("CharactersPerPost");
1546                 loadConfigurationValue("PostCutOffLength");
1547                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1548                 loadConfigurationValue("PositiveTrust");
1549                 loadConfigurationValue("NegativeTrust");
1550                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1551                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1552                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1553
1554                 /* load known Sones. */
1555                 int soneCounter = 0;
1556                 while (true) {
1557                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1558                         if (knownSoneId == null) {
1559                                 break;
1560                         }
1561                         synchronized (knownSones) {
1562                                 knownSones.add(knownSoneId);
1563                         }
1564                 }
1565
1566                 /* load Sone following times. */
1567                 soneCounter = 0;
1568                 while (true) {
1569                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1570                         if (soneId == null) {
1571                                 break;
1572                         }
1573                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1574                         synchronized (soneFollowingTimes) {
1575                                 soneFollowingTimes.put(soneId, time);
1576                         }
1577                         ++soneCounter;
1578                 }
1579
1580                 /* load bookmarked posts. */
1581                 int bookmarkedPostCounter = 0;
1582                 while (true) {
1583                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1584                         if (bookmarkedPostId == null) {
1585                                 break;
1586                         }
1587                         synchronized (bookmarkedPosts) {
1588                                 bookmarkedPosts.add(bookmarkedPostId);
1589                         }
1590                 }
1591
1592         }
1593
1594         /**
1595          * Loads an {@link Integer} configuration value for the option with the given
1596          * name, logging validation failures.
1597          *
1598          * @param optionName
1599          *              The name of the option to load
1600          */
1601         private void loadConfigurationValue(String optionName) {
1602                 try {
1603                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1604                 } catch (IllegalArgumentException iae1) {
1605                         logger.log(Level.WARNING, format("Invalid value for %s in configuration, using default.", optionName));
1606                 }
1607         }
1608
1609         /**
1610          * Notifies the core that a new {@link OwnIdentity} was added.
1611          *
1612          * @param ownIdentityAddedEvent
1613          *              The event
1614          */
1615         @Subscribe
1616         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1617                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1618                 logger.log(Level.FINEST, format("Adding OwnIdentity: %s", ownIdentity));
1619                 if (ownIdentity.hasContext("Sone")) {
1620                         database.storeIdentity(ownIdentity);
1621                         addLocalSone(ownIdentity);
1622                 }
1623         }
1624
1625         /**
1626          * Notifies the core that an {@link OwnIdentity} was removed.
1627          *
1628          * @param ownIdentityRemovedEvent
1629          *              The event
1630          */
1631         @Subscribe
1632         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1633                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1634                 logger.log(Level.FINEST, format("Removing OwnIdentity: %s", ownIdentity));
1635                 trustedIdentities.removeAll(ownIdentity);
1636         }
1637
1638         /**
1639          * Notifies the core that a new {@link Identity} was added.
1640          *
1641          * @param identityAddedEvent
1642          *              The event
1643          */
1644         @Subscribe
1645         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1646                 Identity identity = identityAddedEvent.identity();
1647                 logger.log(Level.FINEST, format("Adding Identity: %s", identity));
1648                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1649                 database.storeIdentity(identity);
1650                 addRemoteSone(identity);
1651         }
1652
1653         /**
1654          * Notifies the core that an {@link Identity} was updated.
1655          *
1656          * @param identityUpdatedEvent
1657          *              The event
1658          */
1659         @Subscribe
1660         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1661                 final Identity identity = identityUpdatedEvent.identity();
1662                 database.storeIdentity(identity);
1663                 soneDownloaders.execute(new Runnable() {
1664
1665                         @Override
1666                         @SuppressWarnings("synthetic-access")
1667                         public void run() {
1668                                 Optional<Sone> sone = getRemoteSone(identity.getId());
1669                                 sone.get().modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition())).update();
1670                                 soneDownloader.addSone(sone.get());
1671                                 soneDownloader.fetchSone(sone.get());
1672                         }
1673                 });
1674         }
1675
1676         /**
1677          * Notifies the core that an {@link Identity} was removed.
1678          *
1679          * @param identityRemovedEvent
1680          *              The event
1681          */
1682         @Subscribe
1683         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1684                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1685                 Identity identity = identityRemovedEvent.identity();
1686                 trustedIdentities.remove(ownIdentity, identity);
1687                 boolean foundIdentity = false;
1688                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1689                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1690                                 continue;
1691                         }
1692                         if (trustedIdentity.getValue().contains(identity)) {
1693                                 foundIdentity = true;
1694                         }
1695                 }
1696                 if (foundIdentity) {
1697                         /* some local identity still trusts this identity, don’t remove. */
1698                         return;
1699                 }
1700                 Optional<Sone> sone = getSone(identity.getId());
1701                 if (!sone.isPresent()) {
1702                         /* TODO - we don’t have the Sone anymore. should this happen? */
1703                         return;
1704                 }
1705                 database.removePosts(sone.get());
1706                 for (Post post : sone.get().getPosts()) {
1707                         eventBus.post(new PostRemovedEvent(post));
1708                 }
1709                 database.removePostReplies(sone.get());
1710                 for (PostReply reply : sone.get().getReplies()) {
1711                         eventBus.post(new PostReplyRemovedEvent(reply));
1712                 }
1713                 eventBus.post(new SoneRemovedEvent(sone.get()));
1714         }
1715
1716         /**
1717          * Deletes the temporary image.
1718          *
1719          * @param imageInsertFinishedEvent
1720          *              The event
1721          */
1722         @Subscribe
1723         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1724                 logger.log(Level.WARNING, format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1725                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1726                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1727                 touchConfiguration();
1728         }
1729
1730         public Optional<PostCreated> postCreated() {
1731                 return Optional.<PostCreated>of(new PostCreated() {
1732                         @Override
1733                         public void postCreated(final Post post) {
1734                                 if (post.isKnown()) {
1735                                         return;
1736                                 }
1737                                 eventBus.post(new NewPostFoundEvent(post));
1738                                 if (post.getSone().isLocal()) {
1739                                         localElementTicker.schedule(new Runnable() {
1740                                                 @Override
1741                                                 public void run() {
1742                                                         markPostKnown(post);
1743                                                 }
1744                                         }, 10, TimeUnit.SECONDS);
1745                                 }
1746                         }
1747                 });
1748         }
1749
1750         public Optional<PostReplyCreated> postReplyCreated() {
1751                 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1752                         @Override
1753                         public void postReplyCreated(final PostReply postReply) {
1754                                 if (postReply.isKnown()) {
1755                                         return;
1756                                 }
1757                                 eventBus.post(new NewPostReplyFoundEvent(postReply));
1758                                 if (postReply.getSone().isLocal()) {
1759                                         localElementTicker.schedule(new Runnable() {
1760
1761                                                 /**
1762                                                  * {@inheritDoc}
1763                                                  */
1764                                                 @Override
1765                                                 public void run() {
1766                                                         postReplyUpdated().get().replyUpdated(postReply);
1767                                                 }
1768                                         }, 10, TimeUnit.SECONDS);
1769                                 }
1770                         }
1771                 });
1772         }
1773
1774         public Optional<ReplyUpdated<PostReply>> postReplyUpdated() {
1775                 return Optional.<ReplyUpdated<PostReply>>of(new ReplyUpdated<PostReply>() {
1776                         @Override
1777                         public void replyUpdated(PostReply reply) {
1778                                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1779                         }
1780                 });
1781         }
1782
1783         public Optional<ImageCreated> imageCreated() {
1784                 return Optional.<ImageCreated>of(new ImageCreated() {
1785                         @Override
1786                         public void imageCreated(Image image) {
1787                                 /* nothing happens here yet. */
1788                         }
1789                 });
1790         }
1791
1792 }