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 net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
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;
import java.util.logging.Level;
import java.util.logging.Logger;
+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.SoneInserter.SetInsertionDelay;
import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
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.Database;
+import net.pterodactylus.sone.database.DatabaseException;
import net.pterodactylus.sone.database.PostBuilder;
-import net.pterodactylus.sone.database.PostBuilderFactory;
import net.pterodactylus.sone.database.PostProvider;
import net.pterodactylus.sone.database.PostReplyBuilder;
-import net.pterodactylus.sone.database.PostReplyBuilderFactory;
import net.pterodactylus.sone.database.PostReplyProvider;
import net.pterodactylus.sone.database.SoneProvider;
-import net.pterodactylus.sone.data.TemporaryImage;
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;
import net.pterodactylus.util.service.AbstractService;
import net.pterodactylus.util.thread.NamedThreadFactory;
-import com.google.common.base.Predicate;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Optional;
import com.google.common.base.Predicates;
-import com.google.common.collect.Collections2;
+import com.google.common.collect.FluentIterable;
+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;
*
* @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
*/
+@Singleton
public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
/** The logger. */
private final EventBus eventBus;
/** The configuration. */
- private Configuration configuration;
+ private final Configuration configuration;
/** Whether we’re currently saving the configuration. */
private boolean storingConfiguration = false;
/** All known Sones. */
private final Set<String> knownSones = new HashSet<String>();
- /** The post builder. */
- private final PostBuilderFactory postBuilderFactory;
-
- /** All posts. */
- private final Map<String, Post> posts = new HashMap<String, Post>();
-
- /** All known posts. */
- private final Set<String> knownPosts = new HashSet<String>();
-
- /** The post reply builder factory. */
- private final PostReplyBuilderFactory postReplyBuilderFactory;
-
- /** All replies. */
- private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
-
- /** All known replies. */
- private final Set<String> knownReplies = new HashSet<String>();
+ /** The post database. */
+ private final Database database;
/** All bookmarked posts. */
/* synchronize access on itself. */
private final Set<String> bookmarkedPosts = new HashSet<String>();
/** Trusted identities, sorted by own identities. */
- private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
-
- /** All known albums. */
- private final Map<String, Album> albums = new HashMap<String, Album>();
-
- /** All known images. */
- private final Map<String, Image> images = new HashMap<String, Image>();
+ private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
/** All temporary images. */
private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
* 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;
}
//
}
/**
- * 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
}
/**
- * Returns all Sones, remote and local.
- *
- * @return All Sones
+ * {@inheritDocs}
*/
- public Set<Sone> getSones() {
- return new HashSet<Sone>(sones.values());
+ @Override
+ public Collection<Sone> getSones() {
+ synchronized (sones) {
+ return ImmutableSet.copyOf(sones.values());
+ }
}
/**
* Sone
*/
@Override
- public Sone getSone(String id) {
- synchronized (sones) {
- 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) {
+ public Optional<Sone> getSone(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<Sone> getLocalSones() {
synchronized (sones) {
- return Collections2.filter(sones.values(), new Predicate<Sone>() {
-
- @Override
- public boolean apply(Sone sone) {
- return sone.isLocal();
- }
- });
+ return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
}
}
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;
}
/**
- * Returns all remote Sones.
- *
- * @return All remote Sones
+ * {@inheritDocs}
*/
+ @Override
public Collection<Sone> getRemoteSones() {
synchronized (sones) {
- return Collections2.filter(sones.values(), new Predicate<Sone>() {
-
- @Override
- public boolean apply(Sone sone) {
- return !sone.isLocal();
- }
- });
+ return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
}
}
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;
* {@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();
}
/**
*/
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();
}
/**
* {@inheritDoc}
*/
@Override
- public Post getPost(String postId) {
- synchronized (posts) {
- return posts.get(postId);
- }
+ public Optional<Post> getPost(String postId) {
+ return database.getPost(postId);
+ }
+
+ /**
+ * {@inheritDocs}
+ */
+ @Override
+ public Collection<Post> getPosts(String soneId) {
+ return database.getPosts(soneId);
}
/**
@Override
public Collection<Post> getDirectedPosts(final String recipientId) {
checkNotNull(recipientId, "recipient must not be null");
- synchronized (posts) {
- return Collections2.filter(posts.values(), new Predicate<Post>() {
-
- @Override
- public boolean apply(Post post) {
- return (post.getRecipient() != null) && (post.getRecipient().getId().equals(recipientId));
- }
- });
- }
+ return database.getDirectedPosts(recipientId);
}
+
/**
* Returns a post reply builder.
*
* @return A new post reply builder
*/
public PostReplyBuilder postReplyBuilder() {
- return postReplyBuilderFactory.newPostReplyBuilder();
+ return database.newPostReplyBuilder();
}
/**
* {@inheritDoc}
*/
@Override
- public PostReply getPostReply(String replyId) {
- synchronized (replies) {
- return replies.get(replyId);
- }
+ public Optional<PostReply> getPostReply(String replyId) {
+ return database.getPostReply(replyId);
}
/**
* {@inheritDoc}
*/
@Override
- public List<PostReply> getReplies(Post post) {
- Set<Sone> sones = getSones();
- List<PostReply> replies = new ArrayList<PostReply>();
- for (Sone sone : sones) {
- for (PostReply reply : sone.getReplies()) {
- if (reply.getPost().equals(post)) {
- replies.add(reply);
- }
- }
- }
- Collections.sort(replies, Reply.TIME_COMPARATOR);
- return replies;
+ public List<PostReply> getReplies(final String postId) {
+ return database.getReplies(postId);
}
/**
Set<Post> posts = new HashSet<Post>();
synchronized (bookmarkedPosts) {
for (String bookmarkedPostId : bookmarkedPosts) {
- Post post = getPost(bookmarkedPostId);
- if (post != null) {
- posts.add(post);
+ Optional<Post> post = getPost(bookmarkedPostId);
+ if (post.isPresent()) {
+ posts.add(post.get());
}
}
}
* The ID of the album
* @return The album with the given ID
*/
- public Album getAlbum(String albumId) {
+ public Album getOrCreateAlbum(String albumId) {
return getAlbum(albumId, true);
}
* 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;
+ Optional<Album> album = database.getAlbum(albumId);
+ if (album.isPresent()) {
+ return album.get();
}
+ if (!create) {
+ return null;
+ }
+ Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
+ database.storeAlbum(newAlbum);
+ return newAlbum;
}
/**
* 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> 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;
}
/**
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 {
return null;
}
Sone sone = addLocalSone(ownIdentity);
- sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
- sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
- sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
- sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
touchConfiguration();
return null;
}
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));
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;
}
}
if (!soneFollowingTimes.containsKey(soneId)) {
long now = System.currentTimeMillis();
soneFollowingTimes.put(soneId, now);
- Sone followedSone = getSone(soneId);
- if (followedSone == null) {
+ Optional<Sone> 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);
}
* 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())) {
+ Optional<Sone> 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. */
+ Collection<Post> removedPosts = new ArrayList<Post>();
+ Collection<Post> newPosts = new ArrayList<Post>();
+ Collection<Post> existingPosts = database.getPosts(sone.getId());
+ for (Post oldPost : existingPosts) {
+ if (!sone.getPosts().contains(oldPost)) {
+ removedPosts.add(oldPost);
}
- List<Post> storedPosts = storedSone.getPosts();
- synchronized (knownPosts) {
- for (Post post : sone.getPosts()) {
- PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
- postBuilder.copyPost(post).from(storedSone.getId());
- Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
- if (!storedPosts.contains(newPost)) {
- if (newPost.getTime() < getSoneFollowingTime(sone)) {
- knownPosts.add(newPost.getId());
- newPost.setKnown(true);
- } else if (!knownPosts.contains(newPost.getId())) {
- eventBus.post(new NewPostFoundEvent(newPost));
- }
- }
- posts.put(newPost.getId(), newPost);
- }
+ }
+ /* find new posts. */
+ for (Post newPost : sone.getPosts()) {
+ if (existingPosts.contains(newPost)) {
+ continue;
+ }
+ if (newPost.getTime() < getSoneFollowingTime(sone)) {
+ newPost.setKnown(true);
+ } else if (!newPost.isKnown()) {
+ newPosts.add(newPost);
}
}
- synchronized (replies) {
- if (!soneRescueMode) {
- for (PostReply reply : storedSone.getReplies()) {
- replies.remove(reply.getId());
- if (!sone.getReplies().contains(reply)) {
- eventBus.post(new PostReplyRemovedEvent(reply));
- }
+ /* store posts. */
+ database.storePosts(sone, sone.getPosts());
+ Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
+ Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
+ if (!soneRescueMode) {
+ for (PostReply reply : storedSone.get().getReplies()) {
+ if (!sone.getReplies().contains(reply)) {
+ removedPostReplies.add(reply);
}
}
- Set<PostReply> 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);
- }
+ }
+ Set<PostReply> storedReplies = storedSone.get().getReplies();
+ for (PostReply reply : sone.getReplies()) {
+ if (storedReplies.contains(reply)) {
+ continue;
+ }
+ if (reply.getTime() < getSoneFollowingTime(sone)) {
+ reply.setKnown(true);
+ } else if (!reply.isKnown()) {
+ newPostReplies.add(reply);
}
}
- 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);
- }
- }
+ database.storePostReplies(sone, sone.getReplies());
+ for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
+ database.removeAlbum(album);
+ for (Image image : album.getImages()) {
+ database.removeImage(image);
}
}
- synchronized (storedSone) {
- if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
- storedSone.setTime(sone.getTime());
+ for (Post removedPost : removedPosts) {
+ eventBus.post(new PostRemovedEvent(removedPost));
+ }
+ for (Post newPost : newPosts) {
+ eventBus.post(new NewPostFoundEvent(newPost));
+ }
+ for (PostReply removedPostReply : removedPostReplies) {
+ eventBus.post(new PostReplyRemovedEvent(removedPostReply));
+ }
+ for (PostReply newPostReply : newPostReplies) {
+ eventBus.post(new NewPostReplyFoundEvent(newPostReply));
+ }
+ for (Album album : sone.getRootAlbum().getAlbums()) {
+ database.storeAlbum(album);
+ for (Image image : album.getImages()) {
+ database.storeImage(image);
}
- storedSone.setClient(sone.getClient());
- storedSone.setProfile(sone.getProfile());
- if (soneRescueMode) {
- for (Post post : sone.getPosts()) {
- storedSone.addPost(post);
- }
- for (PostReply reply : sone.getReplies()) {
- storedSone.addReply(reply);
- }
- for (String likedPostId : sone.getLikedPostIds()) {
- storedSone.addLikedPostId(likedPostId);
- }
- for (String likedReplyId : sone.getLikedReplyIds()) {
- storedSone.addLikedReplyId(likedReplyId);
- }
- for (Album album : sone.getAlbums()) {
- storedSone.addAlbum(album);
- }
- } else {
- storedSone.setPosts(sone.getPosts());
- storedSone.setReplies(sone.getReplies());
- storedSone.setLikePostIds(sone.getLikedPostIds());
- storedSone.setLikeReplyIds(sone.getLikedReplyIds());
- storedSone.setAlbums(sone.getAlbums());
+ }
+ 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();
}
- storedSone.setLatestEdition(sone.getLatestEdition());
+ sones.put(sone.getId(), sone);
}
}
}
logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
return;
}
-
- /* initialize options. */
- sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
- sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
- sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
- sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
- sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
+ logger.info(String.format("Loading local Sone: %s", sone));
/* load Sone. */
String sonePrefix = "Sone/" + sone.getId();
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<Post> posts = new HashSet<Post>();
- 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 = postBuilderFactory.newPostBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
- if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
- postBuilder.to(postRecipientId);
- }
- posts.add(postBuilder.build());
+ Collection<Post> posts;
+ try {
+ posts = configurationSoneParser.parsePosts(database);
+ } catch (InvalidPostFound ipf) {
+ logger.log(Level.WARNING, "Invalid post found, aborting load!");
+ return;
}
/* load replies. */
- Set<PostReply> replies = new HashSet<PostReply>();
- 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<PostReply> replies;
+ try {
+ replies = configurationSoneParser.parsePostReplies(database);
+ } catch (InvalidPostReplyFound iprf) {
+ logger.log(Level.WARNING, "Invalid reply found, aborting load!");
+ return;
}
/* load post likes. */
- Set<String> likedPostIds = new HashSet<String>();
- while (true) {
- String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
- if (likedPostId == null) {
- break;
- }
- likedPostIds.add(likedPostId);
- }
+ Set<String> likedPostIds =
+ configurationSoneParser.parseLikedPostIds();
/* load reply likes. */
- Set<String> likedReplyIds = new HashSet<String>();
- while (true) {
- String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
- if (likedReplyId == null) {
- break;
- }
- likedReplyIds.add(likedReplyId);
- }
+ Set<String> likedReplyIds =
+ configurationSoneParser.parseLikedPostReplyIds();
/* load friends. */
Set<String> friends = new HashSet<String>();
logger.log(Level.WARNING, "Invalid album found, aborting load!");
return;
}
- Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
+ Album album = getOrCreateAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
if (albumParentId != null) {
Album parentAlbum = getAlbum(albumParentId, false);
if (parentAlbum == 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);
+ Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
album.addImage(image);
}
}
/* 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().<ShowCustomAvatars> 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) {
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);
}
synchronized (knownSones) {
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));
}
/**
* The text of the post
* @return The created post
*/
- public Post createPost(Sone sone, Sone recipient, String text) {
+ public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
return createPost(sone, recipient, System.currentTimeMillis(), text);
}
* 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<Sone> recipient, long time, String text) {
checkNotNull(text, "text must not be null");
checkArgument(text.trim().length() > 0, "text must not be empty");
if (!sone.isLocal()) {
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;
}
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();
*/
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
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;
}
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();
}
* 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
* @return The new album
*/
public Album createAlbum(Sone sone, Album parent) {
- Album album = new Album();
- synchronized (albums) {
- albums.put(album.getId(), album);
- }
+ Album album = database.newAlbumBuilder().randomId().build();
+ database.storeAlbum(album);
album.setSone(sone);
- if (parent != null) {
- parent.addAlbum(album);
- } else {
- sone.addAlbum(album);
- }
+ parent.addAlbum(album);
return album;
}
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();
}
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;
}
* 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
*/
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();
}
}
/**
- * 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
identityManager.start();
webOfTrustUpdater.init();
webOfTrustUpdater.start();
+ database.start();
}
/**
synchronized (sones) {
for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
soneInserter.getValue().stop();
- saveSone(soneInserter.getKey());
+ saveSone(getLocalSone(soneInserter.getKey().getId(), false));
}
}
saveConfiguration();
+ database.stop();
webOfTrustUpdater.stop();
updateChecker.stop();
soneDownloader.stop();
+ soneDownloaders.shutdown();
identityManager.stop();
}
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());
}
for (PostReply reply : sone.getReplies()) {
String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
- configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
+ configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
}
configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
/* save albums. first, collect in a flat structure, top-level first. */
- List<Album> albums = sone.getAllAlbums();
+ List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
int albumCounter = 0;
for (Album album : albums) {
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);
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().<ShowCustomAvatars> 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();
}
/* 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;
} 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;
/**
* Loads the configuration.
*/
- @SuppressWarnings("unchecked")
private void loadConfiguration() {
/* create options. */
- options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
-
- @Override
- public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
- SoneInserter.setInsertionDelay(newValue);
- }
-
- }));
+ options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
- options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
- fcpInterface.setActive(newValue);
- }
- }));
- options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
- fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
- }
-
- }));
+ options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
+ options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
loadConfigurationValue("InsertionDelay");
loadConfigurationValue("PostsPerPage");
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) {
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<Identity>()));
addLocalSone(ownIdentity);
}
}
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);
}
/**
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);
}
*/
@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));
}
/**
public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
Identity identity = identityRemovedEvent.identity();
- trustedIdentities.get(ownIdentity).remove(identity);
+ trustedIdentities.remove(ownIdentity, identity);
boolean foundIdentity = false;
- for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
+ for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
if (trustedIdentity.getKey().equals(ownIdentity)) {
continue;
}
/* some local identity still trusts this identity, don’t remove. */
return;
}
- Sone sone = getSone(identity.getId());
- if (sone == null) {
+ Optional<Sone> 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()));
}
/**
@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);
+ }
+
+ }
+
}