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