Merge branch 'release-0.9.6'
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
index f7b35e9..91825a6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Sone - Core.java - Copyright © 2010–2013 David Roden
+ * Sone - Core.java - Copyright © 2010–2016 David Roden
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -23,7 +23,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.primitives.Longs.tryParse;
 import static java.lang.String.format;
 import static java.util.logging.Level.WARNING;
+import static java.util.logging.Logger.getLogger;
 
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -43,7 +45,6 @@ import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
-import net.pterodactylus.sone.core.Options.DefaultOption;
 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
@@ -80,7 +81,6 @@ import net.pterodactylus.sone.database.PostReplyBuilder;
 import net.pterodactylus.sone.database.PostReplyProvider;
 import net.pterodactylus.sone.database.SoneBuilder;
 import net.pterodactylus.sone.database.SoneProvider;
-import net.pterodactylus.sone.fcp.FcpInterface;
 import net.pterodactylus.sone.freenet.wot.Identity;
 import net.pterodactylus.sone.freenet.wot.IdentityManager;
 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
@@ -90,17 +90,14 @@ import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
 import net.pterodactylus.sone.main.SonePlugin;
-import net.pterodactylus.sone.utils.IntegerRangePredicate;
 import net.pterodactylus.util.config.Configuration;
 import net.pterodactylus.util.config.ConfigurationException;
-import net.pterodactylus.util.logging.Logging;
-import net.pterodactylus.util.number.Numbers;
 import net.pterodactylus.util.service.AbstractService;
 import net.pterodactylus.util.thread.NamedThreadFactory;
 
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
 import com.google.common.base.Optional;
-import com.google.common.base.Predicates;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Multimap;
@@ -119,14 +116,11 @@ import com.google.inject.Singleton;
 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
 
        /** The logger. */
-       private static final Logger logger = Logging.getLogger(Core.class);
+       private static final Logger logger = getLogger(Core.class.getName());
 
        /** The start time. */
        private final long startupTime = System.currentTimeMillis();
 
-       /** The options. */
-       private final Options options = new Options();
-
        /** The preferences. */
        private final Preferences preferences;
 
@@ -160,9 +154,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        /** The trust updater. */
        private final WebOfTrustUpdater webOfTrustUpdater;
 
-       /** The FCP interface. */
-       private volatile FcpInterface fcpInterface;
-
        /** The times Sones were followed. */
        private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
 
@@ -184,10 +175,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        /** The post database. */
        private final Database database;
 
-       /** All bookmarked posts. */
-       /* synchronize access on itself. */
-       private final Set<String> bookmarkedPosts = new HashSet<String>();
-
        /** Trusted identities, sorted by own identities. */
        private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
 
@@ -217,18 +204,18 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         *            The database
         */
        @Inject
-       public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
+       public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
                super("Sone Core");
                this.configuration = configuration;
                this.freenetInterface = freenetInterface;
                this.identityManager = identityManager;
                this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
                this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
-               this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
+               this.updateChecker = updateChecker;
                this.webOfTrustUpdater = webOfTrustUpdater;
                this.eventBus = eventBus;
                this.database = database;
-               preferences = new Preferences(this.eventBus, options);
+               preferences = new Preferences(eventBus);
        }
 
        @VisibleForTesting
@@ -243,7 +230,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                this.webOfTrustUpdater = webOfTrustUpdater;
                this.eventBus = eventBus;
                this.database = database;
-               preferences = new Preferences(this.eventBus, options);
+               preferences = new Preferences(eventBus);
        }
 
        //
@@ -287,16 +274,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        }
 
        /**
-        * Sets the FCP interface to use.
-        *
-        * @param fcpInterface
-        *            The FCP interface to use
-        */
-       public void setFcpInterface(FcpInterface fcpInterface) {
-               this.fcpInterface = fcpInterface;
-       }
-
-       /**
         * Returns the Sone rescuer for the given local Sone.
         *
         * @param sone
@@ -342,6 +319,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                return database.getSones();
        }
 
+       @Override
+       public Function<String, Optional<Sone>> soneLoader() {
+               return database.soneLoader();
+       }
+
        /**
         * Returns the Sone with the given ID, regardless whether it’s local or
         * remote.
@@ -527,21 +509,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         *         otherwise
         */
        public boolean isBookmarked(Post post) {
-               return isPostBookmarked(post.getId());
-       }
-
-       /**
-        * Returns whether the post with the given ID is bookmarked.
-        *
-        * @param id
-        *            The ID of the post to check
-        * @return {@code true} if the post with the given ID is bookmarked,
-        *         {@code false} otherwise
-        */
-       public boolean isPostBookmarked(String id) {
-               synchronized (bookmarkedPosts) {
-                       return bookmarkedPosts.contains(id);
-               }
+               return database.isPostBookmarked(post);
        }
 
        /**
@@ -550,16 +518,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         * @return All bookmarked posts
         */
        public Set<Post> getBookmarkedPosts() {
-               Set<Post> posts = new HashSet<Post>();
-               synchronized (bookmarkedPosts) {
-                       for (String bookmarkedPostId : bookmarkedPosts) {
-                               Optional<Post> post = getPost(bookmarkedPostId);
-                               if (post.isPresent()) {
-                                       posts.add(post.get());
-                               }
-                       }
-               }
-               return posts;
+               return database.getBookmarkedPosts();
        }
 
        public AlbumBuilder albumBuilder() {
@@ -682,16 +641,17 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                }
                logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
                Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
