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