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.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
43 import net.pterodactylus.sone.core.Options.DefaultOption;
44 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
45 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
46 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
49 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
50 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
51 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
52 import net.pterodactylus.sone.core.event.PostRemovedEvent;
53 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneLockedEvent;
55 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.SoneImpl;
69 import net.pterodactylus.sone.data.TemporaryImage;
70 import net.pterodactylus.sone.database.AlbumBuilder;
71 import net.pterodactylus.sone.database.Database;
72 import net.pterodactylus.sone.database.DatabaseException;
73 import net.pterodactylus.sone.database.PostBuilder;
74 import net.pterodactylus.sone.database.PostProvider;
75 import net.pterodactylus.sone.database.PostReplyBuilder;
76 import net.pterodactylus.sone.database.PostReplyProvider;
77 import net.pterodactylus.sone.database.SoneProvider;
78 import net.pterodactylus.sone.fcp.FcpInterface;
79 import net.pterodactylus.sone.freenet.wot.Identity;
80 import net.pterodactylus.sone.freenet.wot.IdentityManager;
81 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
87 import net.pterodactylus.sone.main.SonePlugin;
88 import net.pterodactylus.sone.utils.IntegerRangePredicate;
89 import net.pterodactylus.util.config.Configuration;
90 import net.pterodactylus.util.config.ConfigurationException;
91 import net.pterodactylus.util.logging.Logging;
92 import net.pterodactylus.util.number.Numbers;
93 import net.pterodactylus.util.service.AbstractService;
94 import net.pterodactylus.util.thread.NamedThreadFactory;
96 import com.google.common.annotations.VisibleForTesting;
97 import com.google.common.base.Optional;
98 import com.google.common.base.Predicates;
99 import com.google.common.collect.FluentIterable;
100 import com.google.common.collect.HashMultimap;
101 import com.google.common.collect.ImmutableSet;
102 import com.google.common.collect.Multimap;
103 import com.google.common.collect.Multimaps;
104 import com.google.common.eventbus.EventBus;
105 import com.google.common.eventbus.Subscribe;
106 import com.google.inject.Inject;
107 import com.google.inject.Singleton;
109 import freenet.keys.FreenetURI;
114 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
117 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
120 private static final Logger logger = Logging.getLogger(Core.class);
122 /** The start time. */
123 private final long startupTime = System.currentTimeMillis();
126 private final Options options = new Options();
128 /** The preferences. */
129 private final Preferences preferences = new Preferences(options);
131 /** The event bus. */
132 private final EventBus eventBus;
134 /** The configuration. */
135 private final Configuration configuration;
137 /** Whether we’re currently saving the configuration. */
138 private boolean storingConfiguration = false;
140 /** The identity manager. */
141 private final IdentityManager identityManager;
143 /** Interface to freenet. */
144 private final FreenetInterface freenetInterface;
146 /** The Sone downloader. */
147 private final SoneDownloader soneDownloader;
149 /** The image inserter. */
150 private final ImageInserter imageInserter;
152 /** Sone downloader thread-pool. */
153 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
155 /** The update checker. */
156 private final UpdateChecker updateChecker;
158 /** The trust updater. */
159 private final WebOfTrustUpdater webOfTrustUpdater;
161 /** The FCP interface. */
162 private volatile FcpInterface fcpInterface;
164 /** The times Sones were followed. */
165 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
167 /** Locked local Sones. */
168 /* synchronize on itself. */
169 private final Set<Sone> lockedSones = new HashSet<Sone>();
171 /** Sone inserters. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
175 /** Sone rescuers. */
176 /* synchronize access on this on sones. */
177 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
180 /* synchronize access on this on itself. */
181 private final Map<String, Sone> sones = new HashMap<String, Sone>();
183 /** All known Sones. */
184 private final Set<String> knownSones = new HashSet<String>();
186 /** The post database. */
187 private final Database database;
189 /** All bookmarked posts. */
190 /* synchronize access on itself. */
191 private final Set<String> bookmarkedPosts = new HashSet<String>();
193 /** Trusted identities, sorted by own identities. */
194 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
222 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
228 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
229 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
232 this.database = database;
236 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
238 this.configuration = configuration;
239 this.freenetInterface = freenetInterface;
240 this.identityManager = identityManager;
241 this.soneDownloader = soneDownloader;
242 this.imageInserter = imageInserter;
243 this.updateChecker = updateChecker;
244 this.webOfTrustUpdater = webOfTrustUpdater;
245 this.eventBus = eventBus;
246 this.database = database;
254 * Returns the time Sone was started.
256 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
258 public long getStartupTime() {
263 * Returns the options used by the core.
265 * @return The options of the core
267 public Preferences getPreferences() {
272 * Returns the identity manager used by the core.
274 * @return The identity manager
276 public IdentityManager getIdentityManager() {
277 return identityManager;
281 * Returns the update checker.
283 * @return The update checker
285 public UpdateChecker getUpdateChecker() {
286 return updateChecker;
290 * Sets the FCP interface to use.
292 * @param fcpInterface
293 * The FCP interface to use
295 public void setFcpInterface(FcpInterface fcpInterface) {
296 this.fcpInterface = fcpInterface;
300 * Returns the Sone rescuer for the given local Sone.
303 * The local Sone to get the rescuer for
304 * @return The Sone rescuer for the given Sone
306 public SoneRescuer getSoneRescuer(Sone sone) {
307 checkNotNull(sone, "sone must not be null");
308 checkArgument(sone.isLocal(), "sone must be local");
309 synchronized (sones) {
310 SoneRescuer soneRescuer = soneRescuers.get(sone);
311 if (soneRescuer == null) {
312 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
313 soneRescuers.put(sone, soneRescuer);
321 * Returns whether the given Sone is currently locked.
325 * @return {@code true} if the Sone is locked, {@code false} if it is not
327 public boolean isLocked(Sone sone) {
328 synchronized (lockedSones) {
329 return lockedSones.contains(sone);
337 public Collection<Sone> getSones() {
338 synchronized (sones) {
339 return ImmutableSet.copyOf(sones.values());
344 * Returns the Sone with the given ID, regardless whether it’s local or
348 * The ID of the Sone to get
349 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Optional<Sone> getSone(String id) {
354 synchronized (sones) {
355 return Optional.fromNullable(sones.get(id));
363 public Collection<Sone> getLocalSones() {
364 synchronized (sones) {
365 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
370 * Returns the local Sone with the given ID, optionally creating a new Sone.
375 * {@code true} to create a new Sone if none exists,
376 * {@code false} to return null if none exists
377 * @return The Sone with the given ID, or {@code null}
379 public Sone getLocalSone(String id, boolean create) {
380 synchronized (sones) {
381 Sone sone = sones.get(id);
382 if ((sone == null) && create) {
383 sone = new SoneImpl(id, true);
386 if ((sone != null) && !sone.isLocal()) {
387 sone = new SoneImpl(id, true);
398 public Collection<Sone> getRemoteSones() {
399 synchronized (sones) {
400 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
405 * Returns the remote Sone with the given ID.
408 * The ID of the remote Sone to get
410 * {@code true} to always create a Sone, {@code false} to return
411 * {@code null} if no Sone with the given ID exists
412 * @return The Sone with the given ID
414 public Sone getRemoteSone(String id, boolean create) {
415 synchronized (sones) {
416 Sone sone = sones.get(id);
417 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
418 sone = new SoneImpl(id, false);
426 * Returns whether the given Sone has been modified.
429 * The Sone to check for modifications
430 * @return {@code true} if a modification has been detected in the Sone,
431 * {@code false} otherwise
433 public boolean isModifiedSone(Sone sone) {
434 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
438 * Returns the time when the given was first followed by any local Sone.
441 * The Sone to get the time for
442 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
443 * been followed, or {@link Long#MAX_VALUE}
445 public long getSoneFollowingTime(Sone sone) {
446 synchronized (soneFollowingTimes) {
447 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
452 * Returns a post builder.
454 * @return A new post builder
456 public PostBuilder postBuilder() {
457 return database.newPostBuilder();
464 public Optional<Post> getPost(String postId) {
465 return database.getPost(postId);
472 public Collection<Post> getPosts(String soneId) {
473 return database.getPosts(soneId);
480 public Collection<Post> getDirectedPosts(final String recipientId) {
481 checkNotNull(recipientId, "recipient must not be null");
482 return database.getDirectedPosts(recipientId);
486 * Returns a post reply builder.
488 * @return A new post reply builder
490 public PostReplyBuilder postReplyBuilder() {
491 return database.newPostReplyBuilder();
498 public Optional<PostReply> getPostReply(String replyId) {
499 return database.getPostReply(replyId);
506 public List<PostReply> getReplies(final String postId) {
507 return database.getReplies(postId);
511 * Returns all Sones that have liked the given post.
514 * The post to get the liking Sones for
515 * @return The Sones that like the given post
517 public Set<Sone> getLikes(Post post) {
518 Set<Sone> sones = new HashSet<Sone>();
519 for (Sone sone : getSones()) {
520 if (sone.getLikedPostIds().contains(post.getId())) {
528 * Returns all Sones that have liked the given reply.
531 * The reply to get the liking Sones for
532 * @return The Sones that like the given reply
534 public Set<Sone> getLikes(PostReply reply) {
535 Set<Sone> sones = new HashSet<Sone>();
536 for (Sone sone : getSones()) {
537 if (sone.getLikedReplyIds().contains(reply.getId())) {
545 * Returns whether the given post is bookmarked.
549 * @return {@code true} if the given post is bookmarked, {@code false}
552 public boolean isBookmarked(Post post) {
553 return isPostBookmarked(post.getId());
557 * Returns whether the post with the given ID is bookmarked.
560 * The ID of the post to check
561 * @return {@code true} if the post with the given ID is bookmarked,
562 * {@code false} otherwise
564 public boolean isPostBookmarked(String id) {
565 synchronized (bookmarkedPosts) {
566 return bookmarkedPosts.contains(id);
571 * Returns all currently known bookmarked posts.
573 * @return All bookmarked posts
575 public Set<Post> getBookmarkedPosts() {
576 Set<Post> posts = new HashSet<Post>();
577 synchronized (bookmarkedPosts) {
578 for (String bookmarkedPostId : bookmarkedPosts) {
579 Optional<Post> post = getPost(bookmarkedPostId);
580 if (post.isPresent()) {
581 posts.add(post.get());
588 public AlbumBuilder albumBuilder() {
589 return database.newAlbumBuilder();
593 * Returns the album with the given ID, optionally creating a new album if
594 * an album with the given ID can not be found.
597 * The ID of the album
598 * @return The album with the given ID, or {@code null} if no album with the
601 public Album getAlbum(String albumId) {
602 return database.getAlbum(albumId).orNull();
606 * Returns the image with the given ID, creating it if necessary.
609 * The ID of the image
610 * @return The image with the given ID
612 public Image getImage(String imageId) {
613 return getImage(imageId, true);
617 * Returns the image with the given ID, optionally creating it if it does
621 * The ID of the image
623 * {@code true} to create an image if none exists with the given
625 * @return The image with the given ID, or {@code null} if none exists and
628 public Image getImage(String imageId, boolean create) {
629 Optional<Image> image = database.getImage(imageId);
630 if (image.isPresent()) {
636 Image newImage = database.newImageBuilder().withId(imageId).build();
637 database.storeImage(newImage);
642 * Returns the temporary image with the given ID.
645 * The ID of the temporary image
646 * @return The temporary image, or {@code null} if there is no temporary
647 * image with the given ID
649 public TemporaryImage getTemporaryImage(String imageId) {
650 synchronized (temporaryImages) {
651 return temporaryImages.get(imageId);
660 * Locks the given Sone. A locked Sone will not be inserted by
661 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
667 public void lockSone(Sone sone) {
668 synchronized (lockedSones) {
669 if (lockedSones.add(sone)) {
670 eventBus.post(new SoneLockedEvent(sone));
676 * Unlocks the given Sone.
678 * @see #lockSone(Sone)
682 public void unlockSone(Sone sone) {
683 synchronized (lockedSones) {
684 if (lockedSones.remove(sone)) {
685 eventBus.post(new SoneUnlockedEvent(sone));
691 * Adds a local Sone from the given own identity.
694 * The own identity to create a Sone from
695 * @return The added (or already existing) Sone
697 public Sone addLocalSone(OwnIdentity ownIdentity) {
698 if (ownIdentity == null) {
699 logger.log(Level.WARNING, "Given OwnIdentity is null!");
702 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
703 synchronized (sones) {
706 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
707 } catch (MalformedURLException mue1) {
708 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
711 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
712 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
714 /* TODO - load posts ’n stuff */
715 sones.put(ownIdentity.getId(), sone);
716 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
717 soneInserters.put(sone, soneInserter);
718 sone.setStatus(SoneStatus.idle);
720 soneInserter.start();
726 * Creates a new Sone for the given own identity.
729 * The own identity to create a Sone for
730 * @return The created Sone
732 public Sone createSone(OwnIdentity ownIdentity) {
733 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
734 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
737 Sone sone = addLocalSone(ownIdentity);
739 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
740 touchConfiguration();
745 * Adds the Sone of the given identity.
748 * The identity whose Sone to add
749 * @return The added or already existing Sone
751 public Sone addRemoteSone(Identity identity) {
752 if (identity == null) {
753 logger.log(Level.WARNING, "Given Identity is null!");
756 synchronized (sones) {
757 final Sone sone = getRemoteSone(identity.getId(), true);
758 if (sone.isLocal()) {
761 sone.setIdentity(identity);
762 boolean newSone = sone.getRequestUri() == null;
763 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
764 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
766 synchronized (knownSones) {
767 newSone = !knownSones.contains(sone.getId());
769 sone.setKnown(!newSone);
771 eventBus.post(new NewSoneFoundEvent(sone));
772 for (Sone localSone : getLocalSones()) {
773 if (localSone.getOptions().isAutoFollow()) {
774 followSone(localSone, sone.getId());
779 soneDownloader.addSone(sone);
780 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
786 * Lets the given local Sone follow the Sone with the given ID.
789 * The local Sone that should follow another Sone
791 * The ID of the Sone to follow
793 public void followSone(Sone sone, String soneId) {
794 checkNotNull(sone, "sone must not be null");
795 checkNotNull(soneId, "soneId must not be null");
796 sone.addFriend(soneId);
797 synchronized (soneFollowingTimes) {
798 if (!soneFollowingTimes.containsKey(soneId)) {
799 long now = System.currentTimeMillis();
800 soneFollowingTimes.put(soneId, now);
801 Optional<Sone> followedSone = getSone(soneId);
802 if (!followedSone.isPresent()) {
805 for (Post post : followedSone.get().getPosts()) {
806 if (post.getTime() < now) {
810 for (PostReply reply : followedSone.get().getReplies()) {
811 if (reply.getTime() < now) {
812 markReplyKnown(reply);
817 touchConfiguration();
821 * Lets the given local Sone unfollow the Sone with the given ID.
824 * The local Sone that should unfollow another Sone
826 * The ID of the Sone being unfollowed
828 public void unfollowSone(Sone sone, String soneId) {
829 checkNotNull(sone, "sone must not be null");
830 checkNotNull(soneId, "soneId must not be null");
831 sone.removeFriend(soneId);
832 boolean unfollowedSoneStillFollowed = false;
833 for (Sone localSone : getLocalSones()) {
834 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
836 if (!unfollowedSoneStillFollowed) {
837 synchronized (soneFollowingTimes) {
838 soneFollowingTimes.remove(soneId);
841 touchConfiguration();
845 * Sets the trust value of the given origin Sone for the target Sone.
852 * The trust value (from {@code -100} to {@code 100})
854 public void setTrust(Sone origin, Sone target, int trustValue) {
855 checkNotNull(origin, "origin must not be null");
856 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
857 checkNotNull(target, "target must not be null");
858 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
859 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
863 * Removes any trust assignment for the given target Sone.
870 public void removeTrust(Sone origin, Sone target) {
871 checkNotNull(origin, "origin must not be null");
872 checkNotNull(target, "target must not be null");
873 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
874 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
878 * Assigns the configured positive trust value for the given target.
885 public void trustSone(Sone origin, Sone target) {
886 setTrust(origin, target, preferences.getPositiveTrust());
890 * Assigns the configured negative trust value for the given target.
897 public void distrustSone(Sone origin, Sone target) {
898 setTrust(origin, target, preferences.getNegativeTrust());
902 * Removes the trust assignment for the given target.
909 public void untrustSone(Sone origin, Sone target) {
910 removeTrust(origin, target);
914 * Updates the stored Sone with the given Sone.
919 public void updateSone(Sone sone) {
920 updateSone(sone, false);
924 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
925 * {@code true}, an older Sone than the current Sone can be given to restore
930 * @param soneRescueMode
931 * {@code true} if the stored Sone should be updated regardless
932 * of the age of the given Sone
934 public void updateSone(Sone sone, boolean soneRescueMode) {
935 Optional<Sone> storedSone = getSone(sone.getId());
936 if (storedSone.isPresent()) {
937 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
938 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
941 /* find removed posts. */
942 Collection<Post> removedPosts = new ArrayList<Post>();
943 Collection<Post> newPosts = new ArrayList<Post>();
944 Collection<Post> existingPosts = database.getPosts(sone.getId());
945 for (Post oldPost : existingPosts) {
946 if (!sone.getPosts().contains(oldPost)) {
947 removedPosts.add(oldPost);
950 /* find new posts. */
951 for (Post newPost : sone.getPosts()) {
952 if (existingPosts.contains(newPost)) {
955 if (newPost.getTime() < getSoneFollowingTime(sone)) {
956 newPost.setKnown(true);
957 } else if (!newPost.isKnown()) {
958 newPosts.add(newPost);
962 database.storePosts(sone, sone.getPosts());
963 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
964 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
965 if (!soneRescueMode) {
966 for (PostReply reply : storedSone.get().getReplies()) {
967 if (!sone.getReplies().contains(reply)) {
968 removedPostReplies.add(reply);
972 Set<PostReply> storedReplies = storedSone.get().getReplies();
973 for (PostReply reply : sone.getReplies()) {
974 if (storedReplies.contains(reply)) {
977 if (reply.getTime() < getSoneFollowingTime(sone)) {
978 reply.setKnown(true);
979 } else if (!reply.isKnown()) {
980 newPostReplies.add(reply);
983 database.storePostReplies(sone, sone.getReplies());
984 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
985 database.removeAlbum(album);
986 for (Image image : album.getImages()) {
987 database.removeImage(image);
990 for (Post removedPost : removedPosts) {
991 eventBus.post(new PostRemovedEvent(removedPost));
993 for (Post newPost : newPosts) {
994 eventBus.post(new NewPostFoundEvent(newPost));
996 for (PostReply removedPostReply : removedPostReplies) {
997 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
999 for (PostReply newPostReply : newPostReplies) {
1000 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1002 for (Album album : sone.getRootAlbum().getAlbums()) {
1003 database.storeAlbum(album);
1004 for (Image image : album.getImages()) {
1005 database.storeImage(image);
1008 synchronized (sones) {
1009 sone.setOptions(storedSone.get().getOptions());
1010 sone.setKnown(storedSone.get().isKnown());
1011 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1012 if (sone.isLocal()) {
1013 soneInserters.get(storedSone.get()).setSone(sone);
1014 touchConfiguration();
1016 sones.put(sone.getId(), sone);
1022 * Deletes the given Sone. This will remove the Sone from the
1023 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1024 * remove the context from its identity.
1027 * The Sone to delete
1029 public void deleteSone(Sone sone) {
1030 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1031 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1034 synchronized (sones) {
1035 if (!getLocalSones().contains(sone)) {
1036 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1039 sones.remove(sone.getId());
1040 SoneInserter soneInserter = soneInserters.remove(sone);
1041 soneInserter.stop();
1043 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1044 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1046 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1047 } catch (ConfigurationException ce1) {
1048 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1053 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1054 * known} before, a {@link MarkSoneKnownEvent} is fired.
1057 * The Sone to mark as known
1059 public void markSoneKnown(Sone sone) {
1060 if (!sone.isKnown()) {
1061 sone.setKnown(true);
1062 synchronized (knownSones) {
1063 knownSones.add(sone.getId());
1065 eventBus.post(new MarkSoneKnownEvent(sone));
1066 touchConfiguration();
1071 * Loads and updates the given Sone from the configuration. If any error is
1072 * encountered, loading is aborted and the given Sone is not changed.
1075 * The Sone to load and update
1077 public void loadSone(Sone sone) {
1078 if (!sone.isLocal()) {
1079 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1082 logger.info(String.format("Loading local Sone: %s", sone));
1085 String sonePrefix = "Sone/" + sone.getId();
1086 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1087 if (soneTime == null) {
1088 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1091 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1094 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1095 Profile profile = configurationSoneParser.parseProfile();
1098 Collection<Post> posts;
1100 posts = configurationSoneParser.parsePosts(database);
1101 } catch (InvalidPostFound ipf) {
1102 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1107 Collection<PostReply> replies;
1109 replies = configurationSoneParser.parsePostReplies(database);
1110 } catch (InvalidPostReplyFound iprf) {
1111 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1115 /* load post likes. */
1116 Set<String> likedPostIds =
1117 configurationSoneParser.parseLikedPostIds();
1119 /* load reply likes. */
1120 Set<String> likedReplyIds =
1121 configurationSoneParser.parseLikedPostReplyIds();
1124 Set<String> friends = configurationSoneParser.parseFriends();
1127 List<Album> topLevelAlbums = new ArrayList<Album>();
1128 int albumCounter = 0;
1130 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1131 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1132 if (albumId == null) {
1135 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1136 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1137 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1138 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1139 if ((albumTitle == null) || (albumDescription == null)) {
1140 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1143 Album album = database.newAlbumBuilder()
1148 .setTitle(albumTitle)
1149 .setDescription(albumDescription)
1150 .setAlbumImage(albumImageId)
1152 if (albumParentId != null) {
1153 Album parentAlbum = getAlbum(albumParentId);
1154 if (parentAlbum == null) {
1155 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1158 parentAlbum.addAlbum(album);
1160 if (!topLevelAlbums.contains(album)) {
1161 topLevelAlbums.add(album);
1167 int imageCounter = 0;
1169 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1170 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1171 if (imageId == null) {
1174 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1175 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1176 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1177 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1178 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1179 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1180 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1181 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1182 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1185 Album album = getAlbum(albumId);
1186 if (album == null) {
1187 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1190 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1191 album.addImage(image);
1195 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1196 if (avatarId != null) {
1197 profile.setAvatar(getImage(avatarId, false));
1201 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1202 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1203 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1204 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1205 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1206 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1208 /* if we’re still here, Sone was loaded successfully. */
1209 synchronized (sone) {
1210 sone.setTime(soneTime);
1211 sone.setProfile(profile);
1212 sone.setPosts(posts);
1213 sone.setReplies(replies);
1214 sone.setLikePostIds(likedPostIds);
1215 sone.setLikeReplyIds(likedReplyIds);
1216 for (String friendId : friends) {
1217 followSone(sone, friendId);
1219 for (Album album : sone.getRootAlbum().getAlbums()) {
1220 sone.getRootAlbum().removeAlbum(album);
1222 for (Album album : topLevelAlbums) {
1223 sone.getRootAlbum().addAlbum(album);
1225 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1227 synchronized (knownSones) {
1228 for (String friend : friends) {
1229 knownSones.add(friend);
1232 database.storePosts(sone, posts);
1233 for (Post post : posts) {
1234 post.setKnown(true);
1236 database.storePostReplies(sone, replies);
1237 for (PostReply reply : replies) {
1238 reply.setKnown(true);
1241 logger.info(String.format("Sone loaded successfully: %s", sone));
1245 * Creates a new post.
1248 * The Sone that creates the post
1250 * The recipient Sone, or {@code null} if this post does not have
1253 * The text of the post
1254 * @return The created post
1256 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1257 return createPost(sone, recipient, System.currentTimeMillis(), text);
1261 * Creates a new post.
1264 * The Sone that creates the post
1266 * The recipient Sone, or {@code null} if this post does not have
1269 * The time of the post
1271 * The text of the post
1272 * @return The created post
1274 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1275 checkNotNull(text, "text must not be null");
1276 checkArgument(text.trim().length() > 0, "text must not be empty");
1277 if (!sone.isLocal()) {
1278 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1281 PostBuilder postBuilder = database.newPostBuilder();
1282 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1283 if (recipient.isPresent()) {
1284 postBuilder.to(recipient.get().getId());
1286 final Post post = postBuilder.build();
1287 database.storePost(post);
1288 eventBus.post(new NewPostFoundEvent(post));
1290 touchConfiguration();
1291 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1296 * Deletes the given post.
1299 * The post to delete
1301 public void deletePost(Post post) {
1302 if (!post.getSone().isLocal()) {
1303 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1306 database.removePost(post);
1307 eventBus.post(new PostRemovedEvent(post));
1308 markPostKnown(post);
1309 touchConfiguration();
1313 * Marks the given post as known, if it is currently not a known post
1314 * (according to {@link Post#isKnown()}).
1317 * The post to mark as known
1319 public void markPostKnown(Post post) {
1320 post.setKnown(true);
1321 eventBus.post(new MarkPostKnownEvent(post));
1322 touchConfiguration();
1323 for (PostReply reply : getReplies(post.getId())) {
1324 markReplyKnown(reply);
1329 * Bookmarks the post with the given ID.
1332 * The ID of the post to bookmark
1334 public void bookmarkPost(String id) {
1335 synchronized (bookmarkedPosts) {
1336 bookmarkedPosts.add(id);
1341 * Removes the given post from the bookmarks.
1344 * The post to unbookmark
1346 public void unbookmark(Post post) {
1347 unbookmarkPost(post.getId());
1351 * Removes the post with the given ID from the bookmarks.
1354 * The ID of the post to unbookmark
1356 public void unbookmarkPost(String id) {
1357 synchronized (bookmarkedPosts) {
1358 bookmarkedPosts.remove(id);
1363 * Creates a new reply.
1366 * The Sone that creates the reply
1368 * The post that this reply refers to
1370 * The text of the reply
1371 * @return The created reply
1373 public PostReply createReply(Sone sone, Post post, String text) {
1374 checkNotNull(text, "text must not be null");
1375 checkArgument(text.trim().length() > 0, "text must not be empty");
1376 if (!sone.isLocal()) {
1377 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1380 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1381 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1382 final PostReply reply = postReplyBuilder.build();
1383 database.storePostReply(reply);
1384 eventBus.post(new NewPostReplyFoundEvent(reply));
1385 sone.addReply(reply);
1386 touchConfiguration();
1387 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1392 * Deletes the given reply.
1395 * The reply to delete
1397 public void deleteReply(PostReply reply) {
1398 Sone sone = reply.getSone();
1399 if (!sone.isLocal()) {
1400 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1403 database.removePostReply(reply);
1404 markReplyKnown(reply);
1405 sone.removeReply(reply);
1406 touchConfiguration();
1410 * Marks the given reply as known, if it is currently not a known reply
1411 * (according to {@link Reply#isKnown()}).
1414 * The reply to mark as known
1416 public void markReplyKnown(PostReply reply) {
1417 boolean previouslyKnown = reply.isKnown();
1418 reply.setKnown(true);
1419 eventBus.post(new MarkPostReplyKnownEvent(reply));
1420 if (!previouslyKnown) {
1421 touchConfiguration();
1426 * Creates a new album for the given Sone.
1429 * The Sone to create the album for
1431 * The parent of the album (may be {@code null} to create a
1433 * @return The new album
1435 public Album createAlbum(Sone sone, Album parent) {
1436 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1437 database.storeAlbum(album);
1438 parent.addAlbum(album);
1443 * Deletes the given album. The owner of the album has to be a local Sone,
1444 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1447 * The album to remove
1449 public void deleteAlbum(Album album) {
1450 checkNotNull(album, "album must not be null");
1451 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1452 if (!album.isEmpty()) {
1455 album.getParent().removeAlbum(album);
1456 database.removeAlbum(album);
1457 touchConfiguration();
1461 * Creates a new image.
1464 * The Sone creating the image
1466 * The album the image will be inserted into
1467 * @param temporaryImage
1468 * The temporary image to create the image from
1469 * @return The newly created image
1471 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1472 checkNotNull(sone, "sone must not be null");
1473 checkNotNull(album, "album must not be null");
1474 checkNotNull(temporaryImage, "temporaryImage must not be null");
1475 checkArgument(sone.isLocal(), "sone must be a local Sone");
1476 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1477 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1478 album.addImage(image);
1479 database.storeImage(image);
1480 imageInserter.insertImage(temporaryImage, image);
1485 * Deletes the given image. This method will also delete a matching
1488 * @see #deleteTemporaryImage(String)
1490 * The image to delete
1492 public void deleteImage(Image image) {
1493 checkNotNull(image, "image must not be null");
1494 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1495 deleteTemporaryImage(image.getId());
1496 image.getAlbum().removeImage(image);
1497 database.removeImage(image);
1498 touchConfiguration();
1502 * Creates a new temporary image.
1505 * The MIME type of the temporary image
1507 * The encoded data of the image
1508 * @return The temporary image
1510 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1511 TemporaryImage temporaryImage = new TemporaryImage();
1512 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1513 synchronized (temporaryImages) {
1514 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1516 return temporaryImage;
1520 * Deletes the temporary image with the given ID.
1523 * The ID of the temporary image to delete
1525 public void deleteTemporaryImage(String imageId) {
1526 checkNotNull(imageId, "imageId must not be null");
1527 synchronized (temporaryImages) {
1528 temporaryImages.remove(imageId);
1530 Image image = getImage(imageId, false);
1531 if (image != null) {
1532 imageInserter.cancelImageInsert(image);
1537 * Notifies the core that the configuration, either of the core or of a
1538 * single local Sone, has changed, and that the configuration should be
1541 public void touchConfiguration() {
1542 lastConfigurationUpdate = System.currentTimeMillis();
1553 public void serviceStart() {
1554 loadConfiguration();
1555 updateChecker.start();
1556 identityManager.start();
1557 webOfTrustUpdater.init();
1558 webOfTrustUpdater.start();
1566 public void serviceRun() {
1567 long lastSaved = System.currentTimeMillis();
1568 while (!shouldStop()) {
1570 long now = System.currentTimeMillis();
1571 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1572 for (Sone localSone : getLocalSones()) {
1573 saveSone(localSone);
1575 saveConfiguration();
1585 public void serviceStop() {
1586 localElementTicker.shutdownNow();
1587 synchronized (sones) {
1588 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1589 soneInserter.getValue().stop();
1590 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1593 saveConfiguration();
1595 webOfTrustUpdater.stop();
1596 updateChecker.stop();
1597 soneDownloader.stop();
1598 soneDownloaders.shutdown();
1599 identityManager.stop();
1607 * Saves the given Sone. This will persist all local settings for the given
1608 * Sone, such as the friends list and similar, private options.
1613 private synchronized void saveSone(Sone sone) {
1614 if (!sone.isLocal()) {
1615 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1618 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1619 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1623 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1625 /* save Sone into configuration. */
1626 String sonePrefix = "Sone/" + sone.getId();
1627 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1628 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1631 Profile profile = sone.getProfile();
1632 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1633 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1634 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1635 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1636 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1637 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1638 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1640 /* save profile fields. */
1641 int fieldCounter = 0;
1642 for (Field profileField : profile.getFields()) {
1643 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1644 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1645 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1647 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1650 int postCounter = 0;
1651 for (Post post : sone.getPosts()) {
1652 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1653 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1654 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1655 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1656 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1658 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1661 int replyCounter = 0;
1662 for (PostReply reply : sone.getReplies()) {
1663 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1664 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1665 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1666 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1667 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1669 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1671 /* save post likes. */
1672 int postLikeCounter = 0;
1673 for (String postId : sone.getLikedPostIds()) {
1674 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1676 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1678 /* save reply likes. */
1679 int replyLikeCounter = 0;
1680 for (String replyId : sone.getLikedReplyIds()) {
1681 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1683 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1686 int friendCounter = 0;
1687 for (String friendId : sone.getFriends()) {
1688 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1690 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1692 /* save albums. first, collect in a flat structure, top-level first. */
1693 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1695 int albumCounter = 0;
1696 for (Album album : albums) {
1697 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1698 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1699 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1700 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1701 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1702 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1704 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1707 int imageCounter = 0;
1708 for (Album album : albums) {
1709 for (Image image : album.getImages()) {
1710 if (!image.isInserted()) {
1713 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1714 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1715 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1716 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1717 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1718 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1719 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1720 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1721 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1724 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1727 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1728 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1729 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1730 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1731 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1732 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1734 configuration.save();
1736 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1738 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1739 } catch (ConfigurationException ce1) {
1740 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1745 * Saves the current options.
1747 private void saveConfiguration() {
1748 synchronized (configuration) {
1749 if (storingConfiguration) {
1750 logger.log(Level.FINE, "Already storing configuration…");
1753 storingConfiguration = true;
1756 /* store the options first. */
1758 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1759 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1760 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1761 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1762 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1763 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1764 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1765 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1766 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1767 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1768 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1769 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1771 /* save known Sones. */
1772 int soneCounter = 0;
1773 synchronized (knownSones) {
1774 for (String knownSoneId : knownSones) {
1775 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1777 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1780 /* save Sone following times. */
1782 synchronized (soneFollowingTimes) {
1783 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1784 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1785 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1788 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1791 /* save known posts. */
1794 /* save bookmarked posts. */
1795 int bookmarkedPostCounter = 0;
1796 synchronized (bookmarkedPosts) {
1797 for (String bookmarkedPostId : bookmarkedPosts) {
1798 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1801 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1804 configuration.save();
1806 } catch (ConfigurationException ce1) {
1807 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1808 } catch (DatabaseException de1) {
1809 logger.log(Level.SEVERE, "Could not save database!", de1);
1811 synchronized (configuration) {
1812 storingConfiguration = false;
1818 * Loads the configuration.
1820 private void loadConfiguration() {
1821 /* create options. */
1822 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1823 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1824 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1825 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1826 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1827 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1828 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1829 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1830 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1831 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1832 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1834 loadConfigurationValue("InsertionDelay");
1835 loadConfigurationValue("PostsPerPage");
1836 loadConfigurationValue("ImagesPerPage");
1837 loadConfigurationValue("CharactersPerPost");
1838 loadConfigurationValue("PostCutOffLength");
1839 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1840 loadConfigurationValue("PositiveTrust");
1841 loadConfigurationValue("NegativeTrust");
1842 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1843 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1844 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1846 /* load known Sones. */
1847 int soneCounter = 0;
1849 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1850 if (knownSoneId == null) {
1853 synchronized (knownSones) {
1854 knownSones.add(knownSoneId);
1858 /* load Sone following times. */
1861 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1862 if (soneId == null) {
1865 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1866 synchronized (soneFollowingTimes) {
1867 soneFollowingTimes.put(soneId, time);
1872 /* load bookmarked posts. */
1873 int bookmarkedPostCounter = 0;
1875 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1876 if (bookmarkedPostId == null) {
1879 synchronized (bookmarkedPosts) {
1880 bookmarkedPosts.add(bookmarkedPostId);
1887 * Loads an {@link Integer} configuration value for the option with the
1888 * given name, logging validation failures.
1891 * The name of the option to load
1893 private void loadConfigurationValue(String optionName) {
1895 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1896 } catch (IllegalArgumentException iae1) {
1897 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1902 * Notifies the core that a new {@link OwnIdentity} was added.
1904 * @param ownIdentityAddedEvent
1908 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1909 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1910 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1911 if (ownIdentity.hasContext("Sone")) {
1912 addLocalSone(ownIdentity);
1917 * Notifies the core that an {@link OwnIdentity} was removed.
1919 * @param ownIdentityRemovedEvent
1923 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1924 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1925 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1926 trustedIdentities.removeAll(ownIdentity);
1930 * Notifies the core that a new {@link Identity} was added.
1932 * @param identityAddedEvent
1936 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1937 Identity identity = identityAddedEvent.identity();
1938 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1939 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1940 addRemoteSone(identity);
1944 * Notifies the core that an {@link Identity} was updated.
1946 * @param identityUpdatedEvent
1950 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1951 Identity identity = identityUpdatedEvent.identity();
1952 final Sone sone = getRemoteSone(identity.getId(), false);
1953 if (sone.isLocal()) {
1956 sone.setIdentity(identity);
1957 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1958 soneDownloader.addSone(sone);
1959 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1963 * Notifies the core that an {@link Identity} was removed.
1965 * @param identityRemovedEvent
1969 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1970 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1971 Identity identity = identityRemovedEvent.identity();
1972 trustedIdentities.remove(ownIdentity, identity);
1973 boolean foundIdentity = false;
1974 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1975 if (trustedIdentity.getKey().equals(ownIdentity)) {
1978 if (trustedIdentity.getValue().contains(identity)) {
1979 foundIdentity = true;
1982 if (foundIdentity) {
1983 /* some local identity still trusts this identity, don’t remove. */
1986 Optional<Sone> sone = getSone(identity.getId());
1987 if (!sone.isPresent()) {
1988 /* TODO - we don’t have the Sone anymore. should this happen? */
1991 database.removePosts(sone.get());
1992 for (Post post : sone.get().getPosts()) {
1993 eventBus.post(new PostRemovedEvent(post));
1995 database.removePostReplies(sone.get());
1996 for (PostReply reply : sone.get().getReplies()) {
1997 eventBus.post(new PostReplyRemovedEvent(reply));
1999 synchronized (sones) {
2000 sones.remove(identity.getId());
2002 eventBus.post(new SoneRemovedEvent(sone.get()));
2006 * Deletes the temporary image.
2008 * @param imageInsertFinishedEvent
2012 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2013 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2014 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2015 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2016 touchConfiguration();
2020 class MarkPostKnown implements Runnable {
2022 private final Post post;
2024 public MarkPostKnown(Post post) {
2030 markPostKnown(post);
2036 class MarkReplyKnown implements Runnable {
2038 private final PostReply postReply;
2040 public MarkReplyKnown(PostReply postReply) {
2041 this.postReply = postReply;
2046 markReplyKnown(postReply);