X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;ds=inline;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fcore%2FCore.java;h=2ff27c954f9d7e9c1f4307ce7fb730e767d2ffad;hb=23e6594201b63aca5955113106011542810e2778;hp=0f733b6e458a2f240e01df782990344675941639;hpb=21c4819261de874652e7c8be37bde5923758cf4b;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 0f733b6..2ff27c9 100644
--- a/src/main/java/net/pterodactylus/sone/core/Core.java
+++ b/src/main/java/net/pterodactylus/sone/core/Core.java
@@ -1,5 +1,5 @@
/*
- * FreenetSone - Core.java - Copyright © 2010 David Roden
+ * Sone - Core.java - Copyright © 2010â2019 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
@@ -17,98 +17,201 @@
package net.pterodactylus.sone.core;
-import java.net.MalformedURLException;
+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.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.Collections;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
-import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
-import net.pterodactylus.sone.core.SoneException.Type;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+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.event.ImageInsertFinishedEvent;
+import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
+import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
+import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
+import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
+import net.pterodactylus.sone.core.event.NewPostFoundEvent;
+import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
+import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
+import net.pterodactylus.sone.core.event.PostRemovedEvent;
+import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
+import net.pterodactylus.sone.core.event.SoneLockedEvent;
+import net.pterodactylus.sone.core.event.SoneRemovedEvent;
+import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
+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.PostReply;
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.SoneStatus;
+import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
+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.SoneBuilder;
+import net.pterodactylus.sone.database.SoneProvider;
+import net.pterodactylus.sone.freenet.wot.Identity;
+import net.pterodactylus.sone.freenet.wot.IdentityManager;
+import net.pterodactylus.sone.freenet.wot.OwnIdentity;
+import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
+import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
+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.util.config.Configuration;
import net.pterodactylus.util.config.ConfigurationException;
-import net.pterodactylus.util.filter.Filter;
-import net.pterodactylus.util.filter.Filters;
-import net.pterodactylus.util.logging.Logging;
import net.pterodactylus.util.service.AbstractService;
-import freenet.client.FetchResult;
-import freenet.keys.FreenetURI;
+import net.pterodactylus.util.thread.NamedThreadFactory;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.HashMultimap;
+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 kotlin.jvm.functions.Function1;
/**
* The Sone core.
- *
- * @author David âBombeâ Roden
*/
-public class Core extends AbstractService {
+@Singleton
+public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
- /**
- * Enumeration for the possible states of a {@link Sone}.
- *
- * @author David âBombeâ Roden
- */
- public enum SoneStatus {
+ /** The logger. */
+ private static final Logger logger = getLogger(Core.class.getName());
- /** The Sone is unknown, i.e. not yet downloaded. */
- unknown,
+ /** The start time. */
+ private final long startupTime = System.currentTimeMillis();
- /** The Sone is idle, i.e. not being downloaded or inserted. */
- idle,
+ /** The preferences. */
+ private final Preferences preferences;
- /** The Sone is currently being inserted. */
- inserting,
+ /** The event bus. */
+ private final EventBus eventBus;
- /** The Sone is currently being downloaded. */
- downloading,
- }
+ /** The configuration. */
+ private final Configuration configuration;
- /** The logger. */
- private static final Logger logger = Logging.getLogger(Core.class);
+ /** Whether weâre currently saving the configuration. */
+ private boolean storingConfiguration = false;
- /** The configuration. */
- private Configuration configuration;
+ /** The identity manager. */
+ private final IdentityManager identityManager;
/** Interface to freenet. */
- private FreenetInterface freenetInterface;
+ private final FreenetInterface freenetInterface;
/** The Sone downloader. */
- private SoneDownloader soneDownloader;
+ private final SoneDownloader soneDownloader;
+
+ /** The image inserter. */
+ private final ImageInserter imageInserter;
+
+ /** Sone downloader thread-pool. */
+ private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
- /** The local Sones. */
- private final Set localSones = new HashSet();
+ /** The update checker. */
+ private final UpdateChecker updateChecker;
+
+ /** The trust updater. */
+ private final WebOfTrustUpdater webOfTrustUpdater;
+
+ /** Locked local Sones. */
+ /* synchronize on itself. */
+ private final Set lockedSones = new HashSet<>();
/** Sone inserters. */
- private final Map soneInserters = new HashMap();
+ /* synchronize access on this on sones. */
+ private final Map soneInserters = new HashMap<>();
+
+ /** Sone rescuers. */
+ /* synchronize access on this on sones. */
+ private final Map soneRescuers = new HashMap<>();
- /** The Sonesâ statuses. */
- private final Map soneStatuses = new HashMap();
+ /** All known Sones. */
+ private final Set knownSones = new HashSet<>();
- /* various caches follow here. */
+ /** The post database. */
+ private final Database database;
- /** Cache for all known Sones. */
- private final Map soneCache = new HashMap();
+ /** Trusted identities, sorted by own identities. */
+ private final Multimap trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.create());
- /** Cache for all known posts. */
- private final Map postCache = new HashMap();
+ /** All temporary images. */
+ private final Map temporaryImages = new HashMap<>();
- /** Cache for all known replies. */
- private final Map replyCache = new HashMap();
+ /** Ticker for threads that mark own elements as known. */
+ private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
+
+ /** The time the configuration was last touched. */
+ private volatile long lastConfigurationUpdate;
/**
* Creates a new core.
+ *
+ * @param configuration
+ * The configuration of the core
+ * @param freenetInterface
+ * The freenet interface
+ * @param identityManager
+ * The identity manager
+ * @param webOfTrustUpdater
+ * The WebOfTrust updater
+ * @param eventBus
+ * The event bus
+ * @param database
+ * The database
*/
- public Core() {
+ @Inject
+ public 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;
+ preferences = new Preferences(eventBus);
}
//
@@ -116,167 +219,349 @@ public class Core extends AbstractService {
//
/**
- * Sets the configuration of the core.
+ * Returns the time Sone was started.
*
- * @param configuration
- * The configuration of the core
- * @return This core (for method chaining)
+ * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
*/
- public Core configuration(Configuration configuration) {
- this.configuration = configuration;
- return this;
+ public long getStartupTime() {
+ return startupTime;
}
/**
- * Sets the Freenet interface to use.
+ * Returns the options used by the core.
*
- * @param freenetInterface
- * The Freenet interface to use
- * @return This core (for method chaining)
+ * @return The options of the core
*/
- public Core freenetInterface(FreenetInterface freenetInterface) {
- this.freenetInterface = freenetInterface;
- soneDownloader = new SoneDownloader(this, freenetInterface);
- soneDownloader.start();
- return this;
+ public Preferences getPreferences() {
+ return preferences;
}
/**
- * Returns the local Sones.
+ * Returns the identity manager used by the core.
*
- * @return The local Sones
+ * @return The identity manager
*/
- public Set getSones() {
- return Collections.unmodifiableSet(localSones);
+ public IdentityManager getIdentityManager() {
+ return identityManager;
}
/**
- * Returns the Sone with the given ID, or an empty Sone that has been
- * initialized with the given ID.
+ * Returns the update checker.
*
- * @param soneId
- * The ID of the Sone
- * @return The Sone
+ * @return The update checker
+ */
+ public UpdateChecker getUpdateChecker() {
+ return updateChecker;
+ }
+
+ /**
+ * Returns the Sone rescuer for the given local Sone.
+ *
+ * @param sone
+ * The local Sone to get the rescuer for
+ * @return The Sone rescuer for the given Sone
*/
- public Sone getSone(String soneId) {
- if (!soneCache.containsKey(soneId)) {
- Sone sone = new Sone(soneId);
- soneCache.put(soneId, sone);
- setSoneStatus(sone, SoneStatus.unknown);
+ public SoneRescuer getSoneRescuer(Sone sone) {
+ checkNotNull(sone, "sone must not be null");
+ checkArgument(sone.isLocal(), "sone must be local");
+ synchronized (soneRescuers) {
+ SoneRescuer soneRescuer = soneRescuers.get(sone);
+ if (soneRescuer == null) {
+ soneRescuer = new SoneRescuer(this, soneDownloader, sone);
+ soneRescuers.put(sone, soneRescuer);
+ soneRescuer.start();
+ }
+ return soneRescuer;
}
- return soneCache.get(soneId);
}
/**
- * Returns all known sones.
+ * Returns whether the given Sone is currently locked.
*
- * @return All known sones
+ * @param sone
+ * The sone to check
+ * @return {@code true} if the Sone is locked, {@code false} if it is not
*/
- public Collection getKnownSones() {
- return soneCache.values();
+ public boolean isLocked(Sone sone) {
+ synchronized (lockedSones) {
+ return lockedSones.contains(sone);
+ }
+ }
+
+ public SoneBuilder soneBuilder() {
+ return database.newSoneBuilder();
+ }
+
+ /**
+ * {@inheritDocs}
+ */
+ @Nonnull
+ @Override
+ public Collection getSones() {
+ return database.getSones();
+ }
+
+ @Nonnull
+ @Override
+ public Function1 getSoneLoader() {
+ return database.getSoneLoader();
}
/**
- * Gets all known Sones that are not local Sones.
+ * Returns the Sone with the given ID, regardless whether itâs local or
+ * remote.
*
- * @return All remote Sones
+ * @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
*/
- public Collection getRemoteSones() {
- return Filters.filteredCollection(getKnownSones(), new Filter() {
+ @Override
+ @Nullable
+ public Sone getSone(@Nonnull String id) {
+ return database.getSone(id);
+ }
- @Override
- @SuppressWarnings("synthetic-access")
- public boolean filterObject(Sone object) {
- return !localSones.contains(object);
- }
- });
+ /**
+ * {@inheritDocs}
+ */
+ @Override
+ public Collection getLocalSones() {
+ return database.getLocalSones();
}
/**
- * Returns the status of the given Sone.
+ * Returns the local Sone with the given ID, optionally creating a new Sone.
*
- * @param sone
- * The Sone to get the status for
- * @return The status of the Sone
+ * @param id
+ * The ID of the Sone
+ * @return The Sone with the given ID, or {@code null}
+ */
+ public Sone getLocalSone(String id) {
+ Sone sone = database.getSone(id);
+ if ((sone != null) && sone.isLocal()) {
+ return sone;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDocs}
*/
- public SoneStatus getSoneStatus(Sone sone) {
- return soneStatuses.get(sone);
+ @Override
+ public Collection getRemoteSones() {
+ return database.getRemoteSones();
}
/**
- * Sets the status of the Sone.
+ * Returns the remote Sone with the given ID.
*
- * @param sone
- * The Sone to set the status for
- * @param soneStatus
- * The status of the Sone
+ *
+ * @param id
+ * The ID of the remote Sone to get
+ * @return The Sone with the given ID
*/
- public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
- soneStatuses.put(sone, soneStatus);
+ public Sone getRemoteSone(String id) {
+ return database.getSone(id);
}
/**
- * Creates a new post and adds it to the given Sone.
+ * Returns whether the given Sone has been modified.
*
* @param sone
- * The sone that creates the post
- * @param text
- * The text of the post
- * @return The created post
+ * The Sone to check for modifications
+ * @return {@code true} if a modification has been detected in the Sone,
+ * {@code false} otherwise
*/
- public Post createPost(Sone sone, String text) {
- return createPost(sone, System.currentTimeMillis(), text);
+ public boolean isModifiedSone(Sone sone) {
+ return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
}
/**
- * Creates a new post and adds it to the given Sone.
+ * Returns a post builder.
*
- * @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
+ * @return A new post builder
*/
- public Post createPost(Sone sone, long time, String text) {
- Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
- sone.addPost(post);
- return post;
+ public PostBuilder postBuilder() {
+ return database.newPostBuilder();
+ }
+
+ @Nullable
+ @Override
+ public Post getPost(@Nonnull String postId) {
+ return database.getPost(postId);
+ }
+
+ /**
+ * {@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);
}
/**
- * Creates a reply.
+ * Returns a post reply builder.
+ *
+ * @return A new post reply builder
+ */
+ public PostReplyBuilder postReplyBuilder() {
+ return database.newPostReplyBuilder();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Nullable
+ @Override
+ public PostReply getPostReply(String replyId) {
+ return database.getPostReply(replyId);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List getReplies(final String postId) {
+ return database.getReplies(postId);
+ }
+
+ /**
+ * Returns all Sones that have liked the given post.
*
- * @param sone
- * The Sone that posts the reply
* @param post
- * The post the reply refers to
- * @param text
- * The text of the reply
- * @return The created reply
+ * The post to get the liking Sones for
+ * @return The Sones that like the given post
*/
- public Reply createReply(Sone sone, Post post, String text) {
- return createReply(sone, post, System.currentTimeMillis(), text);
+ public Set getLikes(Post post) {
+ Set sones = new HashSet<>();
+ for (Sone sone : getSones()) {
+ if (sone.getLikedPostIds().contains(post.getId())) {
+ sones.add(sone);
+ }
+ }
+ return sones;
}
/**
- * Creates a reply.
+ * Returns all Sones that have liked the given reply.
+ *
+ * @param reply
+ * The reply to get the liking Sones for
+ * @return The Sones that like the given reply
+ */
+ public Set getLikes(PostReply reply) {
+ Set sones = new HashSet<>();
+ for (Sone sone : getSones()) {
+ if (sone.getLikedReplyIds().contains(reply.getId())) {
+ sones.add(sone);
+ }
+ }
+ return sones;
+ }
+
+ /**
+ * Returns whether the given post is bookmarked.
*
- * @param sone
- * The Sone that posts the reply
* @param post
- * The post the reply refers to
- * @param time
- * The time of the post
- * @param text
- * The text of the reply
- * @return The created reply
+ * The post to check
+ * @return {@code true} if the given post is bookmarked, {@code false}
+ * otherwise
*/
- public Reply createReply(Sone sone, Post post, long time, String text) {
- Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
- sone.addReply(reply);
- return reply;
+ public boolean isBookmarked(Post post) {
+ return database.isPostBookmarked(post);
+ }
+
+ /**
+ * Returns all currently known bookmarked posts.
+ *
+ * @return All bookmarked posts
+ */
+ public Set getBookmarkedPosts() {
+ return database.getBookmarkedPosts();
+ }
+
+ public AlbumBuilder albumBuilder() {
+ return database.newAlbumBuilder();
+ }
+
+ /**
+ * Returns the album with the given ID, optionally creating a new album if
+ * an album with the given ID can not be found.
+ *
+ * @param albumId
+ * The ID of the album
+ * @return The album with the given ID, or {@code null} if no album with the
+ * given ID exists
+ */
+ @Nullable
+ public Album getAlbum(@Nonnull String albumId) {
+ return database.getAlbum(albumId);
+ }
+
+ public ImageBuilder imageBuilder() {
+ return database.newImageBuilder();
+ }
+
+ /**
+ * Returns the image with the given ID, creating it if necessary.
+ *
+ * @param imageId
+ * The ID of the image
+ * @return The image with the given ID
+ */
+ @Nullable
+ public Image getImage(String imageId) {
+ return getImage(imageId, true);
+ }
+
+ /**
+ * Returns the image with the given ID, optionally creating it if it does
+ * not exist.
+ *
+ * @param imageId
+ * The ID of the image
+ * @param create
+ * {@code true} to create an image if none exists with the given
+ * ID
+ * @return The image with the given ID, or {@code null} if none exists and
+ * none was created
+ */
+ @Nullable
+ public Image getImage(String imageId, boolean create) {
+ Image image = database.getImage(imageId);
+ if (image != null) {
+ return image;
+ }
+ if (!create) {
+ return null;
+ }
+ Image newImage = database.newImageBuilder().withId(imageId).build();
+ database.storeImage(newImage);
+ return newImage;
+ }
+
+ /**
+ * Returns the temporary image with the given ID.
+ *
+ * @param imageId
+ * The ID of the temporary image
+ * @return The temporary image, or {@code null} if there is no temporary
+ * image with the given ID
+ */
+ public TemporaryImage getTemporaryImage(String imageId) {
+ synchronized (temporaryImages) {
+ return temporaryImages.get(imageId);
+ }
}
//
@@ -284,242 +569,748 @@ public class Core extends AbstractService {
//
/**
- * Adds a Sone to watch for updates. The Sone needs to be completely
- * initialized.
+ * Locks the given Sone. A locked Sone will not be inserted by
+ * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
+ * again.
*
* @param sone
- * The Sone to watch for updates
+ * The sone to lock
*/
- public void addSone(Sone sone) {
- soneCache.put(sone.getId(), sone);
- if (!localSones.contains(sone)) {
- soneDownloader.addSone(sone);
+ public void lockSone(Sone sone) {
+ synchronized (lockedSones) {
+ if (lockedSones.add(sone)) {
+ eventBus.post(new SoneLockedEvent(sone));
+ }
}
}
/**
- * Adds the given Sone.
+ * Unlocks the given Sone.
*
+ * @see #lockSone(Sone)
* @param sone
- * The Sone to add
+ * The sone to unlock
+ */
+ public void unlockSone(Sone sone) {
+ synchronized (lockedSones) {
+ if (lockedSones.remove(sone)) {
+ eventBus.post(new SoneUnlockedEvent(sone));
+ }
+ }
+ }
+
+ /**
+ * Adds a local Sone from the given own identity.
+ *
+ * @param ownIdentity
+ * The own identity to create a Sone from
+ * @return The added (or already existing) Sone
*/
- public void addLocalSone(Sone sone) {
- if (localSones.add(sone)) {
- setSoneStatus(sone, SoneStatus.idle);
- SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
- soneInserter.start();
+ public Sone addLocalSone(OwnIdentity ownIdentity) {
+ if (ownIdentity == null) {
+ logger.log(Level.WARNING, "Given OwnIdentity is null!");
+ return null;
+ }
+ logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
+ Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
+ 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);
+ SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
+ soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
+ eventBus.register(soneInserter);
+ synchronized (soneInserters) {
soneInserters.put(sone, soneInserter);
}
+ loadSone(sone);
+ database.storeSone(sone);
+ sone.setStatus(SoneStatus.idle);
+ soneInserter.start();
+ return sone;
}
/**
- * Creates a new Sone at a random location.
+ * Creates a new Sone for the given own identity.
*
- * @param name
- * The name of the Sone
+ * @param ownIdentity
+ * The own identity to create a Sone for
* @return The created Sone
- * @throws SoneException
- * if a Sone error occurs
*/
- public Sone createSone(String name) throws SoneException {
- return createSone(name, "Sone-" + name, null, null);
+ public Sone createSone(OwnIdentity ownIdentity) {
+ if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
+ logger.log(Level.SEVERE, String.format("Could not add âSoneâ context to own identity: %s", ownIdentity));
+ return null;
+ }
+ Sone sone = addLocalSone(ownIdentity);
+
+ followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
+ touchConfiguration();
+ return sone;
}
/**
- * Creates a new Sone at the given location. If one of {@code requestUri} or
- * {@code insertUrI} is {@code null}, the Sone is created at a random
- * location.
+ * Adds the Sone of the given identity.
*
- * @param name
- * The name of the Sone
- * @param documentName
- * The document name in the SSK
- * @param requestUri
- * The request URI of the Sone, or {@link NullPointerException}
- * to create a Sone at a random location
- * @param insertUri
- * The insert URI of the Sone, or {@code null} to create a Sone
- * at a random location
- * @return The created Sone
- * @throws SoneException
- * if a Sone error occurs
- */
- public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
- if ((name == null) || (name.trim().length() == 0)) {
- throw new SoneException(Type.INVALID_SONE_NAME);
- }
- String finalRequestUri;
- String finalInsertUri;
- if ((requestUri == null) || (insertUri == null)) {
- String[] keyPair = freenetInterface.generateKeyPair();
- finalRequestUri = keyPair[0];
- finalInsertUri = keyPair[1];
- } else {
- finalRequestUri = requestUri;
- finalInsertUri = insertUri;
- }
- Sone sone;
- try {
- logger.log(Level.FINEST, "Creating new Sone â%sâ at %s (%s)â¦", new Object[] { name, finalRequestUri, finalInsertUri });
- sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
- sone.setProfile(new Profile());
- /* set modification counter to 1 so it is inserted immediately. */
- sone.setModificationCounter(1);
- addLocalSone(sone);
- } catch (MalformedURLException mue1) {
- throw new SoneException(Type.INVALID_URI);
+ * @param identity
+ * The identity whose Sone to add
+ * @return The added or already existing Sone
+ */
+ public Sone addRemoteSone(Identity identity) {
+ if (identity == null) {
+ logger.log(Level.WARNING, "Given Identity is null!");
+ return null;
+ }
+ String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
+ long latestEdition = fromNullable(tryParse(property)).or(0L);
+ Sone existingSone = getSone(identity.getId());
+ if ((existingSone != null )&& existingSone.isLocal()) {
+ return existingSone;
+ }
+ boolean newSone = existingSone == null;
+ Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
+ sone.setLatestEdition(latestEdition);
+ if (newSone) {
+ synchronized (knownSones) {
+ newSone = !knownSones.contains(sone.getId());
+ }
+ sone.setKnown(!newSone);
+ if (newSone) {
+ eventBus.post(new NewSoneFoundEvent(sone));
+ for (Sone localSone : getLocalSones()) {
+ if (localSone.getOptions().isAutoFollow()) {
+ followSone(localSone, sone.getId());
+ }
+ }
+ }
}
+ database.storeSone(sone);
+ soneDownloader.addSone(sone);
+ soneDownloaders.execute(soneDownloader.fetchSoneAsUskAction(sone));
return sone;
}
/**
- * Loads the Sone from the given request URI. The fetching of the data is
- * performed in a new thread so this method returns immediately.
+ * Lets the given local Sone follow the Sone with the given ID.
*
- * @param requestUri
- * The request URI to load the Sone from
+ * @param sone
+ * The local Sone that should follow another Sone
+ * @param soneId
+ * The ID of the Sone to follow
*/
- public void loadSone(final String requestUri) {
- loadSone(requestUri, null);
+ public void followSone(Sone sone, String soneId) {
+ checkNotNull(sone, "sone must not be null");
+ checkNotNull(soneId, "soneId must not be null");
+ database.addFriend(sone, soneId);
+ @SuppressWarnings("ConstantConditions") // we just followed, this canât be null.
+ long now = database.getFollowingTime(soneId);
+ Sone followedSone = getSone(soneId);
+ if (followedSone == null) {
+ return;
+ }
+ for (Post post : followedSone.getPosts()) {
+ if (post.getTime() < now) {
+ markPostKnown(post);
+ }
+ }
+ for (PostReply reply : followedSone.getReplies()) {
+ if (reply.getTime() < now) {
+ markReplyKnown(reply);
+ }
+ }
+ touchConfiguration();
}
/**
- * Loads the Sone from the given request URI. The fetching of the data is
- * performed in a new thread so this method returns immediately. If
- * {@code insertUri} is not {@code null} the loaded Sone is converted into a
- * local Sone and available using as any other local Sone.
+ * Lets the given local Sone unfollow the Sone with the given ID.
*
- * @param requestUri
- * The request URI to load the Sone from
- * @param insertUri
- * The insert URI of the Sone
+ * @param sone
+ * The local Sone that should unfollow another Sone
+ * @param soneId
+ * The ID of the Sone being unfollowed
*/
- public void loadSone(final String requestUri, final String insertUri) {
- new Thread(new Runnable() {
+ public void unfollowSone(Sone sone, String soneId) {
+ checkNotNull(sone, "sone must not be null");
+ checkNotNull(soneId, "soneId must not be null");
+ database.removeFriend(sone, soneId);
+ touchConfiguration();
+ }
- @Override
- @SuppressWarnings("synthetic-access")
- public void run() {
- try {
- FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
- FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
- if (fetchResult == null) {
- return;
- }
- Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
- if (parsedSone != null) {
- if (insertUri != null) {
- parsedSone.setInsertUri(new FreenetURI(insertUri));
- addLocalSone(parsedSone);
- } else {
- addSone(parsedSone);
- }
- }
- } catch (MalformedURLException mue1) {
- logger.log(Level.INFO, "Could not create URI from â" + requestUri + "â.", mue1);
- }
- }
- }, "Sone Downloader").start();
+ /**
+ * Sets the trust value of the given origin Sone for the target Sone.
+ *
+ * @param origin
+ * The origin Sone
+ * @param target
+ * The target Sone
+ * @param trustValue
+ * The trust value (from {@code -100} to {@code 100})
+ */
+ public void setTrust(Sone origin, Sone target, int trustValue) {
+ checkNotNull(origin, "origin must not be null");
+ checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
+ checkNotNull(target, "target must not be null");
+ checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
+ webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
+ }
+
+ /**
+ * Removes any trust assignment for the given target Sone.
+ *
+ * @param origin
+ * The trust origin
+ * @param target
+ * The trust target
+ */
+ public void removeTrust(Sone origin, Sone target) {
+ checkNotNull(origin, "origin must not be null");
+ checkNotNull(target, "target must not be null");
+ checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
+ webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
}
/**
- * Loads and updates the given Sone.
+ * Assigns the configured positive trust value for the given target.
+ *
+ * @param origin
+ * The trust origin
+ * @param target
+ * The trust target
+ */
+ public void trustSone(Sone origin, Sone target) {
+ setTrust(origin, target, preferences.getPositiveTrust());
+ }
+
+ /**
+ * Assigns the configured negative trust value for the given target.
+ *
+ * @param origin
+ * The trust origin
+ * @param target
+ * The trust target
+ */
+ public void distrustSone(Sone origin, Sone target) {
+ setTrust(origin, target, preferences.getNegativeTrust());
+ }
+
+ /**
+ * Removes the trust assignment for the given target.
+ *
+ * @param origin
+ * The trust origin
+ * @param target
+ * The trust target
+ */
+ public void untrustSone(Sone origin, Sone target) {
+ removeTrust(origin, target);
+ }
+
+ /**
+ * Updates the stored Sone with the given Sone.
*
* @param sone
- * The Sone to load
- */
- public void loadSone(final Sone sone) {
- new Thread(new Runnable() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void run() {
- FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
- setSoneStatus(sone, SoneStatus.downloading);
- try {
- FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
- if (fetchResult == null) {
- /* TODO - mark Sone as bad. */
- return;
- }
- Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
- if (parsedSone != null) {
- addSone(parsedSone);
- }
- } finally {
- setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
- }
+ * The updated Sone
+ */
+ public void updateSone(Sone sone) {
+ updateSone(sone, false);
+ }
+
+ /**
+ * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
+ * {@code true}, an older Sone than the current Sone can be given to restore
+ * an old state.
+ *
+ * @param sone
+ * The Sone to update
+ * @param soneRescueMode
+ * {@code true} if the stored Sone should be updated regardless
+ * of the age of the given Sone
+ */
+ public void updateSone(final Sone sone, boolean soneRescueMode) {
+ Sone storedSone = getSone(sone.getId());
+ if (storedSone != null) {
+ if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
+ logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
+ return;
+ }
+ List