X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;ds=inline;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fcore%2FCore.java;h=5fa330b175dec903f277559160d53b80fc4d23e2;hb=d50ceb969ffc7187d48127c14f8cd22ba135b137;hp=15ce975805aff1ff0fa87d86c0a4917030c4a28b;hpb=3c04419570520b0c7158dbb8c27083d419afdf47;p=Sone.git
diff --git a/src/main/java/net/pterodactylus/sone/core/Core.java b/src/main/java/net/pterodactylus/sone/core/Core.java
index 15ce975..5fa330b 100644
--- a/src/main/java/net/pterodactylus/sone/core/Core.java
+++ b/src/main/java/net/pterodactylus/sone/core/Core.java
@@ -17,13 +17,19 @@
package net.pterodactylus.sone.core;
+import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Predicates.not;
+import static com.google.common.primitives.Longs.tryParse;
+import static java.lang.String.format;
+import static java.util.logging.Level.WARNING;
+import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
+import static net.pterodactylus.sone.data.Sone.toAllAlbums;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -37,9 +43,15 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
+import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
+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.Options.Option;
-import net.pterodactylus.sone.core.Options.OptionWatcher;
+import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
+import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
+import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
@@ -56,20 +68,25 @@ import net.pterodactylus.sone.data.Album;
import net.pterodactylus.sone.data.Client;
import net.pterodactylus.sone.data.Image;
import net.pterodactylus.sone.data.Post;
-import net.pterodactylus.sone.data.PostBuilder;
-import net.pterodactylus.sone.data.PostBuilderFactory;
import net.pterodactylus.sone.data.PostReply;
-import net.pterodactylus.sone.data.PostReplyBuilder;
-import net.pterodactylus.sone.data.PostReplyBuilderFactory;
import net.pterodactylus.sone.data.Profile;
import net.pterodactylus.sone.data.Profile.Field;
import net.pterodactylus.sone.data.Reply;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
import net.pterodactylus.sone.data.Sone.SoneStatus;
+import net.pterodactylus.sone.data.SoneImpl;
import net.pterodactylus.sone.data.TemporaryImage;
+import net.pterodactylus.sone.database.AlbumBuilder;
+import net.pterodactylus.sone.database.Database;
+import net.pterodactylus.sone.database.DatabaseException;
+import net.pterodactylus.sone.database.ImageBuilder;
+import net.pterodactylus.sone.database.PostBuilder;
+import net.pterodactylus.sone.database.PostProvider;
+import net.pterodactylus.sone.database.PostReplyBuilder;
+import net.pterodactylus.sone.database.PostReplyProvider;
+import net.pterodactylus.sone.database.SoneProvider;
import net.pterodactylus.sone.fcp.FcpInterface;
-import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
import net.pterodactylus.sone.freenet.wot.Identity;
import net.pterodactylus.sone.freenet.wot.IdentityManager;
import net.pterodactylus.sone.freenet.wot.OwnIdentity;
@@ -87,16 +104,18 @@ import net.pterodactylus.util.number.Numbers;
import net.pterodactylus.util.service.AbstractService;
import net.pterodactylus.util.thread.NamedThreadFactory;
-import com.google.common.base.Function;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
-import com.google.common.collect.Collections2;
import com.google.common.collect.FluentIterable;
-import com.google.common.collect.Ordering;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Multimaps;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
+import com.google.inject.Singleton;
import freenet.keys.FreenetURI;
@@ -105,6 +124,7 @@ import freenet.keys.FreenetURI;
*
* @author David âBombeâ Roden
*/
+@Singleton
public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
/** The logger. */
@@ -123,7 +143,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
private final EventBus eventBus;
/** The configuration. */
- private Configuration configuration;
+ private final Configuration configuration;
/** Whether weâre currently saving the configuration. */
private boolean storingConfiguration = false;
@@ -174,36 +194,15 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
/** All known Sones. */
private final Set knownSones = new HashSet();
- /** The post builder. */
- private final PostBuilderFactory postBuilderFactory;
-
- /** All posts. */
- private final Map posts = new HashMap();
-
- /** All known posts. */
- private final Set knownPosts = new HashSet();
-
- /** The post reply builder factory. */
- private final PostReplyBuilderFactory postReplyBuilderFactory;
-
- /** All replies. */
- private final Map replies = new HashMap();
-
- /** All known replies. */
- private final Set knownReplies = new HashSet();
+ /** The post database. */
+ private final Database database;
/** All bookmarked posts. */
/* synchronize access on itself. */
private final Set bookmarkedPosts = new HashSet();
/** Trusted identities, sorted by own identities. */
- private final Map> trustedIdentities = Collections.synchronizedMap(new HashMap>());
-
- /** All known albums. */
- private final Map albums = new HashMap();
-
- /** All known images. */
- private final Map images = new HashMap();
+ private final Multimap trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.create());
/** All temporary images. */
private final Map temporaryImages = new HashMap();
@@ -227,24 +226,35 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* The WebOfTrust updater
* @param eventBus
* The event bus
- * @param postBuilderFactory
- * The post builder
- * @param postReplyBuilderFactory
- * The post reply builder factory
+ * @param database
+ * The database
*/
@Inject
- public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
+ public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
super("Sone Core");
this.configuration = configuration;
this.freenetInterface = freenetInterface;
this.identityManager = identityManager;
- this.soneDownloader = new SoneDownloader(this, freenetInterface);
- this.imageInserter = new ImageInserter(freenetInterface);
+ this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
+ this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
this.webOfTrustUpdater = webOfTrustUpdater;
this.eventBus = eventBus;
- this.postBuilderFactory = postBuilderFactory;
- this.postReplyBuilderFactory = postReplyBuilderFactory;
+ this.database = database;
+ }
+
+ @VisibleForTesting
+ protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
+ super("Sone Core");
+ this.configuration = configuration;
+ this.freenetInterface = freenetInterface;
+ this.identityManager = identityManager;
+ this.soneDownloader = soneDownloader;
+ this.imageInserter = imageInserter;
+ this.updateChecker = updateChecker;
+ this.webOfTrustUpdater = webOfTrustUpdater;
+ this.eventBus = eventBus;
+ this.database = database;
}
//
@@ -261,18 +271,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
}
/**
- * Sets the configuration to use. This will automatically save the current
- * configuration to the given configuration.
- *
- * @param configuration
- * The new configuration to use
- */
- public void setConfiguration(Configuration configuration) {
- this.configuration = configuration;
- touchConfiguration();
- }
-
- /**
* Returns the options used by the core.
*
* @return The options of the core
@@ -344,25 +342,13 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
}
/**
- * Returns all Sones, remote and local.
- *
- * @return All Sones
- */
- public Set getSones() {
- return new HashSet(sones.values());
- }
-
- /**
- * Returns the Sone with the given ID, regardless whether itâs local or
- * remote.
- *
- * @param id
- * The ID of the Sone to get
- * @return The Sone with the given ID, or {@code null} if there is no such
- * Sone
+ * {@inheritDocs}
*/
- public Sone getSone(String id) {
- return getSone(id, true);
+ @Override
+ public Collection getSones() {
+ synchronized (sones) {
+ return ImmutableSet.copyOf(sones.values());
+ }
}
/**
@@ -371,52 +357,23 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*
* @param id
* The ID of the Sone to get
- * @param create
- * {@code true} to create a new Sone if none exists,
- * {@code false} to return {@code null} if a Sone with the given
- * ID does not exist
* @return The Sone with the given ID, or {@code null} if there is no such
* Sone
*/
@Override
- public Sone getSone(String id, boolean create) {
+ public Optional getSone(String id) {
synchronized (sones) {
- if (!sones.containsKey(id) && create) {
- Sone sone = new Sone(id, false);
- sones.put(id, sone);
- }
- return sones.get(id);
- }
- }
-
- /**
- * Checks whether the core knows a Sone with the given ID.
- *
- * @param id
- * The ID of the Sone
- * @return {@code true} if there is a Sone with the given ID, {@code false}
- * otherwise
- */
- public boolean hasSone(String id) {
- synchronized (sones) {
- return sones.containsKey(id);
+ return Optional.fromNullable(sones.get(id));
}
}
/**
- * Returns all local Sones.
- *
- * @return All local Sones
+ * {@inheritDocs}
*/
+ @Override
public Collection getLocalSones() {
synchronized (sones) {
- return Collections2.filter(sones.values(), new Predicate() {
-
- @Override
- public boolean apply(Sone sone) {
- return sone.isLocal();
- }
- });
+ return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
}
}
@@ -434,11 +391,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
synchronized (sones) {
Sone sone = sones.get(id);
if ((sone == null) && create) {
- sone = new Sone(id, true);
+ sone = new SoneImpl(id, true);
sones.put(id, sone);
}
if ((sone != null) && !sone.isLocal()) {
- sone = new Sone(id, true);
+ sone = new SoneImpl(id, true);
sones.put(id, sone);
}
return sone;
@@ -446,19 +403,12 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
}
/**
- * Returns all remote Sones.
- *
- * @return All remote Sones
+ * {@inheritDocs}
*/
+ @Override
public Collection getRemoteSones() {
synchronized (sones) {
- return Collections2.filter(sones.values(), new Predicate() {
-
- @Override
- public boolean apply(Sone sone) {
- return !sone.isLocal();
- }
- });
+ return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
}
}
@@ -476,7 +426,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
synchronized (sones) {
Sone sone = sones.get(id);
if ((sone == null) && create && (id != null) && (id.length() == 43)) {
- sone = new Sone(id, false);
+ sone = new SoneImpl(id, false);
sones.put(id, sone);
}
return sone;
@@ -492,7 +442,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* {@code false} otherwise
*/
public boolean isModifiedSone(Sone sone) {
- return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
+ return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
}
/**
@@ -505,36 +455,17 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*/
public long getSoneFollowingTime(Sone sone) {
synchronized (soneFollowingTimes) {
- if (soneFollowingTimes.containsKey(sone)) {
- return soneFollowingTimes.get(sone);
- }
- return Long.MAX_VALUE;
+ return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
}
}
/**
- * Returns whether the target Sone is trusted by the origin Sone.
- *
- * @param origin
- * The origin Sone
- * @param target
- * The target Sone
- * @return {@code true} if the target Sone is trusted by the origin Sone
- */
- public boolean isSoneTrusted(Sone origin, Sone target) {
- checkNotNull(origin, "origin must not be null");
- checkNotNull(target, "target must not be null");
- checkArgument(origin.getIdentity() instanceof OwnIdentity, "originâs identity must be an OwnIdentity");
- return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
- }
-
- /**
* Returns a post builder.
*
* @return A new post builder
*/
public PostBuilder postBuilder() {
- return postBuilderFactory.newPostBuilder();
+ return database.newPostBuilder();
}
/**
@@ -542,30 +473,24 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*/
@Override
public Optional getPost(String postId) {
- synchronized (posts) {
- return Optional.fromNullable(posts.get(postId));
- }
+ return database.getPost(postId);
}
/**
- * Returns all posts that have the given Sone as recipient.
- *
- * @see Post#getRecipient()
- * @param recipient
- * The recipient of the posts
- * @return All posts that have the given Sone as recipient
- */
- public Set getDirectedPosts(Sone recipient) {
- checkNotNull(recipient, "recipient must not be null");
- Set directedPosts = new HashSet();
- synchronized (posts) {
- for (Post post : posts.values()) {
- if (recipient.equals(post.getRecipient())) {
- directedPosts.add(post);
- }
- }
- }
- return directedPosts;
+ * {@inheritDocs}
+ */
+ @Override
+ public Collection getPosts(String soneId) {
+ return database.getPosts(soneId);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Collection getDirectedPosts(final String recipientId) {
+ checkNotNull(recipientId, "recipient must not be null");
+ return database.getDirectedPosts(recipientId);
}
/**
@@ -574,7 +499,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* @return A new post reply builder
*/
public PostReplyBuilder postReplyBuilder() {
- return postReplyBuilderFactory.newPostReplyBuilder();
+ return database.newPostReplyBuilder();
}
/**
@@ -582,29 +507,15 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*/
@Override
public Optional getPostReply(String replyId) {
- synchronized (replies) {
- return Optional.fromNullable(replies.get(replyId));
- }
+ return database.getPostReply(replyId);
}
/**
* {@inheritDoc}
*/
@Override
- public List getReplies(final Post post) {
- return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function>() {
-
- @Override
- public Iterable apply(Sone sone) {
- return sone.getReplies();
- }
- }).filter(new Predicate() {
-
- @Override
- public boolean apply(PostReply reply) {
- return post.getId().equals(reply.getPostId());
- }
- }));
+ public List getReplies(final String postId) {
+ return database.getReplies(postId);
}
/**
@@ -677,7 +588,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
synchronized (bookmarkedPosts) {
for (String bookmarkedPostId : bookmarkedPosts) {
Optional post = getPost(bookmarkedPostId);
- if (!post.isPresent()) {
+ if (post.isPresent()) {
posts.add(post.get());
}
}
@@ -685,16 +596,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
return posts;
}
- /**
- * Returns the album with the given ID, creating a new album if no album
- * with the given ID can be found.
- *
- * @param albumId
- * The ID of the album
- * @return The album with the given ID
- */
- public Album getAlbum(String albumId) {
- return getAlbum(albumId, true);
+ public AlbumBuilder albumBuilder() {
+ return database.newAlbumBuilder();
}
/**
@@ -703,21 +606,15 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*
* @param albumId
* The ID of the album
- * @param create
- * {@code true} to create a new album if none exists for the
- * given ID
* @return The album with the given ID, or {@code null} if no album with the
- * given ID exists and {@code create} is {@code false}
- */
- public Album getAlbum(String albumId, boolean create) {
- synchronized (albums) {
- Album album = albums.get(albumId);
- if (create && (album == null)) {
- album = new Album(albumId);
- albums.put(albumId, album);
- }
- return album;
- }
+ * given ID exists
+ */
+ public Album getAlbum(String albumId) {
+ return database.getAlbum(albumId).orNull();
+ }
+
+ public ImageBuilder imageBuilder() {
+ return database.newImageBuilder();
}
/**
@@ -744,14 +641,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* none was created
*/
public Image getImage(String imageId, boolean create) {
- synchronized (images) {
- Image image = images.get(imageId);
- if (create && (image == null)) {
- image = new Image(imageId);
- images.put(imageId, image);
- }
- return image;
+ Optional image = database.getImage(imageId);
+ if (image.isPresent()) {
+ return image.get();
}
+ if (!create) {
+ return null;
+ }
+ Image newImage = database.newImageBuilder().withId(imageId).build();
+ database.storeImage(newImage);
+ return newImage;
}
/**
@@ -815,6 +714,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.WARNING, "Given OwnIdentity is null!");
return null;
}
+ logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
synchronized (sones) {
final Sone sone;
try {
@@ -850,12 +750,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
return null;
}
Sone sone = addLocalSone(ownIdentity);
- sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption(false));
- sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption(false));
- sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption(true));
- sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption(ShowCustomAvatars.NEVER));
followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
touchConfiguration();
@@ -874,11 +768,17 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.WARNING, "Given Identity is null!");
return null;
}
+ final Long latestEdition = fromNullable(tryParse(
+ identity.getProperty("Sone.LatestEdition"))).or(0L);
synchronized (sones) {
- final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
+ final Sone sone = getRemoteSone(identity.getId(), true);
+ if (sone.isLocal()) {
+ return sone;
+ }
+ sone.setIdentity(identity);
boolean newSone = sone.getRequestUri() == null;
sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
- sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
+ sone.setLatestEdition(latestEdition);
if (newSone) {
synchronized (knownSones) {
newSone = !knownSones.contains(sone.getId());
@@ -887,22 +787,14 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
if (newSone) {
eventBus.post(new NewSoneFoundEvent(sone));
for (Sone localSone : getLocalSones()) {
- if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
+ if (localSone.getOptions().isAutoFollow()) {
followSone(localSone, sone.getId());
}
}
}
}
soneDownloader.addSone(sone);
- soneDownloaders.execute(new Runnable() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void run() {
- soneDownloader.fetchSone(sone, sone.getRequestUri());
- }
-
- });
+ soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
return sone;
}
}
@@ -923,16 +815,16 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
if (!soneFollowingTimes.containsKey(soneId)) {
long now = System.currentTimeMillis();
soneFollowingTimes.put(soneId, now);
- Sone followedSone = getSone(soneId);
- if (followedSone == null) {
+ Optional followedSone = getSone(soneId);
+ if (!followedSone.isPresent()) {
return;
}
- for (Post post : followedSone.getPosts()) {
+ for (Post post : followedSone.get().getPosts()) {
if (post.getTime() < now) {
markPostKnown(post);
}
}
- for (PostReply reply : followedSone.getReplies()) {
+ for (PostReply reply : followedSone.get().getReplies()) {
if (reply.getTime() < now) {
markReplyKnown(reply);
}
@@ -1056,80 +948,71 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* {@code true} if the stored Sone should be updated regardless
* of the age of the given Sone
*/
- public void updateSone(Sone sone, boolean soneRescueMode) {
- if (hasSone(sone.getId())) {
- Sone storedSone = getSone(sone.getId());
- if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
+ public void updateSone(final Sone sone, boolean soneRescueMode) {
+ Optional storedSone = getSone(sone.getId());
+ if (storedSone.isPresent()) {
+ if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
return;
}
- synchronized (posts) {
- if (!soneRescueMode) {
- for (Post post : storedSone.getPosts()) {
- posts.remove(post.getId());
- if (!sone.getPosts().contains(post)) {
- eventBus.post(new PostRemovedEvent(post));
- }
+ /* 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));
}
}
- List storedPosts = storedSone.getPosts();
- synchronized (knownPosts) {
- for (Post post : sone.getPosts()) {
- post.setKnown(knownPosts.contains(post.getId()));
- if (!storedPosts.contains(post)) {
- if (post.getTime() < getSoneFollowingTime(sone)) {
- knownPosts.add(post.getId());
- post.setKnown(true);
- } else if (!knownPosts.contains(post.getId())) {
- eventBus.post(new NewPostFoundEvent(post));
- }
- }
- posts.put(post.getId(), post);
- }
+ });
+ soneChangeDetector.onRemovedPosts(new PostProcessor() {
+ @Override
+ public void processPost(Post post) {
+ eventBus.post(new PostRemovedEvent(post));
}
- }
- synchronized (replies) {
- if (!soneRescueMode) {
- for (PostReply reply : storedSone.getReplies()) {
- replies.remove(reply.getId());
- if (!sone.getReplies().contains(reply)) {
- eventBus.post(new PostReplyRemovedEvent(reply));
- }
+ });
+ 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));
}
}
- Set storedReplies = storedSone.getReplies();
- synchronized (knownReplies) {
- for (PostReply reply : sone.getReplies()) {
- reply.setKnown(knownReplies.contains(reply.getId()));
- if (!storedReplies.contains(reply)) {
- if (reply.getTime() < getSoneFollowingTime(sone)) {
- knownReplies.add(reply.getId());
- reply.setKnown(true);
- } else if (!knownReplies.contains(reply.getId())) {
- eventBus.post(new NewPostReplyFoundEvent(reply));
- }
- }
- replies.put(reply.getId(), reply);
- }
+ });
+ soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
+ @Override
+ public void processPostReply(PostReply postReply) {
+ eventBus.post(new PostReplyRemovedEvent(postReply));
+ }
+ });
+ soneChangeDetector.detectChanges(sone);
+ /* store posts. */
+ database.storePosts(sone, sone.getPosts());
+ database.storePostReplies(sone, sone.getReplies());
+ for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
+ database.removeAlbum(album);
+ for (Image image : album.getImages()) {
+ database.removeImage(image);
}
}
- synchronized (albums) {
- synchronized (images) {
- for (Album album : storedSone.getAlbums()) {
- albums.remove(album.getId());
- for (Image image : album.getImages()) {
- images.remove(image.getId());
- }
- }
- for (Album album : sone.getAlbums()) {
- albums.put(album.getId(), album);
- for (Image image : album.getImages()) {
- images.put(image.getId(), image);
- }
- }
+ for (Album album : toAllAlbums.apply(sone)) {
+ database.storeAlbum(album);
+ for (Image image : album.getImages()) {
+ database.storeImage(image);
}
}
synchronized (sones) {
+ sone.setOptions(storedSone.get().getOptions());
+ sone.setKnown(storedSone.get().isKnown());
+ sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
+ if (sone.isLocal()) {
+ soneInserters.get(storedSone.get()).setSone(sone);
+ touchConfiguration();
+ }
sones.put(sone.getId(), sone);
}
}
@@ -1196,14 +1079,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
return;
}
-
- /* initialize options. */
- sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption(false));
- sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption(false));
- sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption(true));
- sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption(ShowCustomAvatars.NEVER));
+ logger.info(String.format("Loading local Sone: %s", sone));
/* load Sone. */
String sonePrefix = "Sone/" + sone.getId();
@@ -1215,171 +1091,80 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
/* load profile. */
- Profile profile = new Profile(sone);
- profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
- profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
- profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
- profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
- profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
- profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
-
- /* load profile fields. */
- while (true) {
- String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
- String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
- if (fieldName == null) {
- break;
- }
- String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
- profile.addField(fieldName).setValue(fieldValue);
- }
+ ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
+ Profile profile = configurationSoneParser.parseProfile();
/* load posts. */
- Set posts = new HashSet();
- while (true) {
- String postPrefix = sonePrefix + "/Posts/" + posts.size();
- String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
- if (postId == null) {
- break;
- }
- String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
- long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
- String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
- if ((postTime == 0) || (postText == null)) {
- logger.log(Level.WARNING, "Invalid post found, aborting load!");
- return;
- }
- PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
- if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
- postBuilder.to(postRecipientId);
- }
- posts.add(postBuilder.build());
+ Collection posts;
+ try {
+ posts = configurationSoneParser.parsePosts(database);
+ } catch (InvalidPostFound ipf) {
+ logger.log(Level.WARNING, "Invalid post found, aborting load!");
+ return;
}
/* load replies. */
- Set replies = new HashSet();
- while (true) {
- String replyPrefix = sonePrefix + "/Replies/" + replies.size();
- String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
- if (replyId == null) {
- break;
- }
- String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
- long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
- String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
- if ((postId == null) || (replyTime == 0) || (replyText == null)) {
- logger.log(Level.WARNING, "Invalid reply found, aborting load!");
- return;
- }
- PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
- postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
- replies.add(postReplyBuilder.build());
+ Collection replies;
+ try {
+ replies = configurationSoneParser.parsePostReplies(database);
+ } catch (InvalidPostReplyFound iprf) {
+ logger.log(Level.WARNING, "Invalid reply found, aborting load!");
+ return;
}
/* load post likes. */
- Set likedPostIds = new HashSet();
- while (true) {
- String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
- if (likedPostId == null) {
- break;
- }
- likedPostIds.add(likedPostId);
- }
+ Set likedPostIds =
+ configurationSoneParser.parseLikedPostIds();
/* load reply likes. */
- Set likedReplyIds = new HashSet();
- while (true) {
- String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
- if (likedReplyId == null) {
- break;
- }
- likedReplyIds.add(likedReplyId);
- }
+ Set likedReplyIds =
+ configurationSoneParser.parseLikedPostReplyIds();
/* load friends. */
- Set friends = new HashSet();
- while (true) {
- String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
- if (friendId == null) {
- break;
- }
- friends.add(friendId);
- }
+ Set friends = configurationSoneParser.parseFriends();
/* load albums. */
- List topLevelAlbums = new ArrayList();
- int albumCounter = 0;
- while (true) {
- String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
- String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
- if (albumId == null) {
- break;
- }
- String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
- String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
- String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
- String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
- if ((albumTitle == null) || (albumDescription == null)) {
- logger.log(Level.WARNING, "Invalid album found, aborting load!");
- return;
- }
- Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
- if (albumParentId != null) {
- Album parentAlbum = getAlbum(albumParentId, false);
- if (parentAlbum == null) {
- logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
- return;
- }
- parentAlbum.addAlbum(album);
- } else {
- if (!topLevelAlbums.contains(album)) {
- topLevelAlbums.add(album);
- }
- }
+ List topLevelAlbums;
+ try {
+ topLevelAlbums =
+ configurationSoneParser.parseTopLevelAlbums(database);
+ } catch (InvalidAlbumFound iaf) {
+ logger.log(Level.WARNING, "Invalid album found, aborting load!");
+ return;
+ } catch (InvalidParentAlbumFound ipaf) {
+ logger.log(Level.WARNING, format("Invalid parent album ID: %s",
+ ipaf.getAlbumParentId()));
+ return;
}
/* load images. */
- int imageCounter = 0;
- while (true) {
- String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
- String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
- if (imageId == null) {
- break;
- }
- String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
- String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
- String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
- String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
- Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
- Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
- Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
- if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
- logger.log(Level.WARNING, "Invalid image found, aborting load!");
- return;
- }
- Album album = getAlbum(albumId, false);
- if (album == null) {
- logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
- return;
- }
- Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
- image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
- album.addImage(image);
+ try {
+ configurationSoneParser.parseImages(database);
+ } catch (InvalidImageFound iif) {
+ logger.log(WARNING, "Invalid image found, aborting load!");
+ return;
+ } catch (InvalidParentAlbumFound ipaf) {
+ logger.log(Level.WARNING,
+ format("Invalid album image (%s) encountered, aborting load!",
+ ipaf.getAlbumParentId()));
+ return;
}
/* load avatar. */
String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
if (avatarId != null) {
- profile.setAvatar(getImage(avatarId, false));
+ final Map images =
+ configurationSoneParser.getImages();
+ profile.setAvatar(images.get(avatarId));
}
/* load options. */
- sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
- sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
- sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
- sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
- sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
- sone.getOptions(). getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
+ 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().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
/* if weâre still here, Sone was loaded successfully. */
synchronized (sone) {
@@ -1392,52 +1177,35 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
for (String friendId : friends) {
followSone(sone, friendId);
}
- sone.setAlbums(topLevelAlbums);
+ for (Album album : sone.getRootAlbum().getAlbums()) {
+ sone.getRootAlbum().removeAlbum(album);
+ }
+ for (Album album : topLevelAlbums) {
+ sone.getRootAlbum().addAlbum(album);
+ }
soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
+ for (Album album : toAllAlbums.apply(sone)) {
+ database.storeAlbum(album);
+ for (Image image : album.getImages()) {
+ database.storeImage(image);
+ }
+ }
}
synchronized (knownSones) {
for (String friend : friends) {
knownSones.add(friend);
}
}
- synchronized (knownPosts) {
- for (Post post : posts) {
- knownPosts.add(post.getId());
- }
+ database.storePosts(sone, posts);
+ for (Post post : posts) {
+ post.setKnown(true);
}
- synchronized (knownReplies) {
- for (PostReply reply : replies) {
- knownReplies.add(reply.getId());
- }
+ database.storePostReplies(sone, replies);
+ for (PostReply reply : replies) {
+ reply.setKnown(true);
}
- }
-
- /**
- * Creates a new post.
- *
- * @param sone
- * The Sone that creates the post
- * @param text
- * The text of the post
- * @return The created post
- */
- public Post createPost(Sone sone, String text) {
- return createPost(sone, System.currentTimeMillis(), text);
- }
- /**
- * Creates a new post.
- *
- * @param sone
- * The Sone that creates the post
- * @param time
- * The time of the post
- * @param text
- * The text of the post
- * @return The created post
- */
- public Post createPost(Sone sone, long time, String text) {
- return createPost(sone, null, time, text);
+ logger.info(String.format("Sone loaded successfully: %s", sone));
}
/**
@@ -1452,7 +1220,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* The text of the post
* @return The created post
*/
- public Post createPost(Sone sone, Sone recipient, String text) {
+ public Post createPost(Sone sone, Optional recipient, String text) {
return createPost(sone, recipient, System.currentTimeMillis(), text);
}
@@ -1470,35 +1238,24 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* The text of the post
* @return The created post
*/
- public Post createPost(Sone sone, Sone recipient, long time, String text) {
+ public Post createPost(Sone sone, Optional 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()) {
logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
return null;
}
- PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
+ PostBuilder postBuilder = database.newPostBuilder();
postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
- if (recipient != null) {
- postBuilder.to(recipient.getId());
+ if (recipient.isPresent()) {
+ postBuilder.to(recipient.get().getId());
}
final Post post = postBuilder.build();
- synchronized (posts) {
- posts.put(post.getId(), post);
- }
+ database.storePost(post);
eventBus.post(new NewPostFoundEvent(post));
sone.addPost(post);
touchConfiguration();
- localElementTicker.schedule(new Runnable() {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void run() {
- markPostKnown(post);
- }
- }, 10, TimeUnit.SECONDS);
+ localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
return post;
}
@@ -1513,10 +1270,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
return;
}
- post.getSone().removePost(post);
- synchronized (posts) {
- posts.remove(post.getId());
- }
+ database.removePost(post);
eventBus.post(new PostRemovedEvent(post));
markPostKnown(post);
touchConfiguration();
@@ -1531,28 +1285,14 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*/
public void markPostKnown(Post post) {
post.setKnown(true);
- synchronized (knownPosts) {
- eventBus.post(new MarkPostKnownEvent(post));
- if (knownPosts.add(post.getId())) {
- touchConfiguration();
- }
- }
- for (PostReply reply : getReplies(post)) {
+ eventBus.post(new MarkPostKnownEvent(post));
+ touchConfiguration();
+ for (PostReply reply : getReplies(post.getId())) {
markReplyKnown(reply);
}
}
/**
- * Bookmarks the given post.
- *
- * @param post
- * The post to bookmark
- */
- public void bookmark(Post post) {
- bookmarkPost(post.getId());
- }
-
- /**
* Bookmarks the post with the given ID.
*
* @param id
@@ -1604,27 +1344,14 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
return null;
}
- PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
+ PostReplyBuilder postReplyBuilder = postReplyBuilder();
postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
final PostReply reply = postReplyBuilder.build();
- synchronized (replies) {
- replies.put(reply.getId(), reply);
- }
- synchronized (knownReplies) {
- eventBus.post(new NewPostReplyFoundEvent(reply));
- }
+ database.storePostReply(reply);
+ eventBus.post(new NewPostReplyFoundEvent(reply));
sone.addReply(reply);
touchConfiguration();
- localElementTicker.schedule(new Runnable() {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void run() {
- markReplyKnown(reply);
- }
- }, 10, TimeUnit.SECONDS);
+ localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
return reply;
}
@@ -1640,13 +1367,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
return;
}
- synchronized (replies) {
- replies.remove(reply.getId());
- }
- synchronized (knownReplies) {
- markReplyKnown(reply);
- knownReplies.remove(reply.getId());
- }
+ database.removePostReply(reply);
+ markReplyKnown(reply);
sone.removeReply(reply);
touchConfiguration();
}
@@ -1659,27 +1381,15 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* The reply to mark as known
*/
public void markReplyKnown(PostReply reply) {
+ boolean previouslyKnown = reply.isKnown();
reply.setKnown(true);
- synchronized (knownReplies) {
- eventBus.post(new MarkPostReplyKnownEvent(reply));
- if (knownReplies.add(reply.getId())) {
- touchConfiguration();
- }
+ eventBus.post(new MarkPostReplyKnownEvent(reply));
+ if (!previouslyKnown) {
+ touchConfiguration();
}
}
/**
- * Creates a new top-level album for the given Sone.
- *
- * @param sone
- * The Sone to create the album for
- * @return The new album
- */
- public Album createAlbum(Sone sone) {
- return createAlbum(sone, null);
- }
-
- /**
* Creates a new album for the given Sone.
*
* @param sone
@@ -1690,16 +1400,9 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* @return The new album
*/
public Album createAlbum(Sone sone, Album parent) {
- Album album = new Album();
- synchronized (albums) {
- albums.put(album.getId(), album);
- }
- album.setSone(sone);
- if (parent != null) {
- parent.addAlbum(album);
- } else {
- sone.addAlbum(album);
- }
+ Album album = database.newAlbumBuilder().randomId().by(sone).build();
+ database.storeAlbum(album);
+ parent.addAlbum(album);
return album;
}
@@ -1716,14 +1419,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
if (!album.isEmpty()) {
return;
}
- if (album.getParent() == null) {
- album.getSone().removeAlbum(album);
- } else {
- album.getParent().removeAlbum(album);
- }
- synchronized (albums) {
- albums.remove(album.getId());
- }
+ album.getParent().removeAlbum(album);
+ database.removeAlbum(album);
touchConfiguration();
}
@@ -1744,11 +1441,9 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
checkNotNull(temporaryImage, "temporaryImage must not be null");
checkArgument(sone.isLocal(), "sone must be a local Sone");
checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
- Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
+ Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
album.addImage(image);
- synchronized (images) {
- images.put(image.getId(), image);
- }
+ database.storeImage(image);
imageInserter.insertImage(temporaryImage, image);
return image;
}
@@ -1757,7 +1452,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
* Deletes the given image. This method will also delete a matching
* temporary image.
*
- * @see #deleteTemporaryImage(TemporaryImage)
+ * @see #deleteTemporaryImage(String)
* @param image
* The image to delete
*/
@@ -1766,9 +1461,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
deleteTemporaryImage(image.getId());
image.getAlbum().removeImage(image);
- synchronized (images) {
- images.remove(image.getId());
- }
+ database.removeImage(image);
touchConfiguration();
}
@@ -1791,17 +1484,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
}
/**
- * Deletes the given temporary image.
- *
- * @param temporaryImage
- * The temporary image to delete
- */
- public void deleteTemporaryImage(TemporaryImage temporaryImage) {
- checkNotNull(temporaryImage, "temporaryImage must not be null");
- deleteTemporaryImage(temporaryImage.getId());
- }
-
- /**
* Deletes the temporary image with the given ID.
*
* @param imageId
@@ -1841,6 +1523,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
identityManager.start();
webOfTrustUpdater.init();
webOfTrustUpdater.start();
+ database.start();
}
/**
@@ -1871,10 +1554,11 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
synchronized (sones) {
for (Entry soneInserter : soneInserters.entrySet()) {
soneInserter.getValue().stop();
- saveSone(soneInserter.getKey());
+ saveSone(getLocalSone(soneInserter.getKey().getId(), false));
}
}
saveConfiguration();
+ database.stop();
webOfTrustUpdater.stop();
updateChecker.stop();
soneDownloader.stop();
@@ -1934,7 +1618,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
for (Post post : sone.getPosts()) {
String postPrefix = sonePrefix + "/Posts/" + postCounter++;
configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
- configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
+ configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
}
@@ -1973,7 +1657,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
/* save albums. first, collect in a flat structure, top-level first. */
- List albums = sone.getAllAlbums();
+ List albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
int albumCounter = 0;
for (Album album : albums) {
@@ -1981,7 +1665,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
- configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
+ 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);
@@ -2007,12 +1691,12 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
/* save options. */
- configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
- configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
- configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
- configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
- configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
- configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions(). getEnumOption("ShowCustomAvatars").get().name());
+ configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
+ configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
+ configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
+ configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
+ configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
+ configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
configuration.save();
@@ -2072,22 +1756,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
}
/* save known posts. */
- int postCounter = 0;
- synchronized (knownPosts) {
- for (String knownPostId : knownPosts) {
- configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
- }
- configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
- }
-
- /* save known replies. */
- int replyCounter = 0;
- synchronized (knownReplies) {
- for (String knownReplyId : knownReplies) {
- configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
- }
- configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
- }
+ database.save();
/* save bookmarked posts. */
int bookmarkedPostCounter = 0;
@@ -2103,6 +1772,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
} catch (ConfigurationException ce1) {
logger.log(Level.SEVERE, "Could not store configuration!", ce1);
+ } catch (DatabaseException de1) {
+ logger.log(Level.SEVERE, "Could not save database!", de1);
} finally {
synchronized (configuration) {
storingConfiguration = false;
@@ -2113,17 +1784,9 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
/**
* Loads the configuration.
*/
- @SuppressWarnings("unchecked")
private void loadConfiguration() {
/* create options. */
- options.addIntegerOption("InsertionDelay", new DefaultOption(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher() {
-
- @Override
- public void optionChanged(Option option, Integer oldValue, Integer newValue) {
- SoneInserter.setInsertionDelay(newValue);
- }
-
- }));
+ options.addIntegerOption("InsertionDelay", new DefaultOption(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
options.addIntegerOption("PostsPerPage", new DefaultOption(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
options.addIntegerOption("ImagesPerPage", new DefaultOption(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
options.addIntegerOption("CharactersPerPost", new DefaultOption(400, Predicates. or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
@@ -2132,23 +1795,8 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
options.addIntegerOption("PositiveTrust", new DefaultOption(75, new IntegerRangePredicate(0, 100)));
options.addIntegerOption("NegativeTrust", new DefaultOption(-25, new IntegerRangePredicate(-100, 100)));
options.addStringOption("TrustComment", new DefaultOption("Set from Sone Web Interface"));
- options.addBooleanOption("ActivateFcpInterface", new DefaultOption(false, new OptionWatcher() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void optionChanged(Option option, Boolean oldValue, Boolean newValue) {
- fcpInterface.setActive(newValue);
- }
- }));
- options.addIntegerOption("FcpFullAccessRequired", new DefaultOption(2, new OptionWatcher() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void optionChanged(Option option, Integer oldValue, Integer newValue) {
- fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
- }
-
- }));
+ options.addBooleanOption("ActivateFcpInterface", new DefaultOption(false, fcpInterface.new SetActive()));
+ options.addIntegerOption("FcpFullAccessRequired", new DefaultOption(2, fcpInterface.new SetFullAccessRequired()));
loadConfigurationValue("InsertionDelay");
loadConfigurationValue("PostsPerPage");
@@ -2182,41 +1830,12 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
break;
}
long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
- Sone followedSone = getSone(soneId);
- if (followedSone == null) {
- logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
- } else {
- synchronized (soneFollowingTimes) {
- soneFollowingTimes.put(soneId, time);
- }
+ synchronized (soneFollowingTimes) {
+ soneFollowingTimes.put(soneId, time);
}
++soneCounter;
}
- /* load known posts. */
- int postCounter = 0;
- while (true) {
- String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
- if (knownPostId == null) {
- break;
- }
- synchronized (knownPosts) {
- knownPosts.add(knownPostId);
- }
- }
-
- /* load known replies. */
- int replyCounter = 0;
- while (true) {
- String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
- if (knownReplyId == null) {
- break;
- }
- synchronized (knownReplies) {
- knownReplies.add(knownReplyId);
- }
- }
-
/* load bookmarked posts. */
int bookmarkedPostCounter = 0;
while (true) {
@@ -2257,7 +1876,6 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
if (ownIdentity.hasContext("Sone")) {
- trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet()));
addLocalSone(ownIdentity);
}
}
@@ -2272,7 +1890,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
- trustedIdentities.remove(ownIdentity);
+ trustedIdentities.removeAll(ownIdentity);
}
/**
@@ -2285,7 +1903,7 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
public void identityAdded(IdentityAddedEvent identityAddedEvent) {
Identity identity = identityAddedEvent.identity();
logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
- trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
+ trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
addRemoteSone(identity);
}
@@ -2297,19 +1915,15 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
*/
@Subscribe
public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
- final Identity identity = identityUpdatedEvent.identity();
- soneDownloaders.execute(new Runnable() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void run() {
- Sone sone = getRemoteSone(identity.getId(), false);
- sone.setIdentity(identity);
- sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
- soneDownloader.addSone(sone);
- soneDownloader.fetchSone(sone);
- }
- });
+ Identity identity = identityUpdatedEvent.identity();
+ final Sone sone = getRemoteSone(identity.getId(), false);
+ if (sone.isLocal()) {
+ return;
+ }
+ sone.setIdentity(identity);
+ sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
+ soneDownloader.addSone(sone);
+ soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
}
/**
@@ -2322,45 +1936,32 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
Identity identity = identityRemovedEvent.identity();
- trustedIdentities.get(ownIdentity).remove(identity);
- boolean foundIdentity = false;
- for (Entry> trustedIdentity : trustedIdentities.entrySet()) {
+ trustedIdentities.remove(ownIdentity, identity);
+ for (Entry> trustedIdentity : trustedIdentities.asMap().entrySet()) {
if (trustedIdentity.getKey().equals(ownIdentity)) {
continue;
}
if (trustedIdentity.getValue().contains(identity)) {
- foundIdentity = true;
+ return;
}
}
- if (foundIdentity) {
- /* some local identity still trusts this identity, donât remove. */
- return;
- }
- Sone sone = getSone(identity.getId(), false);
- if (sone == null) {
+ Optional sone = getSone(identity.getId());
+ if (!sone.isPresent()) {
/* TODO - we donât have the Sone anymore. should this happen? */
return;
}
- synchronized (posts) {
- synchronized (knownPosts) {
- for (Post post : sone.getPosts()) {
- posts.remove(post.getId());
- eventBus.post(new PostRemovedEvent(post));
- }
- }
+ database.removePosts(sone.get());
+ for (Post post : sone.get().getPosts()) {
+ eventBus.post(new PostRemovedEvent(post));
}
- synchronized (replies) {
- synchronized (knownReplies) {
- for (PostReply reply : sone.getReplies()) {
- replies.remove(reply.getId());
- eventBus.post(new PostReplyRemovedEvent(reply));
- }
- }
+ database.removePostReplies(sone.get());
+ for (PostReply reply : sone.get().getReplies()) {
+ eventBus.post(new PostReplyRemovedEvent(reply));
}
synchronized (sones) {
sones.remove(identity.getId());
}
- eventBus.post(new SoneRemovedEvent(sone));
+ eventBus.post(new SoneRemovedEvent(sone.get()));
}
/**
@@ -2372,9 +1973,41 @@ public class Core extends AbstractService implements SoneProvider, PostProvider,
@Subscribe
public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
- imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
+ imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
touchConfiguration();
}
+ @VisibleForTesting
+ class MarkPostKnown implements Runnable {
+
+ private final Post post;
+
+ public MarkPostKnown(Post post) {
+ this.post = post;
+ }
+
+ @Override
+ public void run() {
+ markPostKnown(post);
+ }
+
+ }
+
+ @VisibleForTesting
+ class MarkReplyKnown implements Runnable {
+
+ private final PostReply postReply;
+
+ public MarkReplyKnown(PostReply postReply) {
+ this.postReply = postReply;
+ }
+
+ @Override
+ public void run() {
+ markReplyKnown(postReply);
+ }
+
+ }
+
}