Return local Sones from core and web 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.util.logging.Logger.getLogger;
25
26 import java.util.ArrayList;
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.SoneChangeDetector.PostProcessor;
42 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.data.Album;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.LocalSone;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.TemporaryImage;
65 import net.pterodactylus.sone.database.AlbumBuilder;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.ImageBuilder;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneBuilder;
74 import net.pterodactylus.sone.database.SoneProvider;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.service.AbstractService;
86 import net.pterodactylus.util.thread.NamedThreadFactory;
87
88 import com.google.common.annotations.VisibleForTesting;
89 import com.google.common.base.Function;
90 import com.google.common.base.Optional;
91 import com.google.common.collect.HashMultimap;
92 import com.google.common.collect.Multimap;
93 import com.google.common.collect.Multimaps;
94 import com.google.common.eventbus.EventBus;
95 import com.google.common.eventbus.Subscribe;
96 import com.google.inject.Inject;
97 import com.google.inject.Singleton;
98
99 /**
100  * The Sone core.
101  *
102  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103  */
104 @Singleton
105 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
106
107         /** The logger. */
108         private static final Logger logger = getLogger("Sone.Core");
109
110         /** The start time. */
111         private final long startupTime = System.currentTimeMillis();
112
113         /** The preferences. */
114         private final Preferences preferences;
115
116         /** The event bus. */
117         private final EventBus eventBus;
118
119         /** The configuration. */
120         private final Configuration configuration;
121
122         /** Whether we’re currently saving the configuration. */
123         private boolean storingConfiguration = false;
124
125         /** The identity manager. */
126         private final IdentityManager identityManager;
127
128         /** Interface to freenet. */
129         private final FreenetInterface freenetInterface;
130
131         /** The Sone downloader. */
132         private final SoneDownloader soneDownloader;
133
134         /** The image inserter. */
135         private final ImageInserter imageInserter;
136
137         /** Sone downloader thread-pool. */
138         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
139
140         /** The update checker. */
141         private final UpdateChecker updateChecker;
142
143         /** The trust updater. */
144         private final WebOfTrustUpdater webOfTrustUpdater;
145
146         /** The times Sones were followed. */
147         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
148
149         /** Locked local Sones. */
150         /* synchronize on itself. */
151         private final Set<Sone> lockedSones = new HashSet<Sone>();
152
153         /** Sone inserters. */
154         /* synchronize access on this on sones. */
155         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
156
157         /** Sone rescuers. */
158         /* synchronize access on this on sones. */
159         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
160
161         /** All known Sones. */
162         private final Set<String> knownSones = new HashSet<String>();
163
164         /** The post database. */
165         private final Database database;
166
167         /** Trusted identities, sorted by own identities. */
168         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
169
170         /** All temporary images. */
171         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
172
173         /** Ticker for threads that mark own elements as known. */
174         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
175
176         /** The time the configuration was last touched. */
177         private volatile long lastConfigurationUpdate;
178
179         /**
180          * Creates a new core.
181          *
182          * @param configuration
183          *            The configuration of the core
184          * @param freenetInterface
185          *            The freenet interface
186          * @param identityManager
187          *            The identity manager
188          * @param webOfTrustUpdater
189          *            The WebOfTrust updater
190          * @param eventBus
191          *            The event bus
192          * @param database
193          *            The database
194          */
195         @Inject
196         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
197                 super("Sone Core");
198                 this.configuration = configuration;
199                 this.freenetInterface = freenetInterface;
200                 this.identityManager = identityManager;
201                 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
202                 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
203                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
204                 this.webOfTrustUpdater = webOfTrustUpdater;
205                 this.eventBus = eventBus;
206                 this.database = database;
207                 preferences = new Preferences(eventBus);
208         }
209
210         @VisibleForTesting
211         protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
212                 super("Sone Core");
213                 this.configuration = configuration;
214                 this.freenetInterface = freenetInterface;
215                 this.identityManager = identityManager;
216                 this.soneDownloader = soneDownloader;
217                 this.imageInserter = imageInserter;
218                 this.updateChecker = updateChecker;
219                 this.webOfTrustUpdater = webOfTrustUpdater;
220                 this.eventBus = eventBus;
221                 this.database = database;
222                 preferences = new Preferences(eventBus);
223         }
224
225         //
226         // ACCESSORS
227         //
228
229         /**
230          * Returns the time Sone was started.
231          *
232          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
233          */
234         public long getStartupTime() {
235                 return startupTime;
236         }
237
238         /**
239          * Returns the options used by the core.
240          *
241          * @return The options of the core
242          */
243         public Preferences getPreferences() {
244                 return preferences;
245         }
246
247         /**
248          * Returns the identity manager used by the core.
249          *
250          * @return The identity manager
251          */
252         public IdentityManager getIdentityManager() {
253                 return identityManager;
254         }
255
256         /**
257          * Returns the update checker.
258          *
259          * @return The update checker
260          */
261         public UpdateChecker getUpdateChecker() {
262                 return updateChecker;
263         }
264
265         /**
266          * Returns the Sone rescuer for the given local Sone.
267          *
268          * @param sone
269          *            The local Sone to get the rescuer for
270          * @return The Sone rescuer for the given Sone
271          */
272         public SoneRescuer getSoneRescuer(Sone sone) {
273                 checkNotNull(sone, "sone must not be null");
274                 checkArgument(sone.isLocal(), "sone must be local");
275                 synchronized (soneRescuers) {
276                         SoneRescuer soneRescuer = soneRescuers.get(sone);
277                         if (soneRescuer == null) {
278                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
279                                 soneRescuers.put(sone, soneRescuer);
280                                 soneRescuer.start();
281                         }
282                         return soneRescuer;
283                 }
284         }
285
286         /**
287          * Returns whether the given Sone is currently locked.
288          *
289          * @param sone
290          *            The sone to check
291          * @return {@code true} if the Sone is locked, {@code false} if it is not
292          */
293         public boolean isLocked(Sone sone) {
294                 synchronized (lockedSones) {
295                         return lockedSones.contains(sone);
296                 }
297         }
298
299         public SoneBuilder soneBuilder() {
300                 return database.newSoneBuilder();
301         }
302
303         /**
304          * {@inheritDocs}
305          */
306         @Override
307         public Collection<Sone> getSones() {
308                 return database.getSones();
309         }
310
311         @Override
312         public Function<String, Optional<Sone>> soneLoader() {
313                 return database.soneLoader();
314         }
315
316         /**
317          * Returns the Sone with the given ID, regardless whether it’s local or
318          * remote.
319          *
320          * @param id
321          *            The ID of the Sone to get
322          * @return The Sone with the given ID, or {@code null} if there is no such
323          *         Sone
324          */
325         @Override
326         public Optional<Sone> getSone(String id) {
327                 return database.getSone(id);
328         }
329
330         @Override
331         public Collection<LocalSone> getLocalSones() {
332                 return database.getLocalSones();
333         }
334
335         public Optional<LocalSone> getLocalSone(String id) {
336                 return database.getLocalSone(id);
337         }
338
339         /**
340          * {@inheritDocs}
341          */
342         @Override
343         public Collection<Sone> getRemoteSones() {
344                 return database.getRemoteSones();
345         }
346
347         /**
348          * Returns the remote Sone with the given ID.
349          *
350          *
351          * @param id
352          *            The ID of the remote Sone to get
353          * @return The Sone with the given ID
354          */
355         public Sone getRemoteSone(String id) {
356                 return database.getSone(id).orNull();
357         }
358
359         /**
360          * Returns whether the given Sone has been modified.
361          *
362          * @param sone
363          *            The Sone to check for modifications
364          * @return {@code true} if a modification has been detected in the Sone,
365          *         {@code false} otherwise
366          */
367         public boolean isModifiedSone(Sone sone) {
368                 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
369         }
370
371         /**
372          * Returns the time when the given was first followed by any local Sone.
373          *
374          * @param sone
375          *            The Sone to get the time for
376          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
377          *         been followed, or {@link Long#MAX_VALUE}
378          */
379         public long getSoneFollowingTime(Sone sone) {
380                 synchronized (soneFollowingTimes) {
381                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
382                 }
383         }
384
385         /**
386          * Returns a post builder.
387          *
388          * @return A new post builder
389          */
390         public PostBuilder postBuilder() {
391                 return database.newPostBuilder();
392         }
393
394         /**
395          * {@inheritDoc}
396          */
397         @Override
398         public Optional<Post> getPost(String postId) {
399                 return database.getPost(postId);
400         }
401
402         /**
403          * {@inheritDocs}
404          */
405         @Override
406         public Collection<Post> getPosts(String soneId) {
407                 return database.getPosts(soneId);
408         }
409
410         /**
411          * {@inheritDoc}
412          */
413         @Override
414         public Collection<Post> getDirectedPosts(final String recipientId) {
415                 checkNotNull(recipientId, "recipient must not be null");
416                 return database.getDirectedPosts(recipientId);
417         }
418
419         /**
420          * Returns a post reply builder.
421          *
422          * @return A new post reply builder
423          */
424         public PostReplyBuilder postReplyBuilder() {
425                 return database.newPostReplyBuilder();
426         }
427
428         /**
429          * {@inheritDoc}
430          */
431         @Override
432         public Optional<PostReply> getPostReply(String replyId) {
433                 return database.getPostReply(replyId);
434         }
435
436         /**
437          * {@inheritDoc}
438          */
439         @Override
440         public List<PostReply> getReplies(final String postId) {
441                 return database.getReplies(postId);
442         }
443
444         /**
445          * Returns all Sones that have liked the given post.
446          *
447          * @param post
448          *            The post to get the liking Sones for
449          * @return The Sones that like the given post
450          */
451         public Set<Sone> getLikes(Post post) {
452                 Set<Sone> sones = new HashSet<Sone>();
453                 for (Sone sone : getSones()) {
454                         if (sone.getLikedPostIds().contains(post.getId())) {
455                                 sones.add(sone);
456                         }
457                 }
458                 return sones;
459         }
460
461         /**
462          * Returns all Sones that have liked the given reply.
463          *
464          * @param reply
465          *            The reply to get the liking Sones for
466          * @return The Sones that like the given reply
467          */
468         public Set<Sone> getLikes(PostReply reply) {
469                 Set<Sone> sones = new HashSet<Sone>();
470                 for (Sone sone : getSones()) {
471                         if (sone.getLikedReplyIds().contains(reply.getId())) {
472                                 sones.add(sone);
473                         }
474                 }
475                 return sones;
476         }
477
478         /**
479          * Returns whether the given post is bookmarked.
480          *
481          * @param post
482          *            The post to check
483          * @return {@code true} if the given post is bookmarked, {@code false}
484          *         otherwise
485          */
486         public boolean isBookmarked(Post post) {
487                 return database.isPostBookmarked(post);
488         }
489
490         /**
491          * Returns all currently known bookmarked posts.
492          *
493          * @return All bookmarked posts
494          */
495         public Set<Post> getBookmarkedPosts() {
496                 return database.getBookmarkedPosts();
497         }
498
499         public AlbumBuilder albumBuilder() {
500                 return database.newAlbumBuilder();
501         }
502
503         /**
504          * Returns the album with the given ID, optionally creating a new album if
505          * an album with the given ID can not be found.
506          *
507          * @param albumId
508          *            The ID of the album
509          * @return The album with the given ID, or {@code null} if no album with the
510          *         given ID exists
511          */
512         public Album getAlbum(String albumId) {
513                 return database.getAlbum(albumId).orNull();
514         }
515
516         public ImageBuilder imageBuilder() {
517                 return database.newImageBuilder();
518         }
519
520         /**
521          * Returns the image with the given ID, creating it if necessary.
522          *
523          * @param imageId
524          *            The ID of the image
525          * @return The image with the given ID
526          */
527         public Image getImage(String imageId) {
528                 return getImage(imageId, true);
529         }
530
531         /**
532          * Returns the image with the given ID, optionally creating it if it does
533          * not exist.
534          *
535          * @param imageId
536          *            The ID of the image
537          * @param create
538          *            {@code true} to create an image if none exists with the given
539          *            ID
540          * @return The image with the given ID, or {@code null} if none exists and
541          *         none was created
542          */
543         public Image getImage(String imageId, boolean create) {
544                 Optional<Image> image = database.getImage(imageId);
545                 if (image.isPresent()) {
546                         return image.get();
547                 }
548                 if (!create) {
549                         return null;
550                 }
551                 Image newImage = database.newImageBuilder().withId(imageId).build();
552                 database.storeImage(newImage);
553                 return newImage;
554         }
555
556         /**
557          * Returns the temporary image with the given ID.
558          *
559          * @param imageId
560          *            The ID of the temporary image
561          * @return The temporary image, or {@code null} if there is no temporary
562          *         image with the given ID
563          */
564         public TemporaryImage getTemporaryImage(String imageId) {
565                 synchronized (temporaryImages) {
566                         return temporaryImages.get(imageId);
567                 }
568         }
569
570         //
571         // ACTIONS
572         //
573
574         /**
575          * Locks the given Sone. A locked Sone will not be inserted by
576          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
577          * again.
578          *
579          * @param sone
580          *            The sone to lock
581          */
582         public void lockSone(Sone sone) {
583                 synchronized (lockedSones) {
584                         if (lockedSones.add(sone)) {
585                                 eventBus.post(new SoneLockedEvent(sone));
586                         }
587                 }
588         }
589
590         /**
591          * Unlocks the given Sone.
592          *
593          * @see #lockSone(Sone)
594          * @param sone
595          *            The sone to unlock
596          */
597         public void unlockSone(Sone sone) {
598                 synchronized (lockedSones) {
599                         if (lockedSones.remove(sone)) {
600                                 eventBus.post(new SoneUnlockedEvent(sone));
601                         }
602                 }
603         }
604
605         /**
606          * Adds a local Sone from the given own identity.
607          *
608          * @param ownIdentity
609          *            The own identity to create a Sone from
610          * @return The added (or already existing) Sone
611          */
612         public Sone addLocalSone(OwnIdentity ownIdentity) {
613                 if (ownIdentity == null) {
614                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
615                         return null;
616                 }
617                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
618                 Sone sone = database.registerLocalSone(ownIdentity);
619                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
620                 eventBus.register(soneInserter);
621                 synchronized (soneInserters) {
622                         soneInserters.put(sone, soneInserter);
623                 }
624                 synchronized (soneInserters) {
625                         soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
626                 }
627                 sone.setStatus(SoneStatus.idle);
628                 soneInserter.start();
629                 return sone;
630         }
631
632         /**
633          * Creates a new Sone for the given own identity.
634          *
635          * @param ownIdentity
636          *            The own identity to create a Sone for
637          * @return The created Sone
638          */
639         public Sone createSone(OwnIdentity ownIdentity) {
640                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
641                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
642                         return null;
643                 }
644                 Sone sone = addLocalSone(ownIdentity);
645
646                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
647                 touchConfiguration();
648                 return sone;
649         }
650
651         /**
652          * Adds the Sone of the given identity.
653          *
654          * @param identity
655          *            The identity whose Sone to add
656          * @return The added or already existing Sone
657          */
658         public Sone addRemoteSone(Identity identity) {
659                 if (identity == null) {
660                         logger.log(Level.WARNING, "Given Identity is null!");
661                         return null;
662                 }
663                 final Long latestEdition = tryParse(fromNullable(
664                                 identity.getProperty("Sone.LatestEdition")).or("0"));
665                 Optional<Sone> existingSone = getSone(identity.getId());
666                 if (existingSone.isPresent() && existingSone.get().isLocal()) {
667                         return existingSone.get();
668                 }
669                 boolean newSone = !existingSone.isPresent();
670                 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
671                 sone.setLatestEdition(latestEdition);
672                 if (newSone) {
673                         synchronized (knownSones) {
674                                 newSone = !knownSones.contains(sone.getId());
675                         }
676                         sone.setKnown(!newSone);
677                         if (newSone) {
678                                 eventBus.post(new NewSoneFoundEvent(sone));
679                                 for (Sone localSone : getLocalSones()) {
680                                         if (localSone.getOptions().isAutoFollow()) {
681                                                 followSone(localSone, sone.getId());
682                                         }
683                                 }
684                         }
685                 }
686                 database.storeSone(sone);
687                 soneDownloader.addSone(sone);
688                 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
689                 return sone;
690         }
691
692         /**
693          * Lets the given local Sone follow the Sone with the given ID.
694          *
695          * @param sone
696          *            The local Sone that should follow another Sone
697          * @param soneId
698          *            The ID of the Sone to follow
699          */
700         public void followSone(Sone sone, String soneId) {
701                 checkNotNull(sone, "sone must not be null");
702                 checkNotNull(soneId, "soneId must not be null");
703                 database.addFriend(sone, soneId);
704                 synchronized (soneFollowingTimes) {
705                         if (!soneFollowingTimes.containsKey(soneId)) {
706                                 long now = System.currentTimeMillis();
707                                 soneFollowingTimes.put(soneId, now);
708                                 Optional<Sone> followedSone = getSone(soneId);
709                                 if (!followedSone.isPresent()) {
710                                         return;
711                                 }
712                                 for (Post post : followedSone.get().getPosts()) {
713                                         if (post.getTime() < now) {
714                                                 markPostKnown(post);
715                                         }
716                                 }
717                                 for (PostReply reply : followedSone.get().getReplies()) {
718                                         if (reply.getTime() < now) {
719                                                 markReplyKnown(reply);
720                                         }
721                                 }
722                         }
723                 }
724                 touchConfiguration();
725         }
726
727         /**
728          * Lets the given local Sone unfollow the Sone with the given ID.
729          *
730          * @param sone
731          *            The local Sone that should unfollow another Sone
732          * @param soneId
733          *            The ID of the Sone being unfollowed
734          */
735         public void unfollowSone(Sone sone, String soneId) {
736                 checkNotNull(sone, "sone must not be null");
737                 checkNotNull(soneId, "soneId must not be null");
738                 database.removeFriend(sone, soneId);
739                 boolean unfollowedSoneStillFollowed = false;
740                 for (Sone localSone : getLocalSones()) {
741                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
742                 }
743                 if (!unfollowedSoneStillFollowed) {
744                         synchronized (soneFollowingTimes) {
745                                 soneFollowingTimes.remove(soneId);
746                         }
747                 }
748                 touchConfiguration();
749         }
750
751         /**
752          * Sets the trust value of the given origin Sone for the target Sone.
753          *
754          * @param origin
755          *            The origin Sone
756          * @param target
757          *            The target Sone
758          * @param trustValue
759          *            The trust value (from {@code -100} to {@code 100})
760          */
761         public void setTrust(Sone origin, Sone target, int trustValue) {
762                 checkNotNull(origin, "origin must not be null");
763                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
764                 checkNotNull(target, "target must not be null");
765                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
766                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
767         }
768
769         /**
770          * Removes any trust assignment for the given target Sone.
771          *
772          * @param origin
773          *            The trust origin
774          * @param target
775          *            The trust target
776          */
777         public void removeTrust(Sone origin, Sone target) {
778                 checkNotNull(origin, "origin must not be null");
779                 checkNotNull(target, "target must not be null");
780                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
781                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
782         }
783
784         /**
785          * Assigns the configured positive trust value for the given target.
786          *
787          * @param origin
788          *            The trust origin
789          * @param target
790          *            The trust target
791          */
792         public void trustSone(Sone origin, Sone target) {
793                 setTrust(origin, target, preferences.getPositiveTrust());
794         }
795
796         /**
797          * Assigns the configured negative trust value for the given target.
798          *
799          * @param origin
800          *            The trust origin
801          * @param target
802          *            The trust target
803          */
804         public void distrustSone(Sone origin, Sone target) {
805                 setTrust(origin, target, preferences.getNegativeTrust());
806         }
807
808         /**
809          * Removes the trust assignment for the given target.
810          *
811          * @param origin
812          *            The trust origin
813          * @param target
814          *            The trust target
815          */
816         public void untrustSone(Sone origin, Sone target) {
817                 removeTrust(origin, target);
818         }
819
820         /**
821          * Updates the stored Sone with the given Sone.
822          *
823          * @param sone
824          *            The updated Sone
825          */
826         public void updateSone(Sone sone) {
827                 updateSone(sone, false);
828         }
829
830         /**
831          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
832          * {@code true}, an older Sone than the current Sone can be given to restore
833          * an old state.
834          *
835          * @param sone
836          *            The Sone to update
837          * @param soneRescueMode
838          *            {@code true} if the stored Sone should be updated regardless
839          *            of the age of the given Sone
840          */
841         public void updateSone(final Sone sone, boolean soneRescueMode) {
842                 Optional<Sone> storedSone = getSone(sone.getId());
843                 if (storedSone.isPresent()) {
844                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
845                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
846                                 return;
847                         }
848                         List<Object> events =
849                                         collectEventsForChangesInSone(storedSone.get(), sone);
850                         database.storeSone(sone);
851                         for (Object event : events) {
852                                 eventBus.post(event);
853                         }
854                         sone.setOptions(storedSone.get().getOptions());
855                         sone.setKnown(storedSone.get().isKnown());
856                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
857                         if (sone.isLocal()) {
858                                 touchConfiguration();
859                         }
860                 }
861         }
862
863         private List<Object> collectEventsForChangesInSone(Sone oldSone,
864                         final Sone newSone) {
865                 final List<Object> events = new ArrayList<Object>();
866                 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
867                                 oldSone);
868                 soneChangeDetector.onNewPosts(new PostProcessor() {
869                         @Override
870                         public void processPost(Post post) {
871                                 if (post.getTime() < getSoneFollowingTime(newSone)) {
872                                         post.setKnown(true);
873                                 } else if (!post.isKnown()) {
874                                         events.add(new NewPostFoundEvent(post));
875                                 }
876                         }
877                 });
878                 soneChangeDetector.onRemovedPosts(new PostProcessor() {
879                         @Override
880                         public void processPost(Post post) {
881                                 events.add(new PostRemovedEvent(post));
882                         }
883                 });
884                 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
885                         @Override
886                         public void processPostReply(PostReply postReply) {
887                                 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
888                                         postReply.setKnown(true);
889                                 } else if (!postReply.isKnown()) {
890                                         events.add(new NewPostReplyFoundEvent(postReply));
891                                 }
892                         }
893                 });
894                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
895                         @Override
896                         public void processPostReply(PostReply postReply) {
897                                 events.add(new PostReplyRemovedEvent(postReply));
898                         }
899                 });
900                 soneChangeDetector.detectChanges(newSone);
901                 return events;
902         }
903
904         /**
905          * Deletes the given Sone. This will remove the Sone from the
906          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
907          * remove the context from its identity.
908          *
909          * @param sone
910          *            The Sone to delete
911          */
912         public void deleteSone(Sone sone) {
913                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
914                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
915                         return;
916                 }
917                 if (!getLocalSones().contains(sone)) {
918                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
919                         return;
920                 }
921                 SoneInserter soneInserter = soneInserters.remove(sone);
922                 soneInserter.stop();
923                 database.removeSone(sone);
924                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
925                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
926                 try {
927                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
928                 } catch (ConfigurationException ce1) {
929                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
930                 }
931         }
932
933         /**
934          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
935          * known} before, a {@link MarkSoneKnownEvent} is fired.
936          *
937          * @param sone
938          *            The Sone to mark as known
939          */
940         public void markSoneKnown(Sone sone) {
941                 if (!sone.isKnown()) {
942                         sone.setKnown(true);
943                         synchronized (knownSones) {
944                                 knownSones.add(sone.getId());
945                         }
946                         eventBus.post(new MarkSoneKnownEvent(sone));
947                         touchConfiguration();
948                 }
949         }
950
951         /**
952          * Creates a new post.
953          *
954          * @param sone
955          *            The Sone that creates the post
956          * @param recipient
957          *            The recipient Sone, or {@code null} if this post does not have
958          *            a recipient
959          * @param text
960          *            The text of the post
961          * @return The created post
962          */
963         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
964                 checkNotNull(text, "text must not be null");
965                 checkArgument(text.trim().length() > 0, "text must not be empty");
966                 if (!sone.isLocal()) {
967                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
968                         return null;
969                 }
970                 PostBuilder postBuilder = database.newPostBuilder();
971                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
972                 if (recipient.isPresent()) {
973                         postBuilder.to(recipient.get().getId());
974                 }
975                 final Post post = postBuilder.build();
976                 database.storePost(post);
977                 eventBus.post(new NewPostFoundEvent(post));
978                 sone.addPost(post);
979                 touchConfiguration();
980                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
981                 return post;
982         }
983
984         /**
985          * Deletes the given post.
986          *
987          * @param post
988          *            The post to delete
989          */
990         public void deletePost(Post post) {
991                 if (!post.getSone().isLocal()) {
992                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
993                         return;
994                 }
995                 database.removePost(post);
996                 eventBus.post(new PostRemovedEvent(post));
997                 markPostKnown(post);
998                 touchConfiguration();
999         }
1000
1001         /**
1002          * Marks the given post as known, if it is currently not a known post
1003          * (according to {@link Post#isKnown()}).
1004          *
1005          * @param post
1006          *            The post to mark as known
1007          */
1008         public void markPostKnown(Post post) {
1009                 post.setKnown(true);
1010                 eventBus.post(new MarkPostKnownEvent(post));
1011                 touchConfiguration();
1012                 for (PostReply reply : getReplies(post.getId())) {
1013                         markReplyKnown(reply);
1014                 }
1015         }
1016
1017         public void bookmarkPost(Post post) {
1018                 database.bookmarkPost(post);
1019         }
1020
1021         /**
1022          * Removes the given post from the bookmarks.
1023          *
1024          * @param post
1025          *            The post to unbookmark
1026          */
1027         public void unbookmarkPost(Post post) {
1028                 database.unbookmarkPost(post);
1029         }
1030
1031         /**
1032          * Creates a new reply.
1033          *
1034          * @param sone
1035          *            The Sone that creates the reply
1036          * @param post
1037          *            The post that this reply refers to
1038          * @param text
1039          *            The text of the reply
1040          * @return The created reply
1041          */
1042         public PostReply createReply(Sone sone, Post post, String text) {
1043                 checkNotNull(text, "text must not be null");
1044                 checkArgument(text.trim().length() > 0, "text must not be empty");
1045                 if (!sone.isLocal()) {
1046                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1047                         return null;
1048                 }
1049                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1050                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1051                 final PostReply reply = postReplyBuilder.build();
1052                 database.storePostReply(reply);
1053                 eventBus.post(new NewPostReplyFoundEvent(reply));
1054                 sone.addReply(reply);
1055                 touchConfiguration();
1056                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1057                 return reply;
1058         }
1059
1060         /**
1061          * Deletes the given reply.
1062          *
1063          * @param reply
1064          *            The reply to delete
1065          */
1066         public void deleteReply(PostReply reply) {
1067                 Sone sone = reply.getSone();
1068                 if (!sone.isLocal()) {
1069                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1070                         return;
1071                 }
1072                 database.removePostReply(reply);
1073                 markReplyKnown(reply);
1074                 sone.removeReply(reply);
1075                 touchConfiguration();
1076         }
1077
1078         /**
1079          * Marks the given reply as known, if it is currently not a known reply
1080          * (according to {@link Reply#isKnown()}).
1081          *
1082          * @param reply
1083          *            The reply to mark as known
1084          */
1085         public void markReplyKnown(PostReply reply) {
1086                 boolean previouslyKnown = reply.isKnown();
1087                 reply.setKnown(true);
1088                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1089                 if (!previouslyKnown) {
1090                         touchConfiguration();
1091                 }
1092         }
1093
1094         /**
1095          * Creates a new album for the given Sone.
1096          *
1097          * @param sone
1098          *            The Sone to create the album for
1099          * @param parent
1100          *            The parent of the album (may be {@code null} to create a
1101          *            top-level album)
1102          * @return The new album
1103          */
1104         public Album createAlbum(Sone sone, Album parent) {
1105                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1106                 database.storeAlbum(album);
1107                 parent.addAlbum(album);
1108                 return album;
1109         }
1110
1111         /**
1112          * Deletes the given album. The owner of the album has to be a local Sone,
1113          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1114          *
1115          * @param album
1116          *            The album to remove
1117          */
1118         public void deleteAlbum(Album album) {
1119                 checkNotNull(album, "album must not be null");
1120                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1121                 if (!album.isEmpty()) {
1122                         return;
1123                 }
1124                 album.getParent().removeAlbum(album);
1125                 database.removeAlbum(album);
1126                 touchConfiguration();
1127         }
1128
1129         /**
1130          * Creates a new image.
1131          *
1132          * @param sone
1133          *            The Sone creating the image
1134          * @param album
1135          *            The album the image will be inserted into
1136          * @param temporaryImage
1137          *            The temporary image to create the image from
1138          * @return The newly created image
1139          */
1140         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1141                 checkNotNull(sone, "sone must not be null");
1142                 checkNotNull(album, "album must not be null");
1143                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1144                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1145                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1146                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1147                 album.addImage(image);
1148                 database.storeImage(image);
1149                 imageInserter.insertImage(temporaryImage, image);
1150                 return image;
1151         }
1152
1153         /**
1154          * Deletes the given image. This method will also delete a matching
1155          * temporary image.
1156          *
1157          * @see #deleteTemporaryImage(String)
1158          * @param image
1159          *            The image to delete
1160          */
1161         public void deleteImage(Image image) {
1162                 checkNotNull(image, "image must not be null");
1163                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1164                 deleteTemporaryImage(image.getId());
1165                 image.getAlbum().removeImage(image);
1166                 database.removeImage(image);
1167                 touchConfiguration();
1168         }
1169
1170         /**
1171          * Creates a new temporary image.
1172          *
1173          * @param mimeType
1174          *            The MIME type of the temporary image
1175          * @param imageData
1176          *            The encoded data of the image
1177          * @return The temporary image
1178          */
1179         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1180                 TemporaryImage temporaryImage = new TemporaryImage();
1181                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1182                 synchronized (temporaryImages) {
1183                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1184                 }
1185                 return temporaryImage;
1186         }
1187
1188         /**
1189          * Deletes the temporary image with the given ID.
1190          *
1191          * @param imageId
1192          *            The ID of the temporary image to delete
1193          */
1194         public void deleteTemporaryImage(String imageId) {
1195                 checkNotNull(imageId, "imageId must not be null");
1196                 synchronized (temporaryImages) {
1197                         temporaryImages.remove(imageId);
1198                 }
1199                 Image image = getImage(imageId, false);
1200                 if (image != null) {
1201                         imageInserter.cancelImageInsert(image);
1202                 }
1203         }
1204
1205         /**
1206          * Notifies the core that the configuration, either of the core or of a
1207          * single local Sone, has changed, and that the configuration should be
1208          * saved.
1209          */
1210         public void touchConfiguration() {
1211                 lastConfigurationUpdate = System.currentTimeMillis();
1212         }
1213
1214         //
1215         // SERVICE METHODS
1216         //
1217
1218         /**
1219          * Starts the core.
1220          */
1221         @Override
1222         public void serviceStart() {
1223                 loadConfiguration();
1224                 updateChecker.start();
1225                 identityManager.start();
1226                 webOfTrustUpdater.init();
1227                 webOfTrustUpdater.start();
1228                 database.start();
1229         }
1230
1231         /**
1232          * {@inheritDoc}
1233          */
1234         @Override
1235         public void serviceRun() {
1236                 long lastSaved = System.currentTimeMillis();
1237                 while (!shouldStop()) {
1238                         sleep(1000);
1239                         long now = System.currentTimeMillis();
1240                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1241                                 saveConfiguration();
1242                                 lastSaved = now;
1243                         }
1244                 }
1245         }
1246
1247         /**
1248          * Stops the core.
1249          */
1250         @Override
1251         public void serviceStop() {
1252                 localElementTicker.shutdownNow();
1253                 synchronized (soneInserters) {
1254                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1255                                 soneInserter.getValue().stop();
1256                         }
1257                 }
1258                 database.stop();
1259                 saveConfiguration();
1260                 webOfTrustUpdater.stop();
1261                 updateChecker.stop();
1262                 soneDownloader.stop();
1263                 soneDownloaders.shutdown();
1264                 identityManager.stop();
1265         }
1266
1267         //
1268         // PRIVATE METHODS
1269         //
1270
1271         /**
1272          * Saves the current options.
1273          */
1274         private void saveConfiguration() {
1275                 synchronized (configuration) {
1276                         if (storingConfiguration) {
1277                                 logger.log(Level.FINE, "Already storing configuration…");
1278                                 return;
1279                         }
1280                         storingConfiguration = true;
1281                 }
1282
1283                 /* store the options first. */
1284                 try {
1285                         preferences.saveTo(configuration);
1286
1287                         /* save known Sones. */
1288                         int soneCounter = 0;
1289                         synchronized (knownSones) {
1290                                 for (String knownSoneId : knownSones) {
1291                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1292                                 }
1293                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1294                         }
1295
1296                         /* save Sone following times. */
1297                         soneCounter = 0;
1298                         synchronized (soneFollowingTimes) {
1299                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1300                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1301                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1302                                         ++soneCounter;
1303                                 }
1304                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1305                         }
1306
1307                         /* save known posts. */
1308                         database.save();
1309
1310                         /* now save it. */
1311                         configuration.save();
1312
1313                 } catch (ConfigurationException ce1) {
1314                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1315                 } catch (DatabaseException de1) {
1316                         logger.log(Level.SEVERE, "Could not save database!", de1);
1317                 } finally {
1318                         synchronized (configuration) {
1319                                 storingConfiguration = false;
1320                         }
1321                 }
1322         }
1323
1324         /**
1325          * Loads the configuration.
1326          */
1327         private void loadConfiguration() {
1328                 new PreferencesLoader(preferences).loadFrom(configuration);
1329
1330                 /* load known Sones. */
1331                 int soneCounter = 0;
1332                 while (true) {
1333                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1334                         if (knownSoneId == null) {
1335                                 break;
1336                         }
1337                         synchronized (knownSones) {
1338                                 knownSones.add(knownSoneId);
1339                         }
1340                 }
1341
1342                 /* load Sone following times. */
1343                 soneCounter = 0;
1344                 while (true) {
1345                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1346                         if (soneId == null) {
1347                                 break;
1348                         }
1349                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1350                         synchronized (soneFollowingTimes) {
1351                                 soneFollowingTimes.put(soneId, time);
1352                         }
1353                         ++soneCounter;
1354                 }
1355         }
1356
1357         /**
1358          * Notifies the core that a new {@link OwnIdentity} was added.
1359          *
1360          * @param ownIdentityAddedEvent
1361          *            The event
1362          */
1363         @Subscribe
1364         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1365                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1366                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1367                 if (ownIdentity.hasContext("Sone")) {
1368                         addLocalSone(ownIdentity);
1369                 }
1370         }
1371
1372         /**
1373          * Notifies the core that an {@link OwnIdentity} was removed.
1374          *
1375          * @param ownIdentityRemovedEvent
1376          *            The event
1377          */
1378         @Subscribe
1379         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1380                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1381                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1382                 trustedIdentities.removeAll(ownIdentity);
1383         }
1384
1385         /**
1386          * Notifies the core that a new {@link Identity} was added.
1387          *
1388          * @param identityAddedEvent
1389          *            The event
1390          */
1391         @Subscribe
1392         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1393                 Identity identity = identityAddedEvent.identity();
1394                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1395                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1396                 addRemoteSone(identity);
1397         }
1398
1399         /**
1400          * Notifies the core that an {@link Identity} was updated.
1401          *
1402          * @param identityUpdatedEvent
1403          *            The event
1404          */
1405         @Subscribe
1406         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1407                 Identity identity = identityUpdatedEvent.identity();
1408                 final Sone sone = getRemoteSone(identity.getId());
1409                 if (sone.isLocal()) {
1410                         return;
1411                 }
1412                 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1413                 soneDownloader.addSone(sone);
1414                 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1415         }
1416
1417         /**
1418          * Notifies the core that an {@link Identity} was removed.
1419          *
1420          * @param identityRemovedEvent
1421          *            The event
1422          */
1423         @Subscribe
1424         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1425                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1426                 Identity identity = identityRemovedEvent.identity();
1427                 trustedIdentities.remove(ownIdentity, identity);
1428                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1429                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1430                                 continue;
1431                         }
1432                         if (trustedIdentity.getValue().contains(identity)) {
1433                                 return;
1434                         }
1435                 }
1436                 Optional<Sone> sone = getSone(identity.getId());
1437                 if (!sone.isPresent()) {
1438                         /* TODO - we don’t have the Sone anymore. should this happen? */
1439                         return;
1440                 }
1441                 database.removeSone(sone.get());
1442                 eventBus.post(new SoneRemovedEvent(sone.get()));
1443         }
1444
1445         @Subscribe
1446         public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1447                 Sone sone = soneInsertedEvent.sone();
1448                 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1449                 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1450                                 sone.getLatestEdition()));
1451         }
1452
1453         /**
1454          * Deletes the temporary image.
1455          *
1456          * @param imageInsertFinishedEvent
1457          *            The event
1458          */
1459         @Subscribe
1460         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1461                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1462                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1463                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1464                 touchConfiguration();
1465         }
1466
1467         @VisibleForTesting
1468         class MarkPostKnown implements Runnable {
1469
1470                 private final Post post;
1471
1472                 public MarkPostKnown(Post post) {
1473                         this.post = post;
1474                 }
1475
1476                 @Override
1477                 public void run() {
1478                         markPostKnown(post);
1479                 }
1480
1481         }
1482
1483         @VisibleForTesting
1484         class MarkReplyKnown implements Runnable {
1485
1486                 private final PostReply postReply;
1487
1488                 public MarkReplyKnown(PostReply postReply) {
1489                         this.postReply = postReply;
1490                 }
1491
1492                 @Override
1493                 public void run() {
1494                         markReplyKnown(postReply);
1495                 }
1496
1497         }
1498
1499 }