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