-               sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
-               sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
+               String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
+               sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
+               sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
                sone.setKnown(true);
-               /* TODO - load posts ’n stuff */
                SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
                eventBus.register(soneInserter);
                synchronized (soneInserters) {
                        soneInserters.put(sone, soneInserter);
                }
                loadSone(sone);
+               database.storeSone(sone);
                sone.setStatus(SoneStatus.idle);
                soneInserter.start();
                return sone;
@@ -728,8 +688,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        logger.log(Level.WARNING, "Given Identity is null!");
                        return null;
                }
-               final Long latestEdition = tryParse(fromNullable(
-                               identity.getProperty("Sone.LatestEdition")).or("0"));
+               String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
+               long latestEdition = fromNullable(tryParse(property)).or(0L);
                Optional<Sone> existingSone = getSone(identity.getId());
                if (existingSone.isPresent() && existingSone.get().isLocal()) {
                        return existingSone.get();
@@ -768,7 +728,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        public void followSone(Sone sone, String soneId) {
                checkNotNull(sone, "sone must not be null");
                checkNotNull(soneId, "soneId must not be null");
-               sone.addFriend(soneId);
+               database.addFriend(sone, soneId);
                synchronized (soneFollowingTimes) {
                        if (!soneFollowingTimes.containsKey(soneId)) {
                                long now = System.currentTimeMillis();
@@ -803,7 +763,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
        public void unfollowSone(Sone sone, String soneId) {
                checkNotNull(sone, "sone must not be null");
                checkNotNull(soneId, "soneId must not be null");
-               sone.removeFriend(soneId);
+               database.removeFriend(sone, soneId);
                boolean unfollowedSoneStillFollowed = false;
                for (Sone localSone : getLocalSones()) {
                        unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
@@ -913,42 +873,12 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
                                return;
                        }
-                       /* find removed posts. */
-                       SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
-                       soneChangeDetector.onNewPosts(new PostProcessor() {
-                               @Override
-                               public void processPost(Post post) {
-                                       if (post.getTime() < getSoneFollowingTime(sone)) {
-                                               post.setKnown(true);
-                                       } else if (!post.isKnown()) {
-                                               eventBus.post(new NewPostFoundEvent(post));
-                                       }
-                               }
-                       });
-                       soneChangeDetector.onRemovedPosts(new PostProcessor() {
-                               @Override
-                               public void processPost(Post post) {
-                                       eventBus.post(new PostRemovedEvent(post));
-                               }
-                       });
-                       soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
-                               @Override
-                               public void processPostReply(PostReply postReply) {
-                                       if (postReply.getTime() < getSoneFollowingTime(sone)) {
-                                               postReply.setKnown(true);
-                                       } else if (!postReply.isKnown()) {
-                                               eventBus.post(new NewPostReplyFoundEvent(postReply));
-                                       }
-                               }
-                       });
-                       soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
-                               @Override
-                               public void processPostReply(PostReply postReply) {
-                                       eventBus.post(new PostReplyRemovedEvent(postReply));
-                               }
-                       });
-                       soneChangeDetector.detectChanges(sone);
+                       List<Object> events =
+                                       collectEventsForChangesInSone(storedSone.get(), sone);
                        database.storeSone(sone);
+                       for (Object event : events) {
+                               eventBus.post(event);
+                       }
                        sone.setOptions(storedSone.get().getOptions());
                        sone.setKnown(storedSone.get().isKnown());
                        sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
@@ -958,6 +888,47 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                }
        }
 
