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