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.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
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.InvalidAlbumFound;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
46 import net.pterodactylus.sone.core.Options.DefaultOption;
47 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
48 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
49 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
50 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
51 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
52 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
54 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
55 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
56 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
57 import net.pterodactylus.sone.core.event.PostRemovedEvent;
58 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneLockedEvent;
60 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
61 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
62 import net.pterodactylus.sone.data.Album;
63 import net.pterodactylus.sone.data.Client;
64 import net.pterodactylus.sone.data.Image;
65 import net.pterodactylus.sone.data.Post;
66 import net.pterodactylus.sone.data.PostReply;
67 import net.pterodactylus.sone.data.Profile;
68 import net.pterodactylus.sone.data.Profile.Field;
69 import net.pterodactylus.sone.data.Reply;
70 import net.pterodactylus.sone.data.Sone;
71 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
72 import net.pterodactylus.sone.data.Sone.SoneStatus;
73 import net.pterodactylus.sone.data.TemporaryImage;
74 import net.pterodactylus.sone.database.AlbumBuilder;
75 import net.pterodactylus.sone.database.Database;
76 import net.pterodactylus.sone.database.DatabaseException;
77 import net.pterodactylus.sone.database.ImageBuilder;
78 import net.pterodactylus.sone.database.PostBuilder;
79 import net.pterodactylus.sone.database.PostProvider;
80 import net.pterodactylus.sone.database.PostReplyBuilder;
81 import net.pterodactylus.sone.database.PostReplyProvider;
82 import net.pterodactylus.sone.database.SoneBuilder;
83 import net.pterodactylus.sone.database.SoneProvider;
84 import net.pterodactylus.sone.fcp.FcpInterface;
85 import net.pterodactylus.sone.freenet.wot.Identity;
86 import net.pterodactylus.sone.freenet.wot.IdentityManager;
87 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
93 import net.pterodactylus.sone.main.SonePlugin;
94 import net.pterodactylus.sone.utils.IntegerRangePredicate;
95 import net.pterodactylus.util.config.Configuration;
96 import net.pterodactylus.util.config.ConfigurationException;
97 import net.pterodactylus.util.logging.Logging;
98 import net.pterodactylus.util.number.Numbers;
99 import net.pterodactylus.util.service.AbstractService;
100 import net.pterodactylus.util.thread.NamedThreadFactory;
102 import com.google.common.annotations.VisibleForTesting;
103 import com.google.common.base.Optional;
104 import com.google.common.base.Predicates;
105 import com.google.common.collect.FluentIterable;
106 import com.google.common.collect.HashMultimap;
107 import com.google.common.collect.Multimap;
108 import com.google.common.collect.Multimaps;
109 import com.google.common.eventbus.EventBus;
110 import com.google.common.eventbus.Subscribe;
111 import com.google.inject.Inject;
112 import com.google.inject.Singleton;
117 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
120 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
123 private static final Logger logger = Logging.getLogger(Core.class);
125 /** The start time. */
126 private final long startupTime = System.currentTimeMillis();
129 private final Options options = new Options();
131 /** The preferences. */
132 private final Preferences preferences = new Preferences(options);
134 /** The event bus. */
135 private final EventBus eventBus;
137 /** The configuration. */
138 private final Configuration configuration;
140 /** Whether we’re currently saving the configuration. */
141 private boolean storingConfiguration = false;
143 /** The identity manager. */
144 private final IdentityManager identityManager;
146 /** Interface to freenet. */
147 private final FreenetInterface freenetInterface;
149 /** The Sone downloader. */
150 private final SoneDownloader soneDownloader;
152 /** The image inserter. */
153 private final ImageInserter imageInserter;
155 /** Sone downloader thread-pool. */
156 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
158 /** The update checker. */
159 private final UpdateChecker updateChecker;
161 /** The trust updater. */
162 private final WebOfTrustUpdater webOfTrustUpdater;
164 /** The FCP interface. */
165 private volatile FcpInterface fcpInterface;
167 /** The times Sones were followed. */
168 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
170 /** Locked local Sones. */
171 /* synchronize on itself. */
172 private final Set<Sone> lockedSones = new HashSet<Sone>();
174 /** Sone inserters. */
175 /* synchronize access on this on sones. */
176 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
178 /** Sone rescuers. */
179 /* synchronize access on this on sones. */
180 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
182 /** All known Sones. */
183 private final Set<String> knownSones = new HashSet<String>();
185 /** The post database. */
186 private final Database database;
188 /** All bookmarked posts. */
189 /* synchronize access on itself. */
190 private final Set<String> bookmarkedPosts = new HashSet<String>();
192 /** Trusted identities, sorted by own identities. */
193 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
195 /** All temporary images. */
196 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
198 /** Ticker for threads that mark own elements as known. */
199 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
201 /** The time the configuration was last touched. */
202 private volatile long lastConfigurationUpdate;
205 * Creates a new core.
207 * @param configuration
208 * The configuration of the core
209 * @param freenetInterface
210 * The freenet interface
211 * @param identityManager
212 * The identity manager
213 * @param webOfTrustUpdater
214 * The WebOfTrust updater
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
227 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
228 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
231 this.database = database;
235 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
237 this.configuration = configuration;
238 this.freenetInterface = freenetInterface;
239 this.identityManager = identityManager;
240 this.soneDownloader = soneDownloader;
241 this.imageInserter = imageInserter;
242 this.updateChecker = updateChecker;
243 this.webOfTrustUpdater = webOfTrustUpdater;
244 this.eventBus = eventBus;
245 this.database = database;
253 * Returns the time Sone was started.
255 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
257 public long getStartupTime() {
262 * Returns the options used by the core.
264 * @return The options of the core
266 public Preferences getPreferences() {
271 * Returns the identity manager used by the core.
273 * @return The identity manager
275 public IdentityManager getIdentityManager() {
276 return identityManager;
280 * Returns the update checker.
282 * @return The update checker
284 public UpdateChecker getUpdateChecker() {
285 return updateChecker;
289 * Sets the FCP interface to use.
291 * @param fcpInterface
292 * The FCP interface to use
294 public void setFcpInterface(FcpInterface fcpInterface) {
295 this.fcpInterface = fcpInterface;
299 * Returns the Sone rescuer for the given local Sone.
302 * The local Sone to get the rescuer for
303 * @return The Sone rescuer for the given Sone
305 public SoneRescuer getSoneRescuer(Sone sone) {
306 checkNotNull(sone, "sone must not be null");
307 checkArgument(sone.isLocal(), "sone must be local");
308 synchronized (soneRescuers) {
309 SoneRescuer soneRescuer = soneRescuers.get(sone);
310 if (soneRescuer == null) {
311 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
312 soneRescuers.put(sone, soneRescuer);
320 * Returns whether the given Sone is currently locked.
324 * @return {@code true} if the Sone is locked, {@code false} if it is not
326 public boolean isLocked(Sone sone) {
327 synchronized (lockedSones) {
328 return lockedSones.contains(sone);
332 public SoneBuilder soneBuilder() {
333 return database.newSoneBuilder();
340 public Collection<Sone> getSones() {
341 return database.getSones();
345 * Returns the Sone with the given ID, regardless whether it’s local or
349 * The ID of the Sone to get
350 * @return The Sone with the given ID, or {@code null} if there is no such
354 public Optional<Sone> getSone(String id) {
355 return database.getSone(id);
362 public Collection<Sone> getLocalSones() {
363 return database.getLocalSones();
367 * Returns the local Sone with the given ID, optionally creating a new Sone.
371 * @return The Sone with the given ID, or {@code null}
373 public Sone getLocalSone(String id) {
374 Optional<Sone> sone = database.getSone(id);
375 if (sone.isPresent() && sone.get().isLocal()) {
385 public Collection<Sone> getRemoteSones() {
386 return database.getRemoteSones();
390 * Returns the remote Sone with the given ID.
394 * The ID of the remote Sone to get
395 * @return The Sone with the given ID
397 public Sone getRemoteSone(String id) {
398 return database.getSone(id).orNull();
402 * Returns whether the given Sone has been modified.
405 * The Sone to check for modifications
406 * @return {@code true} if a modification has been detected in the Sone,
407 * {@code false} otherwise
409 public boolean isModifiedSone(Sone sone) {
410 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
414 * Returns the time when the given was first followed by any local Sone.
417 * The Sone to get the time for
418 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
419 * been followed, or {@link Long#MAX_VALUE}
421 public long getSoneFollowingTime(Sone sone) {
422 synchronized (soneFollowingTimes) {
423 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
428 * Returns a post builder.
430 * @return A new post builder
432 public PostBuilder postBuilder() {
433 return database.newPostBuilder();
440 public Optional<Post> getPost(String postId) {
441 return database.getPost(postId);
448 public Collection<Post> getPosts(String soneId) {
449 return database.getPosts(soneId);
456 public Collection<Post> getDirectedPosts(final String recipientId) {
457 checkNotNull(recipientId, "recipient must not be null");
458 return database.getDirectedPosts(recipientId);
462 * Returns a post reply builder.
464 * @return A new post reply builder
466 public PostReplyBuilder postReplyBuilder() {
467 return database.newPostReplyBuilder();
474 public Optional<PostReply> getPostReply(String replyId) {
475 return database.getPostReply(replyId);
482 public List<PostReply> getReplies(final String postId) {
483 return database.getReplies(postId);
487 * Returns all Sones that have liked the given post.
490 * The post to get the liking Sones for
491 * @return The Sones that like the given post
493 public Set<Sone> getLikes(Post post) {
494 Set<Sone> sones = new HashSet<Sone>();
495 for (Sone sone : getSones()) {
496 if (sone.getLikedPostIds().contains(post.getId())) {
504 * Returns all Sones that have liked the given reply.
507 * The reply to get the liking Sones for
508 * @return The Sones that like the given reply
510 public Set<Sone> getLikes(PostReply reply) {
511 Set<Sone> sones = new HashSet<Sone>();
512 for (Sone sone : getSones()) {
513 if (sone.getLikedReplyIds().contains(reply.getId())) {
521 * Returns whether the given post is bookmarked.
525 * @return {@code true} if the given post is bookmarked, {@code false}
528 public boolean isBookmarked(Post post) {
529 return isPostBookmarked(post.getId());
533 * Returns whether the post with the given ID is bookmarked.
536 * The ID of the post to check
537 * @return {@code true} if the post with the given ID is bookmarked,
538 * {@code false} otherwise
540 public boolean isPostBookmarked(String id) {
541 synchronized (bookmarkedPosts) {
542 return bookmarkedPosts.contains(id);
547 * Returns all currently known bookmarked posts.
549 * @return All bookmarked posts
551 public Set<Post> getBookmarkedPosts() {
552 Set<Post> posts = new HashSet<Post>();
553 synchronized (bookmarkedPosts) {
554 for (String bookmarkedPostId : bookmarkedPosts) {
555 Optional<Post> post = getPost(bookmarkedPostId);
556 if (post.isPresent()) {
557 posts.add(post.get());
564 public AlbumBuilder albumBuilder() {
565 return database.newAlbumBuilder();
569 * Returns the album with the given ID, optionally creating a new album if
570 * an album with the given ID can not be found.
573 * The ID of the album
574 * @return The album with the given ID, or {@code null} if no album with the
577 public Album getAlbum(String albumId) {
578 return database.getAlbum(albumId).orNull();
581 public ImageBuilder imageBuilder() {
582 return database.newImageBuilder();
586 * Returns the image with the given ID, creating it if necessary.
589 * The ID of the image
590 * @return The image with the given ID
592 public Image getImage(String imageId) {
593 return getImage(imageId, true);
597 * Returns the image with the given ID, optionally creating it if it does
601 * The ID of the image
603 * {@code true} to create an image if none exists with the given
605 * @return The image with the given ID, or {@code null} if none exists and
608 public Image getImage(String imageId, boolean create) {
609 Optional<Image> image = database.getImage(imageId);
610 if (image.isPresent()) {
616 Image newImage = database.newImageBuilder().withId(imageId).build();
617 database.storeImage(newImage);
622 * Returns the temporary image with the given ID.
625 * The ID of the temporary image
626 * @return The temporary image, or {@code null} if there is no temporary
627 * image with the given ID
629 public TemporaryImage getTemporaryImage(String imageId) {
630 synchronized (temporaryImages) {
631 return temporaryImages.get(imageId);
640 * Locks the given Sone. A locked Sone will not be inserted by
641 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
647 public void lockSone(Sone sone) {
648 synchronized (lockedSones) {
649 if (lockedSones.add(sone)) {
650 eventBus.post(new SoneLockedEvent(sone));
656 * Unlocks the given Sone.
658 * @see #lockSone(Sone)
662 public void unlockSone(Sone sone) {
663 synchronized (lockedSones) {
664 if (lockedSones.remove(sone)) {
665 eventBus.post(new SoneUnlockedEvent(sone));
671 * Adds a local Sone from the given own identity.
674 * The own identity to create a Sone from
675 * @return The added (or already existing) Sone
677 public Sone addLocalSone(OwnIdentity ownIdentity) {
678 if (ownIdentity == null) {
679 logger.log(Level.WARNING, "Given OwnIdentity is null!");
682 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
683 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
684 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
685 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
687 /* TODO - load posts ’n stuff */
688 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
689 synchronized (soneInserters) {
690 soneInserters.put(sone, soneInserter);
693 sone.setStatus(SoneStatus.idle);
694 soneInserter.start();
699 * Creates a new Sone for the given own identity.
702 * The own identity to create a Sone for
703 * @return The created Sone
705 public Sone createSone(OwnIdentity ownIdentity) {
706 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
707 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
710 Sone sone = addLocalSone(ownIdentity);
712 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
713 touchConfiguration();
718 * Adds the Sone of the given identity.
721 * The identity whose Sone to add
722 * @return The added or already existing Sone
724 public Sone addRemoteSone(Identity identity) {
725 if (identity == null) {
726 logger.log(Level.WARNING, "Given Identity is null!");
729 final Long latestEdition = tryParse(fromNullable(
730 identity.getProperty("Sone.LatestEdition")).or("0"));
731 Optional<Sone> existingSone = getSone(identity.getId());
732 if (existingSone.isPresent() && existingSone.get().isLocal()) {
733 return existingSone.get();
735 boolean newSone = !existingSone.isPresent();
736 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
737 sone.setLatestEdition(latestEdition);
739 synchronized (knownSones) {
740 newSone = !knownSones.contains(sone.getId());
742 sone.setKnown(!newSone);
744 eventBus.post(new NewSoneFoundEvent(sone));
745 for (Sone localSone : getLocalSones()) {
746 if (localSone.getOptions().isAutoFollow()) {
747 followSone(localSone, sone.getId());
752 database.storeSone(sone);
753 soneDownloader.addSone(sone);
754 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
759 * Lets the given local Sone follow the Sone with the given ID.
762 * The local Sone that should follow another Sone
764 * The ID of the Sone to follow
766 public void followSone(Sone sone, String soneId) {
767 checkNotNull(sone, "sone must not be null");
768 checkNotNull(soneId, "soneId must not be null");
769 sone.addFriend(soneId);
770 synchronized (soneFollowingTimes) {
771 if (!soneFollowingTimes.containsKey(soneId)) {
772 long now = System.currentTimeMillis();
773 soneFollowingTimes.put(soneId, now);
774 Optional<Sone> followedSone = getSone(soneId);
775 if (!followedSone.isPresent()) {
778 for (Post post : followedSone.get().getPosts()) {
779 if (post.getTime() < now) {
783 for (PostReply reply : followedSone.get().getReplies()) {
784 if (reply.getTime() < now) {
785 markReplyKnown(reply);
790 touchConfiguration();
794 * Lets the given local Sone unfollow the Sone with the given ID.
797 * The local Sone that should unfollow another Sone
799 * The ID of the Sone being unfollowed
801 public void unfollowSone(Sone sone, String soneId) {
802 checkNotNull(sone, "sone must not be null");
803 checkNotNull(soneId, "soneId must not be null");
804 sone.removeFriend(soneId);
805 boolean unfollowedSoneStillFollowed = false;
806 for (Sone localSone : getLocalSones()) {
807 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
809 if (!unfollowedSoneStillFollowed) {
810 synchronized (soneFollowingTimes) {
811 soneFollowingTimes.remove(soneId);
814 touchConfiguration();
818 * Sets the trust value of the given origin Sone for the target Sone.
825 * The trust value (from {@code -100} to {@code 100})
827 public void setTrust(Sone origin, Sone target, int trustValue) {
828 checkNotNull(origin, "origin must not be null");
829 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
830 checkNotNull(target, "target must not be null");
831 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
832 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
836 * Removes any trust assignment for the given target Sone.
843 public void removeTrust(Sone origin, Sone target) {
844 checkNotNull(origin, "origin must not be null");
845 checkNotNull(target, "target must not be null");
846 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
847 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
851 * Assigns the configured positive trust value for the given target.
858 public void trustSone(Sone origin, Sone target) {
859 setTrust(origin, target, preferences.getPositiveTrust());
863 * Assigns the configured negative trust value for the given target.
870 public void distrustSone(Sone origin, Sone target) {
871 setTrust(origin, target, preferences.getNegativeTrust());
875 * Removes the trust assignment for the given target.
882 public void untrustSone(Sone origin, Sone target) {
883 removeTrust(origin, target);
887 * Updates the stored Sone with the given Sone.
892 public void updateSone(Sone sone) {
893 updateSone(sone, false);
897 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
898 * {@code true}, an older Sone than the current Sone can be given to restore
903 * @param soneRescueMode
904 * {@code true} if the stored Sone should be updated regardless
905 * of the age of the given Sone
907 public void updateSone(final Sone sone, boolean soneRescueMode) {
908 Optional<Sone> storedSone = getSone(sone.getId());
909 if (storedSone.isPresent()) {
910 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
911 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
914 /* find removed posts. */
915 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
916 soneChangeDetector.onNewPosts(new PostProcessor() {
918 public void processPost(Post post) {
919 if (post.getTime() < getSoneFollowingTime(sone)) {
921 } else if (!post.isKnown()) {
922 eventBus.post(new NewPostFoundEvent(post));
926 soneChangeDetector.onRemovedPosts(new PostProcessor() {
928 public void processPost(Post post) {
929 eventBus.post(new PostRemovedEvent(post));
932 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
934 public void processPostReply(PostReply postReply) {
935 if (postReply.getTime() < getSoneFollowingTime(sone)) {
936 postReply.setKnown(true);
937 } else if (!postReply.isKnown()) {
938 eventBus.post(new NewPostReplyFoundEvent(postReply));
942 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
944 public void processPostReply(PostReply postReply) {
945 eventBus.post(new PostReplyRemovedEvent(postReply));
948 soneChangeDetector.detectChanges(sone);
949 database.storeSone(sone);
950 sone.setOptions(storedSone.get().getOptions());
951 sone.setKnown(storedSone.get().isKnown());
952 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
953 if (sone.isLocal()) {
954 touchConfiguration();
960 * Deletes the given Sone. This will remove the Sone from the
961 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
962 * remove the context from its identity.
967 public void deleteSone(Sone sone) {
968 if (!(sone.getIdentity() instanceof OwnIdentity)) {
969 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
972 if (!getLocalSones().contains(sone)) {
973 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
976 // FIXME – implement in database
977 // sones.remove(sone.getId());
978 SoneInserter soneInserter = soneInserters.remove(sone);
980 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
981 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
983 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
984 } catch (ConfigurationException ce1) {
985 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
990 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
991 * known} before, a {@link MarkSoneKnownEvent} is fired.
994 * The Sone to mark as known
996 public void markSoneKnown(Sone sone) {
997 if (!sone.isKnown()) {
999 synchronized (knownSones) {
1000 knownSones.add(sone.getId());
1002 eventBus.post(new MarkSoneKnownEvent(sone));
1003 touchConfiguration();
1008 * Loads and updates the given Sone from the configuration. If any error is
1009 * encountered, loading is aborted and the given Sone is not changed.
1012 * The Sone to load and update
1014 public void loadSone(Sone sone) {
1015 if (!sone.isLocal()) {
1016 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1019 logger.info(String.format("Loading local Sone: %s", sone));
1022 String sonePrefix = "Sone/" + sone.getId();
1023 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1024 if (soneTime == null) {
1025 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1028 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1031 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1032 Profile profile = configurationSoneParser.parseProfile();
1035 Collection<Post> posts;
1037 posts = configurationSoneParser.parsePosts(database);
1038 } catch (InvalidPostFound ipf) {
1039 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1044 Collection<PostReply> replies;
1046 replies = configurationSoneParser.parsePostReplies(database);
1047 } catch (InvalidPostReplyFound iprf) {
1048 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1052 /* load post likes. */
1053 Set<String> likedPostIds =
1054 configurationSoneParser.parseLikedPostIds();
1056 /* load reply likes. */
1057 Set<String> likedReplyIds =
1058 configurationSoneParser.parseLikedPostReplyIds();
1061 Set<String> friends = configurationSoneParser.parseFriends();
1064 List<Album> topLevelAlbums;
1067 configurationSoneParser.parseTopLevelAlbums(database);
1068 } catch (InvalidAlbumFound iaf) {
1069 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1071 } catch (InvalidParentAlbumFound ipaf) {
1072 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1073 ipaf.getAlbumParentId()));
1079 configurationSoneParser.parseImages(database);
1080 } catch (InvalidImageFound iif) {
1081 logger.log(WARNING, "Invalid image found, aborting load!");
1083 } catch (InvalidParentAlbumFound ipaf) {
1084 logger.log(Level.WARNING,
1085 format("Invalid album image (%s) encountered, aborting load!",
1086 ipaf.getAlbumParentId()));
1091 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1092 if (avatarId != null) {
1093 final Map<String, Image> images =
1094 configurationSoneParser.getImages();
1095 profile.setAvatar(images.get(avatarId));
1099 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1100 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1101 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1102 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1103 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1104 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1106 /* if we’re still here, Sone was loaded successfully. */
1107 synchronized (sone) {
1108 sone.setTime(soneTime);
1109 sone.setProfile(profile);
1110 sone.setPosts(posts);
1111 sone.setReplies(replies);
1112 sone.setLikePostIds(likedPostIds);
1113 sone.setLikeReplyIds(likedReplyIds);
1114 for (String friendId : friends) {
1115 followSone(sone, friendId);
1117 for (Album album : sone.getRootAlbum().getAlbums()) {
1118 sone.getRootAlbum().removeAlbum(album);
1120 for (Album album : topLevelAlbums) {
1121 sone.getRootAlbum().addAlbum(album);
1123 database.storeSone(sone);
1124 synchronized (soneInserters) {
1125 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1128 synchronized (knownSones) {
1129 for (String friend : friends) {
1130 knownSones.add(friend);
1133 for (Post post : posts) {
1134 post.setKnown(true);
1136 for (PostReply reply : replies) {
1137 reply.setKnown(true);
1140 logger.info(String.format("Sone loaded successfully: %s", sone));
1144 * Creates a new post.
1147 * The Sone that creates the post
1149 * The recipient Sone, or {@code null} if this post does not have
1152 * The text of the post
1153 * @return The created post
1155 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1156 return createPost(sone, recipient, System.currentTimeMillis(), text);
1160 * Creates a new post.
1163 * The Sone that creates the post
1165 * The recipient Sone, or {@code null} if this post does not have
1168 * The time of the post
1170 * The text of the post
1171 * @return The created post
1173 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1174 checkNotNull(text, "text must not be null");
1175 checkArgument(text.trim().length() > 0, "text must not be empty");
1176 if (!sone.isLocal()) {
1177 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1180 PostBuilder postBuilder = database.newPostBuilder();
1181 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1182 if (recipient.isPresent()) {
1183 postBuilder.to(recipient.get().getId());
1185 final Post post = postBuilder.build();
1186 database.storePost(post);
1187 eventBus.post(new NewPostFoundEvent(post));
1189 touchConfiguration();
1190 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1195 * Deletes the given post.
1198 * The post to delete
1200 public void deletePost(Post post) {
1201 if (!post.getSone().isLocal()) {
1202 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1205 database.removePost(post);
1206 eventBus.post(new PostRemovedEvent(post));
1207 markPostKnown(post);
1208 touchConfiguration();
1212 * Marks the given post as known, if it is currently not a known post
1213 * (according to {@link Post#isKnown()}).
1216 * The post to mark as known
1218 public void markPostKnown(Post post) {
1219 post.setKnown(true);
1220 eventBus.post(new MarkPostKnownEvent(post));
1221 touchConfiguration();
1222 for (PostReply reply : getReplies(post.getId())) {
1223 markReplyKnown(reply);
1228 * Bookmarks the post with the given ID.
1231 * The ID of the post to bookmark
1233 public void bookmarkPost(String id) {
1234 synchronized (bookmarkedPosts) {
1235 bookmarkedPosts.add(id);
1240 * Removes the given post from the bookmarks.
1243 * The post to unbookmark
1245 public void unbookmark(Post post) {
1246 unbookmarkPost(post.getId());
1250 * Removes the post with the given ID from the bookmarks.
1253 * The ID of the post to unbookmark
1255 public void unbookmarkPost(String id) {
1256 synchronized (bookmarkedPosts) {
1257 bookmarkedPosts.remove(id);
1262 * Creates a new reply.
1265 * The Sone that creates the reply
1267 * The post that this reply refers to
1269 * The text of the reply
1270 * @return The created reply
1272 public PostReply createReply(Sone sone, Post post, String text) {
1273 checkNotNull(text, "text must not be null");
1274 checkArgument(text.trim().length() > 0, "text must not be empty");
1275 if (!sone.isLocal()) {
1276 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1279 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1280 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1281 final PostReply reply = postReplyBuilder.build();
1282 database.storePostReply(reply);
1283 eventBus.post(new NewPostReplyFoundEvent(reply));
1284 sone.addReply(reply);
1285 touchConfiguration();
1286 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1291 * Deletes the given reply.
1294 * The reply to delete
1296 public void deleteReply(PostReply reply) {
1297 Sone sone = reply.getSone();
1298 if (!sone.isLocal()) {
1299 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1302 database.removePostReply(reply);
1303 markReplyKnown(reply);
1304 sone.removeReply(reply);
1305 touchConfiguration();
1309 * Marks the given reply as known, if it is currently not a known reply
1310 * (according to {@link Reply#isKnown()}).
1313 * The reply to mark as known
1315 public void markReplyKnown(PostReply reply) {
1316 boolean previouslyKnown = reply.isKnown();
1317 reply.setKnown(true);
1318 eventBus.post(new MarkPostReplyKnownEvent(reply));
1319 if (!previouslyKnown) {
1320 touchConfiguration();
1325 * Creates a new album for the given Sone.
1328 * The Sone to create the album for
1330 * The parent of the album (may be {@code null} to create a
1332 * @return The new album
1334 public Album createAlbum(Sone sone, Album parent) {
1335 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1336 database.storeAlbum(album);
1337 parent.addAlbum(album);
1342 * Deletes the given album. The owner of the album has to be a local Sone,
1343 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1346 * The album to remove
1348 public void deleteAlbum(Album album) {
1349 checkNotNull(album, "album must not be null");
1350 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1351 if (!album.isEmpty()) {
1354 album.getParent().removeAlbum(album);
1355 database.removeAlbum(album);
1356 touchConfiguration();
1360 * Creates a new image.
1363 * The Sone creating the image
1365 * The album the image will be inserted into
1366 * @param temporaryImage
1367 * The temporary image to create the image from
1368 * @return The newly created image
1370 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1371 checkNotNull(sone, "sone must not be null");
1372 checkNotNull(album, "album must not be null");
1373 checkNotNull(temporaryImage, "temporaryImage must not be null");
1374 checkArgument(sone.isLocal(), "sone must be a local Sone");
1375 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1376 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1377 album.addImage(image);
1378 database.storeImage(image);
1379 imageInserter.insertImage(temporaryImage, image);
1384 * Deletes the given image. This method will also delete a matching
1387 * @see #deleteTemporaryImage(String)
1389 * The image to delete
1391 public void deleteImage(Image image) {
1392 checkNotNull(image, "image must not be null");
1393 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1394 deleteTemporaryImage(image.getId());
1395 image.getAlbum().removeImage(image);
1396 database.removeImage(image);
1397 touchConfiguration();
1401 * Creates a new temporary image.
1404 * The MIME type of the temporary image
1406 * The encoded data of the image
1407 * @return The temporary image
1409 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1410 TemporaryImage temporaryImage = new TemporaryImage();
1411 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1412 synchronized (temporaryImages) {
1413 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1415 return temporaryImage;
1419 * Deletes the temporary image with the given ID.
1422 * The ID of the temporary image to delete
1424 public void deleteTemporaryImage(String imageId) {
1425 checkNotNull(imageId, "imageId must not be null");
1426 synchronized (temporaryImages) {
1427 temporaryImages.remove(imageId);
1429 Image image = getImage(imageId, false);
1430 if (image != null) {
1431 imageInserter.cancelImageInsert(image);
1436 * Notifies the core that the configuration, either of the core or of a
1437 * single local Sone, has changed, and that the configuration should be
1440 public void touchConfiguration() {
1441 lastConfigurationUpdate = System.currentTimeMillis();
1452 public void serviceStart() {
1453 loadConfiguration();
1454 updateChecker.start();
1455 identityManager.start();
1456 webOfTrustUpdater.init();
1457 webOfTrustUpdater.start();
1465 public void serviceRun() {
1466 long lastSaved = System.currentTimeMillis();
1467 while (!shouldStop()) {
1469 long now = System.currentTimeMillis();
1470 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1471 for (Sone localSone : getLocalSones()) {
1472 saveSone(localSone);
1474 saveConfiguration();
1484 public void serviceStop() {
1485 localElementTicker.shutdownNow();
1486 synchronized (soneInserters) {
1487 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1488 soneInserter.getValue().stop();
1489 saveSone(soneInserter.getKey());
1492 saveConfiguration();
1494 webOfTrustUpdater.stop();
1495 updateChecker.stop();
1496 soneDownloader.stop();
1497 soneDownloaders.shutdown();
1498 identityManager.stop();
1506 * Saves the given Sone. This will persist all local settings for the given
1507 * Sone, such as the friends list and similar, private options.
1512 private synchronized void saveSone(Sone sone) {
1513 if (!sone.isLocal()) {
1514 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1517 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1518 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1522 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1524 /* save Sone into configuration. */
1525 String sonePrefix = "Sone/" + sone.getId();
1526 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1527 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1530 Profile profile = sone.getProfile();
1531 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1532 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1533 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1534 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1535 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1536 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1537 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1539 /* save profile fields. */
1540 int fieldCounter = 0;
1541 for (Field profileField : profile.getFields()) {
1542 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1543 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1544 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1546 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1549 int postCounter = 0;
1550 for (Post post : sone.getPosts()) {
1551 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1552 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1553 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1554 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1555 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1557 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1560 int replyCounter = 0;
1561 for (PostReply reply : sone.getReplies()) {
1562 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1563 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1564 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1565 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1566 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1568 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1570 /* save post likes. */
1571 int postLikeCounter = 0;
1572 for (String postId : sone.getLikedPostIds()) {
1573 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1575 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1577 /* save reply likes. */
1578 int replyLikeCounter = 0;
1579 for (String replyId : sone.getLikedReplyIds()) {
1580 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1582 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1585 int friendCounter = 0;
1586 for (String friendId : sone.getFriends()) {
1587 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1589 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1591 /* save albums. first, collect in a flat structure, top-level first. */
1592 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1594 int albumCounter = 0;
1595 for (Album album : albums) {
1596 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1597 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1598 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1599 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1600 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1601 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1603 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1606 int imageCounter = 0;
1607 for (Album album : albums) {
1608 for (Image image : album.getImages()) {
1609 if (!image.isInserted()) {
1612 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1613 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1614 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1615 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1616 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1617 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1618 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1619 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1620 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1623 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1626 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1627 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1628 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1629 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1630 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1631 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1633 configuration.save();
1635 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1637 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1638 } catch (ConfigurationException ce1) {
1639 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1644 * Saves the current options.
1646 private void saveConfiguration() {
1647 synchronized (configuration) {
1648 if (storingConfiguration) {
1649 logger.log(Level.FINE, "Already storing configuration…");
1652 storingConfiguration = true;
1655 /* store the options first. */
1657 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1658 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1659 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1660 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1661 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1662 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1663 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1664 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1665 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1666 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1667 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1668 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1670 /* save known Sones. */
1671 int soneCounter = 0;
1672 synchronized (knownSones) {
1673 for (String knownSoneId : knownSones) {
1674 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1676 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1679 /* save Sone following times. */
1681 synchronized (soneFollowingTimes) {
1682 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1683 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1684 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1687 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1690 /* save known posts. */
1693 /* save bookmarked posts. */
1694 int bookmarkedPostCounter = 0;
1695 synchronized (bookmarkedPosts) {
1696 for (String bookmarkedPostId : bookmarkedPosts) {
1697 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1700 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1703 configuration.save();
1705 } catch (ConfigurationException ce1) {
1706 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1707 } catch (DatabaseException de1) {
1708 logger.log(Level.SEVERE, "Could not save database!", de1);
1710 synchronized (configuration) {
1711 storingConfiguration = false;
1717 * Loads the configuration.
1719 private void loadConfiguration() {
1720 /* create options. */
1721 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1722 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1723 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1724 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1725 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1726 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1727 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1728 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1729 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1730 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1731 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1733 loadConfigurationValue("InsertionDelay");
1734 loadConfigurationValue("PostsPerPage");
1735 loadConfigurationValue("ImagesPerPage");
1736 loadConfigurationValue("CharactersPerPost");
1737 loadConfigurationValue("PostCutOffLength");
1738 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1739 loadConfigurationValue("PositiveTrust");
1740 loadConfigurationValue("NegativeTrust");
1741 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1742 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1743 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1745 /* load known Sones. */
1746 int soneCounter = 0;
1748 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1749 if (knownSoneId == null) {
1752 synchronized (knownSones) {
1753 knownSones.add(knownSoneId);
1757 /* load Sone following times. */
1760 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1761 if (soneId == null) {
1764 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1765 synchronized (soneFollowingTimes) {
1766 soneFollowingTimes.put(soneId, time);
1771 /* load bookmarked posts. */
1772 int bookmarkedPostCounter = 0;
1774 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1775 if (bookmarkedPostId == null) {
1778 synchronized (bookmarkedPosts) {
1779 bookmarkedPosts.add(bookmarkedPostId);
1786 * Loads an {@link Integer} configuration value for the option with the
1787 * given name, logging validation failures.
1790 * The name of the option to load
1792 private void loadConfigurationValue(String optionName) {
1794 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1795 } catch (IllegalArgumentException iae1) {
1796 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1801 * Notifies the core that a new {@link OwnIdentity} was added.
1803 * @param ownIdentityAddedEvent
1807 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1808 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1809 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1810 if (ownIdentity.hasContext("Sone")) {
1811 addLocalSone(ownIdentity);
1816 * Notifies the core that an {@link OwnIdentity} was removed.
1818 * @param ownIdentityRemovedEvent
1822 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1823 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1824 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1825 trustedIdentities.removeAll(ownIdentity);
1829 * Notifies the core that a new {@link Identity} was added.
1831 * @param identityAddedEvent
1835 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1836 Identity identity = identityAddedEvent.identity();
1837 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1838 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1839 addRemoteSone(identity);
1843 * Notifies the core that an {@link Identity} was updated.
1845 * @param identityUpdatedEvent
1849 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1850 Identity identity = identityUpdatedEvent.identity();
1851 final Sone sone = getRemoteSone(identity.getId());
1852 if (sone.isLocal()) {
1855 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1856 soneDownloader.addSone(sone);
1857 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1861 * Notifies the core that an {@link Identity} was removed.
1863 * @param identityRemovedEvent
1867 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1868 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1869 Identity identity = identityRemovedEvent.identity();
1870 trustedIdentities.remove(ownIdentity, identity);
1871 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1872 if (trustedIdentity.getKey().equals(ownIdentity)) {
1875 if (trustedIdentity.getValue().contains(identity)) {
1879 Optional<Sone> sone = getSone(identity.getId());
1880 if (!sone.isPresent()) {
1881 /* TODO - we don’t have the Sone anymore. should this happen? */
1884 database.removePosts(sone.get());
1885 for (Post post : sone.get().getPosts()) {
1886 eventBus.post(new PostRemovedEvent(post));
1888 database.removePostReplies(sone.get());
1889 for (PostReply reply : sone.get().getReplies()) {
1890 eventBus.post(new PostReplyRemovedEvent(reply));
1892 // TODO – implement in database
1893 // sones.remove(identity.getId());
1894 eventBus.post(new SoneRemovedEvent(sone.get()));
1898 * Deletes the temporary image.
1900 * @param imageInsertFinishedEvent
1904 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1905 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1906 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1907 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1908 touchConfiguration();
1912 class MarkPostKnown implements Runnable {
1914 private final Post post;
1916 public MarkPostKnown(Post post) {
1922 markPostKnown(post);
1928 class MarkReplyKnown implements Runnable {
1930 private final PostReply postReply;
1932 public MarkReplyKnown(PostReply postReply) {
1933 this.postReply = postReply;
1938 markReplyKnown(postReply);