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