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