+       private List<Object> collectEventsForChangesInSone(Sone oldSone,
+                       final Sone newSone) {
+               final List<Object> events = new ArrayList<Object>();
+               SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
+                               oldSone);
+               soneChangeDetector.onNewPosts(new PostProcessor() {
+                       @Override
+                       public void processPost(Post post) {
+                               if (post.getTime() < getSoneFollowingTime(newSone)) {
+                                       post.setKnown(true);
+                               } else if (!post.isKnown()) {
+                                       events.add(new NewPostFoundEvent(post));
+                               }
+                       }
+               });
+               soneChangeDetector.onRemovedPosts(new PostProcessor() {
+                       @Override
+                       public void processPost(Post post) {
+                               events.add(new PostRemovedEvent(post));
+                       }
+               });
+               soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
+                       @Override
+                       public void processPostReply(PostReply postReply) {
+                               if (postReply.getTime() < getSoneFollowingTime(newSone)) {
+                                       postReply.setKnown(true);
+                               } else if (!postReply.isKnown()) {
+                                       events.add(new NewPostReplyFoundEvent(postReply));
+                               }
+                       }
+               });
+               soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
+                       @Override
+                       public void processPostReply(PostReply postReply) {
+                               events.add(new PostReplyRemovedEvent(postReply));
+                       }
+               });
+               soneChangeDetector.detectChanges(newSone);
+               return events;
+       }
+
        /**
         * Deletes the given Sone. This will remove the Sone from the
         * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
@@ -975,10 +946,9 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
                        return;
                }
-               // FIXME – implement in database
-//             sones.remove(sone.getId());
                SoneInserter soneInserter = soneInserters.remove(sone);
                soneInserter.stop();
+               database.removeSone(sone);
                webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
                webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
                try {
@@ -1059,9 +1029,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                Set<String> likedReplyIds =
                                configurationSoneParser.parseLikedPostReplyIds();
 
-               /* load friends. */
-               Set<String> friends = configurationSoneParser.parseFriends();
-
                /* load albums. */
                List<Album> topLevelAlbums;
                try {
@@ -1098,11 +1065,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                }
 
                /* load options. */
-               sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
-               sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
-               sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
-               sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
-               sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
+               sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
+               sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
+               sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
+               sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
+               sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
                sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
 
                /* if we’re still here, Sone was loaded successfully. */
@@ -1113,25 +1080,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        sone.setReplies(replies);
                        sone.setLikePostIds(likedPostIds);
                        sone.setLikeReplyIds(likedReplyIds);
-                       for (String friendId : friends) {
-                               followSone(sone, friendId);
-                       }
                        for (Album album : sone.getRootAlbum().getAlbums()) {
                                sone.getRootAlbum().removeAlbum(album);
                        }
                        for (Album album : topLevelAlbums) {
                                sone.getRootAlbum().addAlbum(album);
                        }
-                       database.storeSone(sone);
                        synchronized (soneInserters) {
                                soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
                        }
                }
-               synchronized (knownSones) {
-                       for (String friend : friends) {
-                               knownSones.add(friend);
-                       }
-               }
                for (Post post : posts) {
                        post.setKnown(true);
                }
@@ -1155,24 +1113,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         * @return The created post
         */
        public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
-               return createPost(sone, recipient, System.currentTimeMillis(), text);
-       }
-
-       /**
-        * Creates a new post.
-        *
-        * @param sone
-        *            The Sone that creates the post
-        * @param recipient
-        *            The recipient Sone, or {@code null} if this post does not have
-        *            a recipient
-        * @param time
-        *            The time of the post
-        * @param text
-        *            The text of the post
-        * @return The created post
-        */
-       public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
                checkNotNull(text, "text must not be null");
                checkArgument(text.trim().length() > 0, "text must not be empty");
                if (!sone.isLocal()) {
@@ -1180,7 +1120,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        return null;
                }
                PostBuilder postBuilder = database.newPostBuilder();
-               postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
+               postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
                if (recipient.isPresent()) {
                        postBuilder.to(recipient.get().getId());
                }
@@ -1226,16 +1166,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                }
        }
 
