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