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