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