-       /**
-        * Bookmarks the post with the given ID.
-        *
-        * @param id
-        *            The ID of the post to bookmark
-        */
-       public void bookmarkPost(String id) {
-               synchronized (bookmarkedPosts) {
-                       bookmarkedPosts.add(id);
-               }
+       public void bookmarkPost(Post post) {
+               database.bookmarkPost(post);
        }
 
        /**
@@ -1244,20 +1176,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         * @param post
         *            The post to unbookmark
         */
-       public void unbookmark(Post post) {
-               unbookmarkPost(post.getId());
-       }
-
-       /**
-        * Removes the post with the given ID from the bookmarks.
-        *
-        * @param id
-        *            The ID of the post to unbookmark
-        */
-       public void unbookmarkPost(String id) {
-               synchronized (bookmarkedPosts) {
-                       bookmarkedPosts.remove(id);
-               }
+       public void unbookmarkPost(Post post) {
+               database.unbookmarkPost(post);
        }
 
        /**
@@ -1491,6 +1411,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                saveSone(soneInserter.getKey());
                        }
                }
+               synchronized (soneRescuers) {
+                       for (SoneRescuer soneRescuer : soneRescuers.values()) {
+                               soneRescuer.stop();
+                       }
+               }
                saveConfiguration();
                database.stop();
                webOfTrustUpdater.stop();
@@ -1583,13 +1508,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        }
                        configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
 
-                       /* save friends. */
-                       int friendCounter = 0;
-                       for (String friendId : sone.getFriends()) {
-                               configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
-                       }
-                       configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
-
                        /* save albums. first, collect in a flat structure, top-level first. */
                        List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
 
@@ -1600,7 +1518,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                                configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
                                configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
                                configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
-                               configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
                        }
                        configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
 
@@ -1656,18 +1573,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
 
                /* store the options first. */
                try {
-                       configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
-                       configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
-                       configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
-                       configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
-                       configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
-                       configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
-                       configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
-                       configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
-                       configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
-                       configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
-                       configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
-                       configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
+                       preferences.saveTo(configuration);
 
                        /* save known Sones. */
                        int soneCounter = 0;
@@ -1692,15 +1598,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        /* save known posts. */
                        database.save();
 
-                       /* save bookmarked posts. */
-                       int bookmarkedPostCounter = 0;
-                       synchronized (bookmarkedPosts) {
-                               for (String bookmarkedPostId : bookmarkedPosts) {
-                                       configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
-                               }
-                       }
-                       configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
-
                        /* now save it. */
                        configuration.save();
 
@@ -1719,30 +1616,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
         * Loads the configuration.
         */
        private void loadConfiguration() {
-               /* create options. */
-               options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE)));
-               options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
-               options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
-               options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
-               options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
-               options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
-               options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
-               options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
-               options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
-               options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
-               options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
-
-               loadConfigurationValue("InsertionDelay");
-               loadConfigurationValue("PostsPerPage");
-               loadConfigurationValue("ImagesPerPage");
-               loadConfigurationValue("CharactersPerPost");
-               loadConfigurationValue("PostCutOffLength");
-               options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
-               loadConfigurationValue("PositiveTrust");
-               loadConfigurationValue("NegativeTrust");
-               options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
-               options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
-               options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
+               new PreferencesLoader(preferences).loadFrom(configuration);
 
                /* load known Sones. */
                int soneCounter = 0;
@@ -1769,34 +1643,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        }
                        ++soneCounter;
                }
-
-               /* load bookmarked posts. */
-               int bookmarkedPostCounter = 0;
-               while (true) {
-                       String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
-                       if (bookmarkedPostId == null) {
-                               break;
-                       }
-                       synchronized (bookmarkedPosts) {
-                               bookmarkedPosts.add(bookmarkedPostId);
-                       }
-               }
-
-       }
-
-       /**
-        * Loads an {@link Integer} configuration value for the option with the
-        * given name, logging validation failures.
-        *
-        * @param optionName
-        *            The name of the option to load
-        */
-       private void loadConfigurationValue(String optionName) {
-               try {
-                       options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
-               } catch (IllegalArgumentException iae1) {
-                       logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
-               }
        }
 
        /**
@@ -1854,7 +1700,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                if (sone.isLocal()) {
                        return;
                }
-               sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
+               sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
                soneDownloader.addSone(sone);
                soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
        }
@@ -1883,17 +1729,14 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
                        /* TODO - we don’t have the Sone anymore. should this happen? */
                        return;
                }
-               database.removePosts(sone.get());
+               for (PostReply postReply : sone.get().getReplies()) {
+                       eventBus.post(new PostReplyRemovedEvent(postReply));
+               }
                for (Post post : sone.get().getPosts()) {
                        eventBus.post(new PostRemovedEvent(post));
                }
-               database.removePostReplies(sone.get());
-               for (PostReply reply : sone.get().getReplies()) {
-                       eventBus.post(new PostReplyRemovedEvent(reply));
-               }
-//             TODO – implement in database
-//             sones.remove(identity.getId());
                eventBus.post(new SoneRemovedEvent(sone.get()));
+               database.removeSone(sone.get());
        }
 
        /**