2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.primitives.Longs.tryParse;
25 import static java.lang.String.format;
26 import static java.util.logging.Level.WARNING;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
30 import java.net.MalformedURLException;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
41 import java.util.concurrent.ScheduledExecutorService;
42 import java.util.concurrent.TimeUnit;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
51 import net.pterodactylus.sone.core.Options.DefaultOption;
52 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
53 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
54 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
55 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
56 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
57 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
58 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
59 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
60 import net.pterodactylus.sone.core.event.PostRemovedEvent;
61 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneLockedEvent;
63 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
64 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
65 import net.pterodactylus.sone.data.Album;
66 import net.pterodactylus.sone.data.Client;
67 import net.pterodactylus.sone.data.Image;
68 import net.pterodactylus.sone.data.Post;
69 import net.pterodactylus.sone.data.PostReply;
70 import net.pterodactylus.sone.data.Profile;
71 import net.pterodactylus.sone.data.Profile.Field;
72 import net.pterodactylus.sone.data.Reply;
73 import net.pterodactylus.sone.data.Sone;
74 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
75 import net.pterodactylus.sone.data.Sone.SoneStatus;
76 import net.pterodactylus.sone.data.SoneImpl;
77 import net.pterodactylus.sone.data.TemporaryImage;
78 import net.pterodactylus.sone.database.AlbumBuilder;
79 import net.pterodactylus.sone.database.Database;
80 import net.pterodactylus.sone.database.DatabaseException;
81 import net.pterodactylus.sone.database.PostBuilder;
82 import net.pterodactylus.sone.database.PostProvider;
83 import net.pterodactylus.sone.database.PostReplyBuilder;
84 import net.pterodactylus.sone.database.PostReplyProvider;
85 import net.pterodactylus.sone.database.SoneProvider;
86 import net.pterodactylus.sone.fcp.FcpInterface;
87 import net.pterodactylus.sone.freenet.wot.Identity;
88 import net.pterodactylus.sone.freenet.wot.IdentityManager;
89 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
95 import net.pterodactylus.sone.main.SonePlugin;
96 import net.pterodactylus.sone.utils.IntegerRangePredicate;
97 import net.pterodactylus.util.config.Configuration;
98 import net.pterodactylus.util.config.ConfigurationException;
99 import net.pterodactylus.util.logging.Logging;
100 import net.pterodactylus.util.number.Numbers;
101 import net.pterodactylus.util.service.AbstractService;
102 import net.pterodactylus.util.thread.NamedThreadFactory;
104 import com.google.common.annotations.VisibleForTesting;
105 import com.google.common.base.Optional;
106 import com.google.common.base.Predicates;
107 import com.google.common.collect.FluentIterable;
108 import com.google.common.collect.HashMultimap;
109 import com.google.common.collect.ImmutableSet;
110 import com.google.common.collect.Multimap;
111 import com.google.common.collect.Multimaps;
112 import com.google.common.eventbus.EventBus;
113 import com.google.common.eventbus.Subscribe;
114 import com.google.inject.Inject;
115 import com.google.inject.Singleton;
117 import freenet.keys.FreenetURI;
122 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
125 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
128 private static final Logger logger = Logging.getLogger(Core.class);
130 /** The start time. */
131 private final long startupTime = System.currentTimeMillis();
134 private final Options options = new Options();
136 /** The preferences. */
137 private final Preferences preferences = new Preferences(options);
139 /** The event bus. */
140 private final EventBus eventBus;
142 /** The configuration. */
143 private final Configuration configuration;
145 /** Whether we’re currently saving the configuration. */
146 private boolean storingConfiguration = false;
148 /** The identity manager. */
149 private final IdentityManager identityManager;
151 /** Interface to freenet. */
152 private final FreenetInterface freenetInterface;
154 /** The Sone downloader. */
155 private final SoneDownloader soneDownloader;
157 /** The image inserter. */
158 private final ImageInserter imageInserter;
160 /** Sone downloader thread-pool. */
161 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
163 /** The update checker. */
164 private final UpdateChecker updateChecker;
166 /** The trust updater. */
167 private final WebOfTrustUpdater webOfTrustUpdater;
169 /** The FCP interface. */
170 private volatile FcpInterface fcpInterface;
172 /** The times Sones were followed. */
173 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
175 /** Locked local Sones. */
176 /* synchronize on itself. */
177 private final Set<Sone> lockedSones = new HashSet<Sone>();
179 /** Sone inserters. */
180 /* synchronize access on this on sones. */
181 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
183 /** Sone rescuers. */
184 /* synchronize access on this on sones. */
185 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
188 /* synchronize access on this on itself. */
189 private final Map<String, Sone> sones = new HashMap<String, Sone>();
191 /** All known Sones. */
192 private final Set<String> knownSones = new HashSet<String>();
194 /** The post database. */
195 private final Database database;
197 /** All bookmarked posts. */
198 /* synchronize access on itself. */
199 private final Set<String> bookmarkedPosts = new HashSet<String>();
201 /** Trusted identities, sorted by own identities. */
202 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
204 /** All temporary images. */
205 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
207 /** Ticker for threads that mark own elements as known. */
208 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
210 /** The time the configuration was last touched. */
211 private volatile long lastConfigurationUpdate;
214 * Creates a new core.
216 * @param configuration
217 * The configuration of the core
218 * @param freenetInterface
219 * The freenet interface
220 * @param identityManager
221 * The identity manager
222 * @param webOfTrustUpdater
223 * The WebOfTrust updater
230 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
232 this.configuration = configuration;
233 this.freenetInterface = freenetInterface;
234 this.identityManager = identityManager;
235 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
236 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
237 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
238 this.webOfTrustUpdater = webOfTrustUpdater;
239 this.eventBus = eventBus;
240 this.database = database;
244 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
246 this.configuration = configuration;
247 this.freenetInterface = freenetInterface;
248 this.identityManager = identityManager;
249 this.soneDownloader = soneDownloader;
250 this.imageInserter = imageInserter;
251 this.updateChecker = updateChecker;
252 this.webOfTrustUpdater = webOfTrustUpdater;
253 this.eventBus = eventBus;
254 this.database = database;
262 * Returns the time Sone was started.
264 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
266 public long getStartupTime() {
271 * Returns the options used by the core.
273 * @return The options of the core
275 public Preferences getPreferences() {
280 * Returns the identity manager used by the core.
282 * @return The identity manager
284 public IdentityManager getIdentityManager() {
285 return identityManager;
289 * Returns the update checker.
291 * @return The update checker
293 public UpdateChecker getUpdateChecker() {
294 return updateChecker;
298 * Sets the FCP interface to use.
300 * @param fcpInterface
301 * The FCP interface to use
303 public void setFcpInterface(FcpInterface fcpInterface) {
304 this.fcpInterface = fcpInterface;
308 * Returns the Sone rescuer for the given local Sone.
311 * The local Sone to get the rescuer for
312 * @return The Sone rescuer for the given Sone
314 public SoneRescuer getSoneRescuer(Sone sone) {
315 checkNotNull(sone, "sone must not be null");
316 checkArgument(sone.isLocal(), "sone must be local");
317 synchronized (sones) {
318 SoneRescuer soneRescuer = soneRescuers.get(sone);
319 if (soneRescuer == null) {
320 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
321 soneRescuers.put(sone, soneRescuer);
329 * Returns whether the given Sone is currently locked.
333 * @return {@code true} if the Sone is locked, {@code false} if it is not
335 public boolean isLocked(Sone sone) {
336 synchronized (lockedSones) {
337 return lockedSones.contains(sone);
345 public Collection<Sone> getSones() {
346 synchronized (sones) {
347 return ImmutableSet.copyOf(sones.values());
352 * Returns the Sone with the given ID, regardless whether it’s local or
356 * The ID of the Sone to get
357 * @return The Sone with the given ID, or {@code null} if there is no such
361 public Optional<Sone> getSone(String id) {
362 synchronized (sones) {
363 return Optional.fromNullable(sones.get(id));
371 public Collection<Sone> getLocalSones() {
372 synchronized (sones) {
373 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
378 * Returns the local Sone with the given ID, optionally creating a new Sone.
383 * {@code true} to create a new Sone if none exists,
384 * {@code false} to return null if none exists
385 * @return The Sone with the given ID, or {@code null}
387 public Sone getLocalSone(String id, boolean create) {
388 synchronized (sones) {
389 Sone sone = sones.get(id);
390 if ((sone == null) && create) {
391 sone = new SoneImpl(id, true);
394 if ((sone != null) && !sone.isLocal()) {
395 sone = new SoneImpl(id, true);
406 public Collection<Sone> getRemoteSones() {
407 synchronized (sones) {
408 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
413 * Returns the remote Sone with the given ID.
416 * The ID of the remote Sone to get
418 * {@code true} to always create a Sone, {@code false} to return
419 * {@code null} if no Sone with the given ID exists
420 * @return The Sone with the given ID
422 public Sone getRemoteSone(String id, boolean create) {
423 synchronized (sones) {
424 Sone sone = sones.get(id);
425 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
426 sone = new SoneImpl(id, false);
434 * Returns whether the given Sone has been modified.
437 * The Sone to check for modifications
438 * @return {@code true} if a modification has been detected in the Sone,
439 * {@code false} otherwise
441 public boolean isModifiedSone(Sone sone) {
442 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
446 * Returns the time when the given was first followed by any local Sone.
449 * The Sone to get the time for
450 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
451 * been followed, or {@link Long#MAX_VALUE}
453 public long getSoneFollowingTime(Sone sone) {
454 synchronized (soneFollowingTimes) {
455 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
460 * Returns a post builder.
462 * @return A new post builder
464 public PostBuilder postBuilder() {
465 return database.newPostBuilder();
472 public Optional<Post> getPost(String postId) {
473 return database.getPost(postId);
480 public Collection<Post> getPosts(String soneId) {
481 return database.getPosts(soneId);
488 public Collection<Post> getDirectedPosts(final String recipientId) {
489 checkNotNull(recipientId, "recipient must not be null");
490 return database.getDirectedPosts(recipientId);
494 * Returns a post reply builder.
496 * @return A new post reply builder
498 public PostReplyBuilder postReplyBuilder() {
499 return database.newPostReplyBuilder();
506 public Optional<PostReply> getPostReply(String replyId) {
507 return database.getPostReply(replyId);
514 public List<PostReply> getReplies(final String postId) {
515 return database.getReplies(postId);
519 * Returns all Sones that have liked the given post.
522 * The post to get the liking Sones for
523 * @return The Sones that like the given post
525 public Set<Sone> getLikes(Post post) {
526 Set<Sone> sones = new HashSet<Sone>();
527 for (Sone sone : getSones()) {
528 if (sone.getLikedPostIds().contains(post.getId())) {
536 * Returns all Sones that have liked the given reply.
539 * The reply to get the liking Sones for
540 * @return The Sones that like the given reply
542 public Set<Sone> getLikes(PostReply reply) {
543 Set<Sone> sones = new HashSet<Sone>();
544 for (Sone sone : getSones()) {
545 if (sone.getLikedReplyIds().contains(reply.getId())) {
553 * Returns whether the given post is bookmarked.
557 * @return {@code true} if the given post is bookmarked, {@code false}
560 public boolean isBookmarked(Post post) {
561 return isPostBookmarked(post.getId());
565 * Returns whether the post with the given ID is bookmarked.
568 * The ID of the post to check
569 * @return {@code true} if the post with the given ID is bookmarked,
570 * {@code false} otherwise
572 public boolean isPostBookmarked(String id) {
573 synchronized (bookmarkedPosts) {
574 return bookmarkedPosts.contains(id);
579 * Returns all currently known bookmarked posts.
581 * @return All bookmarked posts
583 public Set<Post> getBookmarkedPosts() {
584 Set<Post> posts = new HashSet<Post>();
585 synchronized (bookmarkedPosts) {
586 for (String bookmarkedPostId : bookmarkedPosts) {
587 Optional<Post> post = getPost(bookmarkedPostId);
588 if (post.isPresent()) {
589 posts.add(post.get());
596 public AlbumBuilder albumBuilder() {
597 return database.newAlbumBuilder();
601 * Returns the album with the given ID, optionally creating a new album if
602 * an album with the given ID can not be found.
605 * The ID of the album
606 * @return The album with the given ID, or {@code null} if no album with the
609 public Album getAlbum(String albumId) {
610 return database.getAlbum(albumId).orNull();
614 * Returns the image with the given ID, creating it if necessary.
617 * The ID of the image
618 * @return The image with the given ID
620 public Image getImage(String imageId) {
621 return getImage(imageId, true);
625 * Returns the image with the given ID, optionally creating it if it does
629 * The ID of the image
631 * {@code true} to create an image if none exists with the given
633 * @return The image with the given ID, or {@code null} if none exists and
636 public Image getImage(String imageId, boolean create) {
637 Optional<Image> image = database.getImage(imageId);
638 if (image.isPresent()) {
644 Image newImage = database.newImageBuilder().withId(imageId).build();
645 database.storeImage(newImage);
650 * Returns the temporary image with the given ID.
653 * The ID of the temporary image
654 * @return The temporary image, or {@code null} if there is no temporary
655 * image with the given ID
657 public TemporaryImage getTemporaryImage(String imageId) {
658 synchronized (temporaryImages) {
659 return temporaryImages.get(imageId);
668 * Locks the given Sone. A locked Sone will not be inserted by
669 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
675 public void lockSone(Sone sone) {
676 synchronized (lockedSones) {
677 if (lockedSones.add(sone)) {
678 eventBus.post(new SoneLockedEvent(sone));
684 * Unlocks the given Sone.
686 * @see #lockSone(Sone)
690 public void unlockSone(Sone sone) {
691 synchronized (lockedSones) {
692 if (lockedSones.remove(sone)) {
693 eventBus.post(new SoneUnlockedEvent(sone));
699 * Adds a local Sone from the given own identity.
702 * The own identity to create a Sone from
703 * @return The added (or already existing) Sone
705 public Sone addLocalSone(OwnIdentity ownIdentity) {
706 if (ownIdentity == null) {
707 logger.log(Level.WARNING, "Given OwnIdentity is null!");
710 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
711 synchronized (sones) {
714 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
715 } catch (MalformedURLException mue1) {
716 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
719 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
720 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
722 /* TODO - load posts ’n stuff */
723 sones.put(ownIdentity.getId(), sone);
724 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
725 soneInserters.put(sone, soneInserter);
726 sone.setStatus(SoneStatus.idle);
728 soneInserter.start();
734 * Creates a new Sone for the given own identity.
737 * The own identity to create a Sone for
738 * @return The created Sone
740 public Sone createSone(OwnIdentity ownIdentity) {
741 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
742 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
745 Sone sone = addLocalSone(ownIdentity);
747 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
748 touchConfiguration();
753 * Adds the Sone of the given identity.
756 * The identity whose Sone to add
757 * @return The added or already existing Sone
759 public Sone addRemoteSone(Identity identity) {
760 if (identity == null) {
761 logger.log(Level.WARNING, "Given Identity is null!");
764 final Long latestEdition = fromNullable(tryParse(
765 identity.getProperty("Sone.LatestEdition"))).or(0L);
766 synchronized (sones) {
767 final Sone sone = getRemoteSone(identity.getId(), true);
768 if (sone.isLocal()) {
771 sone.setIdentity(identity);
772 boolean newSone = sone.getRequestUri() == null;
773 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
774 sone.setLatestEdition(latestEdition);
776 synchronized (knownSones) {
777 newSone = !knownSones.contains(sone.getId());
779 sone.setKnown(!newSone);
781 eventBus.post(new NewSoneFoundEvent(sone));
782 for (Sone localSone : getLocalSones()) {
783 if (localSone.getOptions().isAutoFollow()) {
784 followSone(localSone, sone.getId());
789 soneDownloader.addSone(sone);
790 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
796 * Lets the given local Sone follow the Sone with the given ID.
799 * The local Sone that should follow another Sone
801 * The ID of the Sone to follow
803 public void followSone(Sone sone, String soneId) {
804 checkNotNull(sone, "sone must not be null");
805 checkNotNull(soneId, "soneId must not be null");
806 sone.addFriend(soneId);
807 synchronized (soneFollowingTimes) {
808 if (!soneFollowingTimes.containsKey(soneId)) {
809 long now = System.currentTimeMillis();
810 soneFollowingTimes.put(soneId, now);
811 Optional<Sone> followedSone = getSone(soneId);
812 if (!followedSone.isPresent()) {
815 for (Post post : followedSone.get().getPosts()) {
816 if (post.getTime() < now) {
820 for (PostReply reply : followedSone.get().getReplies()) {
821 if (reply.getTime() < now) {
822 markReplyKnown(reply);
827 touchConfiguration();
831 * Lets the given local Sone unfollow the Sone with the given ID.
834 * The local Sone that should unfollow another Sone
836 * The ID of the Sone being unfollowed
838 public void unfollowSone(Sone sone, String soneId) {
839 checkNotNull(sone, "sone must not be null");
840 checkNotNull(soneId, "soneId must not be null");
841 sone.removeFriend(soneId);
842 boolean unfollowedSoneStillFollowed = false;
843 for (Sone localSone : getLocalSones()) {
844 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
846 if (!unfollowedSoneStillFollowed) {
847 synchronized (soneFollowingTimes) {
848 soneFollowingTimes.remove(soneId);
851 touchConfiguration();
855 * Sets the trust value of the given origin Sone for the target Sone.
862 * The trust value (from {@code -100} to {@code 100})
864 public void setTrust(Sone origin, Sone target, int trustValue) {
865 checkNotNull(origin, "origin must not be null");
866 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
867 checkNotNull(target, "target must not be null");
868 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
869 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
873 * Removes any trust assignment for the given target Sone.
880 public void removeTrust(Sone origin, Sone target) {
881 checkNotNull(origin, "origin must not be null");
882 checkNotNull(target, "target must not be null");
883 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
884 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
888 * Assigns the configured positive trust value for the given target.
895 public void trustSone(Sone origin, Sone target) {
896 setTrust(origin, target, preferences.getPositiveTrust());
900 * Assigns the configured negative trust value for the given target.
907 public void distrustSone(Sone origin, Sone target) {
908 setTrust(origin, target, preferences.getNegativeTrust());
912 * Removes the trust assignment for the given target.
919 public void untrustSone(Sone origin, Sone target) {
920 removeTrust(origin, target);
924 * Updates the stored Sone with the given Sone.
929 public void updateSone(Sone sone) {
930 updateSone(sone, false);
934 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
935 * {@code true}, an older Sone than the current Sone can be given to restore
940 * @param soneRescueMode
941 * {@code true} if the stored Sone should be updated regardless
942 * of the age of the given Sone
944 public void updateSone(Sone sone, boolean soneRescueMode) {
945 Optional<Sone> storedSone = getSone(sone.getId());
946 if (storedSone.isPresent()) {
947 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
948 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
951 /* find removed posts. */
952 Collection<Post> removedPosts = new ArrayList<Post>();
953 Collection<Post> newPosts = new ArrayList<Post>();
954 Collection<Post> existingPosts = database.getPosts(sone.getId());
955 for (Post oldPost : existingPosts) {
956 if (!sone.getPosts().contains(oldPost)) {
957 removedPosts.add(oldPost);
960 /* find new posts. */
961 for (Post newPost : sone.getPosts()) {
962 if (existingPosts.contains(newPost)) {
965 if (newPost.getTime() < getSoneFollowingTime(sone)) {
966 newPost.setKnown(true);
967 } else if (!newPost.isKnown()) {
968 newPosts.add(newPost);
972 database.storePosts(sone, sone.getPosts());
973 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
974 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
975 if (!soneRescueMode) {
976 for (PostReply reply : storedSone.get().getReplies()) {
977 if (!sone.getReplies().contains(reply)) {
978 removedPostReplies.add(reply);
982 Set<PostReply> storedReplies = storedSone.get().getReplies();
983 for (PostReply reply : sone.getReplies()) {
984 if (storedReplies.contains(reply)) {
987 if (reply.getTime() < getSoneFollowingTime(sone)) {
988 reply.setKnown(true);
989 } else if (!reply.isKnown()) {
990 newPostReplies.add(reply);
993 database.storePostReplies(sone, sone.getReplies());
994 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
995 database.removeAlbum(album);
996 for (Image image : album.getImages()) {
997 database.removeImage(image);
1000 for (Post removedPost : removedPosts) {
1001 eventBus.post(new PostRemovedEvent(removedPost));
1003 for (Post newPost : newPosts) {
1004 eventBus.post(new NewPostFoundEvent(newPost));
1006 for (PostReply removedPostReply : removedPostReplies) {
1007 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1009 for (PostReply newPostReply : newPostReplies) {
1010 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1012 for (Album album : sone.getRootAlbum().getAlbums()) {
1013 database.storeAlbum(album);
1014 for (Image image : album.getImages()) {
1015 database.storeImage(image);
1018 synchronized (sones) {
1019 sone.setOptions(storedSone.get().getOptions());
1020 sone.setKnown(storedSone.get().isKnown());
1021 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1022 if (sone.isLocal()) {
1023 soneInserters.get(storedSone.get()).setSone(sone);
1024 touchConfiguration();
1026 sones.put(sone.getId(), sone);
1032 * Deletes the given Sone. This will remove the Sone from the
1033 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1034 * remove the context from its identity.
1037 * The Sone to delete
1039 public void deleteSone(Sone sone) {
1040 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1041 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1044 synchronized (sones) {
1045 if (!getLocalSones().contains(sone)) {
1046 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1049 sones.remove(sone.getId());
1050 SoneInserter soneInserter = soneInserters.remove(sone);
1051 soneInserter.stop();
1053 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1054 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1056 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1057 } catch (ConfigurationException ce1) {
1058 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1063 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1064 * known} before, a {@link MarkSoneKnownEvent} is fired.
1067 * The Sone to mark as known
1069 public void markSoneKnown(Sone sone) {
1070 if (!sone.isKnown()) {
1071 sone.setKnown(true);
1072 synchronized (knownSones) {
1073 knownSones.add(sone.getId());
1075 eventBus.post(new MarkSoneKnownEvent(sone));
1076 touchConfiguration();
1081 * Loads and updates the given Sone from the configuration. If any error is
1082 * encountered, loading is aborted and the given Sone is not changed.
1085 * The Sone to load and update
1087 public void loadSone(Sone sone) {
1088 if (!sone.isLocal()) {
1089 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1092 logger.info(String.format("Loading local Sone: %s", sone));
1095 String sonePrefix = "Sone/" + sone.getId();
1096 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1097 if (soneTime == null) {
1098 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1101 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1104 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1105 Profile profile = configurationSoneParser.parseProfile();
1108 Collection<Post> posts;
1110 posts = configurationSoneParser.parsePosts(database);
1111 } catch (InvalidPostFound ipf) {
1112 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1117 Collection<PostReply> replies;
1119 replies = configurationSoneParser.parsePostReplies(database);
1120 } catch (InvalidPostReplyFound iprf) {
1121 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1125 /* load post likes. */
1126 Set<String> likedPostIds =
1127 configurationSoneParser.parseLikedPostIds();
1129 /* load reply likes. */
1130 Set<String> likedReplyIds =
1131 configurationSoneParser.parseLikedPostReplyIds();
1134 Set<String> friends = configurationSoneParser.parseFriends();
1137 List<Album> topLevelAlbums;
1140 configurationSoneParser.parseTopLevelAlbums(database);
1141 } catch (InvalidAlbumFound iaf) {
1142 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1144 } catch (InvalidParentAlbumFound ipaf) {
1145 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1146 ipaf.getAlbumParentId()));
1152 configurationSoneParser.parseImages(database);
1153 } catch (InvalidImageFound iif) {
1154 logger.log(WARNING, "Invalid image found, aborting load!");
1156 } catch (InvalidParentAlbumFound ipaf) {
1157 logger.log(Level.WARNING,
1158 format("Invalid album image (%s) encountered, aborting load!",
1159 ipaf.getAlbumParentId()));
1164 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1165 if (avatarId != null) {
1166 final Map<String, Image> images =
1167 configurationSoneParser.getImages();
1168 profile.setAvatar(images.get(avatarId));
1172 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1173 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1174 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1175 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1176 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1177 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1179 /* if we’re still here, Sone was loaded successfully. */
1180 synchronized (sone) {
1181 sone.setTime(soneTime);
1182 sone.setProfile(profile);
1183 sone.setPosts(posts);
1184 sone.setReplies(replies);
1185 sone.setLikePostIds(likedPostIds);
1186 sone.setLikeReplyIds(likedReplyIds);
1187 for (String friendId : friends) {
1188 followSone(sone, friendId);
1190 for (Album album : sone.getRootAlbum().getAlbums()) {
1191 sone.getRootAlbum().removeAlbum(album);
1193 for (Album album : topLevelAlbums) {
1194 sone.getRootAlbum().addAlbum(album);
1196 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1197 for (Album album : toAllAlbums.apply(sone)) {
1198 database.storeAlbum(album);
1199 for (Image image : album.getImages()) {
1200 database.storeImage(image);
1204 synchronized (knownSones) {
1205 for (String friend : friends) {
1206 knownSones.add(friend);
1209 database.storePosts(sone, posts);
1210 for (Post post : posts) {
1211 post.setKnown(true);
1213 database.storePostReplies(sone, replies);
1214 for (PostReply reply : replies) {
1215 reply.setKnown(true);
1218 logger.info(String.format("Sone loaded successfully: %s", sone));
1222 * Creates a new post.
1225 * The Sone that creates the post
1227 * The recipient Sone, or {@code null} if this post does not have
1230 * The text of the post
1231 * @return The created post
1233 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1234 return createPost(sone, recipient, System.currentTimeMillis(), text);
1238 * Creates a new post.
1241 * The Sone that creates the post
1243 * The recipient Sone, or {@code null} if this post does not have
1246 * The time of the post
1248 * The text of the post
1249 * @return The created post
1251 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1252 checkNotNull(text, "text must not be null");
1253 checkArgument(text.trim().length() > 0, "text must not be empty");
1254 if (!sone.isLocal()) {
1255 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1258 PostBuilder postBuilder = database.newPostBuilder();
1259 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1260 if (recipient.isPresent()) {
1261 postBuilder.to(recipient.get().getId());
1263 final Post post = postBuilder.build();
1264 database.storePost(post);
1265 eventBus.post(new NewPostFoundEvent(post));
1267 touchConfiguration();
1268 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1273 * Deletes the given post.
1276 * The post to delete
1278 public void deletePost(Post post) {
1279 if (!post.getSone().isLocal()) {
1280 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1283 database.removePost(post);
1284 eventBus.post(new PostRemovedEvent(post));
1285 markPostKnown(post);
1286 touchConfiguration();
1290 * Marks the given post as known, if it is currently not a known post
1291 * (according to {@link Post#isKnown()}).
1294 * The post to mark as known
1296 public void markPostKnown(Post post) {
1297 post.setKnown(true);
1298 eventBus.post(new MarkPostKnownEvent(post));
1299 touchConfiguration();
1300 for (PostReply reply : getReplies(post.getId())) {
1301 markReplyKnown(reply);
1306 * Bookmarks the post with the given ID.
1309 * The ID of the post to bookmark
1311 public void bookmarkPost(String id) {
1312 synchronized (bookmarkedPosts) {
1313 bookmarkedPosts.add(id);
1318 * Removes the given post from the bookmarks.
1321 * The post to unbookmark
1323 public void unbookmark(Post post) {
1324 unbookmarkPost(post.getId());
1328 * Removes the post with the given ID from the bookmarks.
1331 * The ID of the post to unbookmark
1333 public void unbookmarkPost(String id) {
1334 synchronized (bookmarkedPosts) {
1335 bookmarkedPosts.remove(id);
1340 * Creates a new reply.
1343 * The Sone that creates the reply
1345 * The post that this reply refers to
1347 * The text of the reply
1348 * @return The created reply
1350 public PostReply createReply(Sone sone, Post post, String text) {
1351 checkNotNull(text, "text must not be null");
1352 checkArgument(text.trim().length() > 0, "text must not be empty");
1353 if (!sone.isLocal()) {
1354 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1357 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1358 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1359 final PostReply reply = postReplyBuilder.build();
1360 database.storePostReply(reply);
1361 eventBus.post(new NewPostReplyFoundEvent(reply));
1362 sone.addReply(reply);
1363 touchConfiguration();
1364 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1369 * Deletes the given reply.
1372 * The reply to delete
1374 public void deleteReply(PostReply reply) {
1375 Sone sone = reply.getSone();
1376 if (!sone.isLocal()) {
1377 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1380 database.removePostReply(reply);
1381 markReplyKnown(reply);
1382 sone.removeReply(reply);
1383 touchConfiguration();
1387 * Marks the given reply as known, if it is currently not a known reply
1388 * (according to {@link Reply#isKnown()}).
1391 * The reply to mark as known
1393 public void markReplyKnown(PostReply reply) {
1394 boolean previouslyKnown = reply.isKnown();
1395 reply.setKnown(true);
1396 eventBus.post(new MarkPostReplyKnownEvent(reply));
1397 if (!previouslyKnown) {
1398 touchConfiguration();
1403 * Creates a new album for the given Sone.
1406 * The Sone to create the album for
1408 * The parent of the album (may be {@code null} to create a
1410 * @return The new album
1412 public Album createAlbum(Sone sone, Album parent) {
1413 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1414 database.storeAlbum(album);
1415 parent.addAlbum(album);
1420 * Deletes the given album. The owner of the album has to be a local Sone,
1421 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1424 * The album to remove
1426 public void deleteAlbum(Album album) {
1427 checkNotNull(album, "album must not be null");
1428 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1429 if (!album.isEmpty()) {
1432 album.getParent().removeAlbum(album);
1433 database.removeAlbum(album);
1434 touchConfiguration();
1438 * Creates a new image.
1441 * The Sone creating the image
1443 * The album the image will be inserted into
1444 * @param temporaryImage
1445 * The temporary image to create the image from
1446 * @return The newly created image
1448 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1449 checkNotNull(sone, "sone must not be null");
1450 checkNotNull(album, "album must not be null");
1451 checkNotNull(temporaryImage, "temporaryImage must not be null");
1452 checkArgument(sone.isLocal(), "sone must be a local Sone");
1453 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1454 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1455 album.addImage(image);
1456 database.storeImage(image);
1457 imageInserter.insertImage(temporaryImage, image);
1462 * Deletes the given image. This method will also delete a matching
1465 * @see #deleteTemporaryImage(String)
1467 * The image to delete
1469 public void deleteImage(Image image) {
1470 checkNotNull(image, "image must not be null");
1471 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1472 deleteTemporaryImage(image.getId());
1473 image.getAlbum().removeImage(image);
1474 database.removeImage(image);
1475 touchConfiguration();
1479 * Creates a new temporary image.
1482 * The MIME type of the temporary image
1484 * The encoded data of the image
1485 * @return The temporary image
1487 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1488 TemporaryImage temporaryImage = new TemporaryImage();
1489 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1490 synchronized (temporaryImages) {
1491 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1493 return temporaryImage;
1497 * Deletes the temporary image with the given ID.
1500 * The ID of the temporary image to delete
1502 public void deleteTemporaryImage(String imageId) {
1503 checkNotNull(imageId, "imageId must not be null");
1504 synchronized (temporaryImages) {
1505 temporaryImages.remove(imageId);
1507 Image image = getImage(imageId, false);
1508 if (image != null) {
1509 imageInserter.cancelImageInsert(image);
1514 * Notifies the core that the configuration, either of the core or of a
1515 * single local Sone, has changed, and that the configuration should be
1518 public void touchConfiguration() {
1519 lastConfigurationUpdate = System.currentTimeMillis();
1530 public void serviceStart() {
1531 loadConfiguration();
1532 updateChecker.start();
1533 identityManager.start();
1534 webOfTrustUpdater.init();
1535 webOfTrustUpdater.start();
1543 public void serviceRun() {
1544 long lastSaved = System.currentTimeMillis();
1545 while (!shouldStop()) {
1547 long now = System.currentTimeMillis();
1548 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1549 for (Sone localSone : getLocalSones()) {
1550 saveSone(localSone);
1552 saveConfiguration();
1562 public void serviceStop() {
1563 localElementTicker.shutdownNow();
1564 synchronized (sones) {
1565 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1566 soneInserter.getValue().stop();
1567 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1570 saveConfiguration();
1572 webOfTrustUpdater.stop();
1573 updateChecker.stop();
1574 soneDownloader.stop();
1575 soneDownloaders.shutdown();
1576 identityManager.stop();
1584 * Saves the given Sone. This will persist all local settings for the given
1585 * Sone, such as the friends list and similar, private options.
1590 private synchronized void saveSone(Sone sone) {
1591 if (!sone.isLocal()) {
1592 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1595 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1596 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1600 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1602 /* save Sone into configuration. */
1603 String sonePrefix = "Sone/" + sone.getId();
1604 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1605 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1608 Profile profile = sone.getProfile();
1609 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1610 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1611 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1612 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1613 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1614 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1615 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1617 /* save profile fields. */
1618 int fieldCounter = 0;
1619 for (Field profileField : profile.getFields()) {
1620 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1621 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1622 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1624 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1627 int postCounter = 0;
1628 for (Post post : sone.getPosts()) {
1629 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1630 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1631 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1632 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1633 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1635 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1638 int replyCounter = 0;
1639 for (PostReply reply : sone.getReplies()) {
1640 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1641 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1642 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1643 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1644 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1646 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1648 /* save post likes. */
1649 int postLikeCounter = 0;
1650 for (String postId : sone.getLikedPostIds()) {
1651 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1653 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1655 /* save reply likes. */
1656 int replyLikeCounter = 0;
1657 for (String replyId : sone.getLikedReplyIds()) {
1658 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1660 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1663 int friendCounter = 0;
1664 for (String friendId : sone.getFriends()) {
1665 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1667 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1669 /* save albums. first, collect in a flat structure, top-level first. */
1670 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1672 int albumCounter = 0;
1673 for (Album album : albums) {
1674 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1675 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1676 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1677 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1678 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1679 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1681 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1684 int imageCounter = 0;
1685 for (Album album : albums) {
1686 for (Image image : album.getImages()) {
1687 if (!image.isInserted()) {
1690 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1691 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1692 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1693 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1694 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1695 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1696 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1697 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1698 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1701 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1704 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1705 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1706 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1707 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1708 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1709 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1711 configuration.save();
1713 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1715 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1716 } catch (ConfigurationException ce1) {
1717 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1722 * Saves the current options.
1724 private void saveConfiguration() {
1725 synchronized (configuration) {
1726 if (storingConfiguration) {
1727 logger.log(Level.FINE, "Already storing configuration…");
1730 storingConfiguration = true;
1733 /* store the options first. */
1735 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1736 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1737 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1738 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1739 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1740 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1741 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1742 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1743 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1744 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1745 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1746 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1748 /* save known Sones. */
1749 int soneCounter = 0;
1750 synchronized (knownSones) {
1751 for (String knownSoneId : knownSones) {
1752 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1754 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1757 /* save Sone following times. */
1759 synchronized (soneFollowingTimes) {
1760 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1761 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1762 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1765 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1768 /* save known posts. */
1771 /* save bookmarked posts. */
1772 int bookmarkedPostCounter = 0;
1773 synchronized (bookmarkedPosts) {
1774 for (String bookmarkedPostId : bookmarkedPosts) {
1775 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1778 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1781 configuration.save();
1783 } catch (ConfigurationException ce1) {
1784 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1785 } catch (DatabaseException de1) {
1786 logger.log(Level.SEVERE, "Could not save database!", de1);
1788 synchronized (configuration) {
1789 storingConfiguration = false;
1795 * Loads the configuration.
1797 private void loadConfiguration() {
1798 /* create options. */
1799 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1800 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1801 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1802 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1803 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1804 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1805 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1806 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1807 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1808 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1809 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1811 loadConfigurationValue("InsertionDelay");
1812 loadConfigurationValue("PostsPerPage");
1813 loadConfigurationValue("ImagesPerPage");
1814 loadConfigurationValue("CharactersPerPost");
1815 loadConfigurationValue("PostCutOffLength");
1816 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1817 loadConfigurationValue("PositiveTrust");
1818 loadConfigurationValue("NegativeTrust");
1819 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1820 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1821 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1823 /* load known Sones. */
1824 int soneCounter = 0;
1826 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1827 if (knownSoneId == null) {
1830 synchronized (knownSones) {
1831 knownSones.add(knownSoneId);
1835 /* load Sone following times. */
1838 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1839 if (soneId == null) {
1842 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1843 synchronized (soneFollowingTimes) {
1844 soneFollowingTimes.put(soneId, time);
1849 /* load bookmarked posts. */
1850 int bookmarkedPostCounter = 0;
1852 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1853 if (bookmarkedPostId == null) {
1856 synchronized (bookmarkedPosts) {
1857 bookmarkedPosts.add(bookmarkedPostId);
1864 * Loads an {@link Integer} configuration value for the option with the
1865 * given name, logging validation failures.
1868 * The name of the option to load
1870 private void loadConfigurationValue(String optionName) {
1872 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1873 } catch (IllegalArgumentException iae1) {
1874 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1879 * Notifies the core that a new {@link OwnIdentity} was added.
1881 * @param ownIdentityAddedEvent
1885 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1886 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1887 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1888 if (ownIdentity.hasContext("Sone")) {
1889 addLocalSone(ownIdentity);
1894 * Notifies the core that an {@link OwnIdentity} was removed.
1896 * @param ownIdentityRemovedEvent
1900 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1901 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1902 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1903 trustedIdentities.removeAll(ownIdentity);
1907 * Notifies the core that a new {@link Identity} was added.
1909 * @param identityAddedEvent
1913 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1914 Identity identity = identityAddedEvent.identity();
1915 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1916 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1917 addRemoteSone(identity);
1921 * Notifies the core that an {@link Identity} was updated.
1923 * @param identityUpdatedEvent
1927 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1928 Identity identity = identityUpdatedEvent.identity();
1929 final Sone sone = getRemoteSone(identity.getId(), false);
1930 if (sone.isLocal()) {
1933 sone.setIdentity(identity);
1934 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1935 soneDownloader.addSone(sone);
1936 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1940 * Notifies the core that an {@link Identity} was removed.
1942 * @param identityRemovedEvent
1946 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1947 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1948 Identity identity = identityRemovedEvent.identity();
1949 trustedIdentities.remove(ownIdentity, identity);
1950 boolean foundIdentity = false;
1951 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1952 if (trustedIdentity.getKey().equals(ownIdentity)) {
1955 if (trustedIdentity.getValue().contains(identity)) {
1956 foundIdentity = true;
1959 if (foundIdentity) {
1960 /* some local identity still trusts this identity, don’t remove. */
1963 Optional<Sone> sone = getSone(identity.getId());
1964 if (!sone.isPresent()) {
1965 /* TODO - we don’t have the Sone anymore. should this happen? */
1968 database.removePosts(sone.get());
1969 for (Post post : sone.get().getPosts()) {
1970 eventBus.post(new PostRemovedEvent(post));
1972 database.removePostReplies(sone.get());
1973 for (PostReply reply : sone.get().getReplies()) {
1974 eventBus.post(new PostReplyRemovedEvent(reply));
1976 synchronized (sones) {
1977 sones.remove(identity.getId());
1979 eventBus.post(new SoneRemovedEvent(sone.get()));
1983 * Deletes the temporary image.
1985 * @param imageInsertFinishedEvent
1989 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1990 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1991 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1992 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1993 touchConfiguration();
1997 class MarkPostKnown implements Runnable {
1999 private final Post post;
2001 public MarkPostKnown(Post post) {
2007 markPostKnown(post);
2013 class MarkReplyKnown implements Runnable {
2015 private final PostReply postReply;
2017 public MarkReplyKnown(PostReply postReply) {
2018 this.postReply = postReply;
2023 markReplyKnown(postReply);