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.SoneChangeDetector.PostProcessor;
47 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
48 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
49 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
52 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
53 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
54 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
55 import net.pterodactylus.sone.core.event.PostRemovedEvent;
56 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneLockedEvent;
58 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
60 import net.pterodactylus.sone.data.Album;
61 import net.pterodactylus.sone.data.Client;
62 import net.pterodactylus.sone.data.Image;
63 import net.pterodactylus.sone.data.Post;
64 import net.pterodactylus.sone.data.PostReply;
65 import net.pterodactylus.sone.data.Profile;
66 import net.pterodactylus.sone.data.Profile.Field;
67 import net.pterodactylus.sone.data.Reply;
68 import net.pterodactylus.sone.data.Sone;
69 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
70 import net.pterodactylus.sone.data.Sone.SoneStatus;
71 import net.pterodactylus.sone.data.TemporaryImage;
72 import net.pterodactylus.sone.database.AlbumBuilder;
73 import net.pterodactylus.sone.database.Database;
74 import net.pterodactylus.sone.database.DatabaseException;
75 import net.pterodactylus.sone.database.ImageBuilder;
76 import net.pterodactylus.sone.database.PostBuilder;
77 import net.pterodactylus.sone.database.PostProvider;
78 import net.pterodactylus.sone.database.PostReplyBuilder;
79 import net.pterodactylus.sone.database.PostReplyProvider;
80 import net.pterodactylus.sone.database.SoneBuilder;
81 import net.pterodactylus.sone.database.SoneProvider;
82 import net.pterodactylus.sone.fcp.FcpInterface;
83 import net.pterodactylus.sone.freenet.wot.Identity;
84 import net.pterodactylus.sone.freenet.wot.IdentityManager;
85 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
91 import net.pterodactylus.sone.main.SonePlugin;
92 import net.pterodactylus.sone.utils.DefaultOption;
93 import net.pterodactylus.sone.utils.IntegerRangePredicate;
94 import net.pterodactylus.util.config.Configuration;
95 import net.pterodactylus.util.config.ConfigurationException;
96 import net.pterodactylus.util.logging.Logging;
97 import net.pterodactylus.util.number.Numbers;
98 import net.pterodactylus.util.service.AbstractService;
99 import net.pterodactylus.util.thread.NamedThreadFactory;
101 import com.google.common.annotations.VisibleForTesting;
102 import com.google.common.base.Optional;
103 import com.google.common.base.Predicates;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
111 import com.google.inject.Singleton;
116 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
119 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
122 private static final Logger logger = Logging.getLogger(Core.class);
124 /** The start time. */
125 private final long startupTime = System.currentTimeMillis();
128 private final Options options = new Options();
130 /** The preferences. */
131 private final Preferences preferences;
133 /** The event bus. */
134 private final EventBus eventBus;
136 /** The configuration. */
137 private final Configuration configuration;
139 /** Whether we’re currently saving the configuration. */
140 private boolean storingConfiguration = false;
142 /** The identity manager. */
143 private final IdentityManager identityManager;
145 /** Interface to freenet. */
146 private final FreenetInterface freenetInterface;
148 /** The Sone downloader. */
149 private final SoneDownloader soneDownloader;
151 /** The image inserter. */
152 private final ImageInserter imageInserter;
154 /** Sone downloader thread-pool. */
155 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
157 /** The update checker. */
158 private final UpdateChecker updateChecker;
160 /** The trust updater. */
161 private final WebOfTrustUpdater webOfTrustUpdater;
163 /** The FCP interface. */
164 private volatile FcpInterface fcpInterface;
166 /** The times Sones were followed. */
167 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
169 /** Locked local Sones. */
170 /* synchronize on itself. */
171 private final Set<Sone> lockedSones = new HashSet<Sone>();
173 /** Sone inserters. */
174 /* synchronize access on this on sones. */
175 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
177 /** Sone rescuers. */
178 /* synchronize access on this on sones. */
179 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
181 /** All known Sones. */
182 private final Set<String> knownSones = new HashSet<String>();
184 /** The post database. */
185 private final Database database;
187 /** All bookmarked posts. */
188 /* synchronize access on itself. */
189 private final Set<String> bookmarkedPosts = new HashSet<String>();
191 /** Trusted identities, sorted by own identities. */
192 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
194 /** All temporary images. */
195 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
197 /** Ticker for threads that mark own elements as known. */
198 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
200 /** The time the configuration was last touched. */
201 private volatile long lastConfigurationUpdate;
204 * Creates a new core.
206 * @param configuration
207 * The configuration of the core
208 * @param freenetInterface
209 * The freenet interface
210 * @param identityManager
211 * The identity manager
212 * @param webOfTrustUpdater
213 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
226 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
227 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
230 this.database = database;
231 preferences = new Preferences(this.eventBus, options);
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;
246 preferences = new Preferences(this.eventBus, options);
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 (soneRescuers) {
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);
333 public SoneBuilder soneBuilder() {
334 return database.newSoneBuilder();
341 public Collection<Sone> getSones() {
342 return database.getSones();
346 * Returns the Sone with the given ID, regardless whether it’s local or
350 * The ID of the Sone to get
351 * @return The Sone with the given ID, or {@code null} if there is no such
355 public Optional<Sone> getSone(String id) {
356 return database.getSone(id);
363 public Collection<Sone> getLocalSones() {
364 return database.getLocalSones();
368 * Returns the local Sone with the given ID, optionally creating a new Sone.
372 * @return The Sone with the given ID, or {@code null}
374 public Sone getLocalSone(String id) {
375 Optional<Sone> sone = database.getSone(id);
376 if (sone.isPresent() && sone.get().isLocal()) {
386 public Collection<Sone> getRemoteSones() {
387 return database.getRemoteSones();
391 * Returns the remote Sone with the given ID.
395 * The ID of the remote Sone to get
396 * @return The Sone with the given ID
398 public Sone getRemoteSone(String id) {
399 return database.getSone(id).orNull();
403 * Returns whether the given Sone has been modified.
406 * The Sone to check for modifications
407 * @return {@code true} if a modification has been detected in the Sone,
408 * {@code false} otherwise
410 public boolean isModifiedSone(Sone sone) {
411 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
415 * Returns the time when the given was first followed by any local Sone.
418 * The Sone to get the time for
419 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
420 * been followed, or {@link Long#MAX_VALUE}
422 public long getSoneFollowingTime(Sone sone) {
423 synchronized (soneFollowingTimes) {
424 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
429 * Returns a post builder.
431 * @return A new post builder
433 public PostBuilder postBuilder() {
434 return database.newPostBuilder();
441 public Optional<Post> getPost(String postId) {
442 return database.getPost(postId);
449 public Collection<Post> getPosts(String soneId) {
450 return database.getPosts(soneId);
457 public Collection<Post> getDirectedPosts(final String recipientId) {
458 checkNotNull(recipientId, "recipient must not be null");
459 return database.getDirectedPosts(recipientId);
463 * Returns a post reply builder.
465 * @return A new post reply builder
467 public PostReplyBuilder postReplyBuilder() {
468 return database.newPostReplyBuilder();
475 public Optional<PostReply> getPostReply(String replyId) {
476 return database.getPostReply(replyId);
483 public List<PostReply> getReplies(final String postId) {
484 return database.getReplies(postId);
488 * Returns all Sones that have liked the given post.
491 * The post to get the liking Sones for
492 * @return The Sones that like the given post
494 public Set<Sone> getLikes(Post post) {
495 Set<Sone> sones = new HashSet<Sone>();
496 for (Sone sone : getSones()) {
497 if (sone.getLikedPostIds().contains(post.getId())) {
505 * Returns all Sones that have liked the given reply.
508 * The reply to get the liking Sones for
509 * @return The Sones that like the given reply
511 public Set<Sone> getLikes(PostReply reply) {
512 Set<Sone> sones = new HashSet<Sone>();
513 for (Sone sone : getSones()) {
514 if (sone.getLikedReplyIds().contains(reply.getId())) {
522 * Returns whether the given post is bookmarked.
526 * @return {@code true} if the given post is bookmarked, {@code false}
529 public boolean isBookmarked(Post post) {
530 return isPostBookmarked(post.getId());
534 * Returns whether the post with the given ID is bookmarked.
537 * The ID of the post to check
538 * @return {@code true} if the post with the given ID is bookmarked,
539 * {@code false} otherwise
541 public boolean isPostBookmarked(String id) {
542 synchronized (bookmarkedPosts) {
543 return bookmarkedPosts.contains(id);
548 * Returns all currently known bookmarked posts.
550 * @return All bookmarked posts
552 public Set<Post> getBookmarkedPosts() {
553 Set<Post> posts = new HashSet<Post>();
554 synchronized (bookmarkedPosts) {
555 for (String bookmarkedPostId : bookmarkedPosts) {
556 Optional<Post> post = getPost(bookmarkedPostId);
557 if (post.isPresent()) {
558 posts.add(post.get());
565 public AlbumBuilder albumBuilder() {
566 return database.newAlbumBuilder();
570 * Returns the album with the given ID, optionally creating a new album if
571 * an album with the given ID can not be found.
574 * The ID of the album
575 * @return The album with the given ID, or {@code null} if no album with the
578 public Album getAlbum(String albumId) {
579 return database.getAlbum(albumId).orNull();
582 public ImageBuilder imageBuilder() {
583 return database.newImageBuilder();
587 * Returns the image with the given ID, creating it if necessary.
590 * The ID of the image
591 * @return The image with the given ID
593 public Image getImage(String imageId) {
594 return getImage(imageId, true);
598 * Returns the image with the given ID, optionally creating it if it does
602 * The ID of the image
604 * {@code true} to create an image if none exists with the given
606 * @return The image with the given ID, or {@code null} if none exists and
609 public Image getImage(String imageId, boolean create) {
610 Optional<Image> image = database.getImage(imageId);
611 if (image.isPresent()) {
617 Image newImage = database.newImageBuilder().withId(imageId).build();
618 database.storeImage(newImage);
623 * Returns the temporary image with the given ID.
626 * The ID of the temporary image
627 * @return The temporary image, or {@code null} if there is no temporary
628 * image with the given ID
630 public TemporaryImage getTemporaryImage(String imageId) {
631 synchronized (temporaryImages) {
632 return temporaryImages.get(imageId);
641 * Locks the given Sone. A locked Sone will not be inserted by
642 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
648 public void lockSone(Sone sone) {
649 synchronized (lockedSones) {
650 if (lockedSones.add(sone)) {
651 eventBus.post(new SoneLockedEvent(sone));
657 * Unlocks the given Sone.
659 * @see #lockSone(Sone)
663 public void unlockSone(Sone sone) {
664 synchronized (lockedSones) {
665 if (lockedSones.remove(sone)) {
666 eventBus.post(new SoneUnlockedEvent(sone));
672 * Adds a local Sone from the given own identity.
675 * The own identity to create a Sone from
676 * @return The added (or already existing) Sone
678 public Sone addLocalSone(OwnIdentity ownIdentity) {
679 if (ownIdentity == null) {
680 logger.log(Level.WARNING, "Given OwnIdentity is null!");
683 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
684 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
685 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
686 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
688 /* TODO - load posts ’n stuff */
689 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
690 eventBus.register(soneInserter);
691 synchronized (soneInserters) {
692 soneInserters.put(sone, soneInserter);
695 sone.setStatus(SoneStatus.idle);
696 soneInserter.start();
701 * Creates a new Sone for the given own identity.
704 * The own identity to create a Sone for
705 * @return The created Sone
707 public Sone createSone(OwnIdentity ownIdentity) {
708 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
709 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
712 Sone sone = addLocalSone(ownIdentity);
714 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
715 touchConfiguration();
720 * Adds the Sone of the given identity.
723 * The identity whose Sone to add
724 * @return The added or already existing Sone
726 public Sone addRemoteSone(Identity identity) {
727 if (identity == null) {
728 logger.log(Level.WARNING, "Given Identity is null!");
731 final Long latestEdition = tryParse(fromNullable(
732 identity.getProperty("Sone.LatestEdition")).or("0"));
733 Optional<Sone> existingSone = getSone(identity.getId());
734 if (existingSone.isPresent() && existingSone.get().isLocal()) {
735 return existingSone.get();
737 boolean newSone = !existingSone.isPresent();
738 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
739 sone.setLatestEdition(latestEdition);
741 synchronized (knownSones) {
742 newSone = !knownSones.contains(sone.getId());
744 sone.setKnown(!newSone);
746 eventBus.post(new NewSoneFoundEvent(sone));
747 for (Sone localSone : getLocalSones()) {
748 if (localSone.getOptions().isAutoFollow()) {
749 followSone(localSone, sone.getId());
754 database.storeSone(sone);
755 soneDownloader.addSone(sone);
756 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
761 * Lets the given local Sone follow the Sone with the given ID.
764 * The local Sone that should follow another Sone
766 * The ID of the Sone to follow
768 public void followSone(Sone sone, String soneId) {
769 checkNotNull(sone, "sone must not be null");
770 checkNotNull(soneId, "soneId must not be null");
771 sone.addFriend(soneId);
772 synchronized (soneFollowingTimes) {
773 if (!soneFollowingTimes.containsKey(soneId)) {
774 long now = System.currentTimeMillis();
775 soneFollowingTimes.put(soneId, now);
776 Optional<Sone> followedSone = getSone(soneId);
777 if (!followedSone.isPresent()) {
780 for (Post post : followedSone.get().getPosts()) {
781 if (post.getTime() < now) {
785 for (PostReply reply : followedSone.get().getReplies()) {
786 if (reply.getTime() < now) {
787 markReplyKnown(reply);
792 touchConfiguration();
796 * Lets the given local Sone unfollow the Sone with the given ID.
799 * The local Sone that should unfollow another Sone
801 * The ID of the Sone being unfollowed
803 public void unfollowSone(Sone sone, String soneId) {
804 checkNotNull(sone, "sone must not be null");
805 checkNotNull(soneId, "soneId must not be null");
806 sone.removeFriend(soneId);
807 boolean unfollowedSoneStillFollowed = false;
808 for (Sone localSone : getLocalSones()) {
809 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
811 if (!unfollowedSoneStillFollowed) {
812 synchronized (soneFollowingTimes) {
813 soneFollowingTimes.remove(soneId);
816 touchConfiguration();
820 * Sets the trust value of the given origin Sone for the target Sone.
827 * The trust value (from {@code -100} to {@code 100})
829 public void setTrust(Sone origin, Sone target, int trustValue) {
830 checkNotNull(origin, "origin must not be null");
831 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
832 checkNotNull(target, "target must not be null");
833 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
834 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
838 * Removes any trust assignment for the given target Sone.
845 public void removeTrust(Sone origin, Sone target) {
846 checkNotNull(origin, "origin must not be null");
847 checkNotNull(target, "target must not be null");
848 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
849 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
853 * Assigns the configured positive trust value for the given target.
860 public void trustSone(Sone origin, Sone target) {
861 setTrust(origin, target, preferences.getPositiveTrust());
865 * Assigns the configured negative trust value for the given target.
872 public void distrustSone(Sone origin, Sone target) {
873 setTrust(origin, target, preferences.getNegativeTrust());
877 * Removes the trust assignment for the given target.
884 public void untrustSone(Sone origin, Sone target) {
885 removeTrust(origin, target);
889 * Updates the stored Sone with the given Sone.
894 public void updateSone(Sone sone) {
895 updateSone(sone, false);
899 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
900 * {@code true}, an older Sone than the current Sone can be given to restore
905 * @param soneRescueMode
906 * {@code true} if the stored Sone should be updated regardless
907 * of the age of the given Sone
909 public void updateSone(final Sone sone, boolean soneRescueMode) {
910 Optional<Sone> storedSone = getSone(sone.getId());
911 if (storedSone.isPresent()) {
912 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
913 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
916 /* find removed posts. */
917 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
918 soneChangeDetector.onNewPosts(new PostProcessor() {
920 public void processPost(Post post) {
921 if (post.getTime() < getSoneFollowingTime(sone)) {
923 } else if (!post.isKnown()) {
924 eventBus.post(new NewPostFoundEvent(post));
928 soneChangeDetector.onRemovedPosts(new PostProcessor() {
930 public void processPost(Post post) {
931 eventBus.post(new PostRemovedEvent(post));
934 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
936 public void processPostReply(PostReply postReply) {
937 if (postReply.getTime() < getSoneFollowingTime(sone)) {
938 postReply.setKnown(true);
939 } else if (!postReply.isKnown()) {
940 eventBus.post(new NewPostReplyFoundEvent(postReply));
944 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
946 public void processPostReply(PostReply postReply) {
947 eventBus.post(new PostReplyRemovedEvent(postReply));
950 soneChangeDetector.detectChanges(sone);
951 database.storeSone(sone);
952 sone.setOptions(storedSone.get().getOptions());
953 sone.setKnown(storedSone.get().isKnown());
954 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
955 if (sone.isLocal()) {
956 touchConfiguration();
962 * Deletes the given Sone. This will remove the Sone from the
963 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
964 * remove the context from its identity.
969 public void deleteSone(Sone sone) {
970 if (!(sone.getIdentity() instanceof OwnIdentity)) {
971 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
974 if (!getLocalSones().contains(sone)) {
975 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
978 // FIXME – implement in database
979 // sones.remove(sone.getId());
980 SoneInserter soneInserter = soneInserters.remove(sone);
982 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
983 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
985 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
986 } catch (ConfigurationException ce1) {
987 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
992 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
993 * known} before, a {@link MarkSoneKnownEvent} is fired.
996 * The Sone to mark as known
998 public void markSoneKnown(Sone sone) {
999 if (!sone.isKnown()) {
1000 sone.setKnown(true);
1001 synchronized (knownSones) {
1002 knownSones.add(sone.getId());
1004 eventBus.post(new MarkSoneKnownEvent(sone));
1005 touchConfiguration();
1010 * Loads and updates the given Sone from the configuration. If any error is
1011 * encountered, loading is aborted and the given Sone is not changed.
1014 * The Sone to load and update
1016 public void loadSone(Sone sone) {
1017 if (!sone.isLocal()) {
1018 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1021 logger.info(String.format("Loading local Sone: %s", sone));
1024 String sonePrefix = "Sone/" + sone.getId();
1025 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1026 if (soneTime == null) {
1027 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1030 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1033 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1034 Profile profile = configurationSoneParser.parseProfile();
1037 Collection<Post> posts;
1039 posts = configurationSoneParser.parsePosts(database);
1040 } catch (InvalidPostFound ipf) {
1041 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1046 Collection<PostReply> replies;
1048 replies = configurationSoneParser.parsePostReplies(database);
1049 } catch (InvalidPostReplyFound iprf) {
1050 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1054 /* load post likes. */
1055 Set<String> likedPostIds =
1056 configurationSoneParser.parseLikedPostIds();
1058 /* load reply likes. */
1059 Set<String> likedReplyIds =
1060 configurationSoneParser.parseLikedPostReplyIds();
1063 Set<String> friends = configurationSoneParser.parseFriends();
1066 List<Album> topLevelAlbums;
1069 configurationSoneParser.parseTopLevelAlbums(database);
1070 } catch (InvalidAlbumFound iaf) {
1071 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1073 } catch (InvalidParentAlbumFound ipaf) {
1074 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1075 ipaf.getAlbumParentId()));
1081 configurationSoneParser.parseImages(database);
1082 } catch (InvalidImageFound iif) {
1083 logger.log(WARNING, "Invalid image found, aborting load!");
1085 } catch (InvalidParentAlbumFound ipaf) {
1086 logger.log(Level.WARNING,
1087 format("Invalid album image (%s) encountered, aborting load!",
1088 ipaf.getAlbumParentId()));
1093 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1094 if (avatarId != null) {
1095 final Map<String, Image> images =
1096 configurationSoneParser.getImages();
1097 profile.setAvatar(images.get(avatarId));
1101 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1102 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1103 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1104 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1105 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1106 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1108 /* if we’re still here, Sone was loaded successfully. */
1109 synchronized (sone) {
1110 sone.setTime(soneTime);
1111 sone.setProfile(profile);
1112 sone.setPosts(posts);
1113 sone.setReplies(replies);
1114 sone.setLikePostIds(likedPostIds);
1115 sone.setLikeReplyIds(likedReplyIds);
1116 for (String friendId : friends) {
1117 followSone(sone, friendId);
1119 for (Album album : sone.getRootAlbum().getAlbums()) {
1120 sone.getRootAlbum().removeAlbum(album);
1122 for (Album album : topLevelAlbums) {
1123 sone.getRootAlbum().addAlbum(album);
1125 database.storeSone(sone);
1126 synchronized (soneInserters) {
1127 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1130 synchronized (knownSones) {
1131 for (String friend : friends) {
1132 knownSones.add(friend);
1135 for (Post post : posts) {
1136 post.setKnown(true);
1138 for (PostReply reply : replies) {
1139 reply.setKnown(true);
1142 logger.info(String.format("Sone loaded successfully: %s", sone));
1146 * Creates a new post.
1149 * The Sone that creates the post
1151 * The recipient Sone, or {@code null} if this post does not have
1154 * The text of the post
1155 * @return The created post
1157 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1158 return createPost(sone, recipient, System.currentTimeMillis(), text);
1162 * Creates a new post.
1165 * The Sone that creates the post
1167 * The recipient Sone, or {@code null} if this post does not have
1170 * The time of the post
1172 * The text of the post
1173 * @return The created post
1175 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1176 checkNotNull(text, "text must not be null");
1177 checkArgument(text.trim().length() > 0, "text must not be empty");
1178 if (!sone.isLocal()) {
1179 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1182 PostBuilder postBuilder = database.newPostBuilder();
1183 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1184 if (recipient.isPresent()) {
1185 postBuilder.to(recipient.get().getId());
1187 final Post post = postBuilder.build();
1188 database.storePost(post);
1189 eventBus.post(new NewPostFoundEvent(post));
1191 touchConfiguration();
1192 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1197 * Deletes the given post.
1200 * The post to delete
1202 public void deletePost(Post post) {
1203 if (!post.getSone().isLocal()) {
1204 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1207 database.removePost(post);
1208 eventBus.post(new PostRemovedEvent(post));
1209 markPostKnown(post);
1210 touchConfiguration();
1214 * Marks the given post as known, if it is currently not a known post
1215 * (according to {@link Post#isKnown()}).
1218 * The post to mark as known
1220 public void markPostKnown(Post post) {
1221 post.setKnown(true);
1222 eventBus.post(new MarkPostKnownEvent(post));
1223 touchConfiguration();
1224 for (PostReply reply : getReplies(post.getId())) {
1225 markReplyKnown(reply);
1230 * Bookmarks the post with the given ID.
1233 * The ID of the post to bookmark
1235 public void bookmarkPost(String id) {
1236 synchronized (bookmarkedPosts) {
1237 bookmarkedPosts.add(id);
1242 * Removes the given post from the bookmarks.
1245 * The post to unbookmark
1247 public void unbookmark(Post post) {
1248 unbookmarkPost(post.getId());
1252 * Removes the post with the given ID from the bookmarks.
1255 * The ID of the post to unbookmark
1257 public void unbookmarkPost(String id) {
1258 synchronized (bookmarkedPosts) {
1259 bookmarkedPosts.remove(id);
1264 * Creates a new reply.
1267 * The Sone that creates the reply
1269 * The post that this reply refers to
1271 * The text of the reply
1272 * @return The created reply
1274 public PostReply createReply(Sone sone, Post post, 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 reply for non-local Sone: %s", sone));
1281 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1282 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1283 final PostReply reply = postReplyBuilder.build();
1284 database.storePostReply(reply);
1285 eventBus.post(new NewPostReplyFoundEvent(reply));
1286 sone.addReply(reply);
1287 touchConfiguration();
1288 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1293 * Deletes the given reply.
1296 * The reply to delete
1298 public void deleteReply(PostReply reply) {
1299 Sone sone = reply.getSone();
1300 if (!sone.isLocal()) {
1301 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1304 database.removePostReply(reply);
1305 markReplyKnown(reply);
1306 sone.removeReply(reply);
1307 touchConfiguration();
1311 * Marks the given reply as known, if it is currently not a known reply
1312 * (according to {@link Reply#isKnown()}).
1315 * The reply to mark as known
1317 public void markReplyKnown(PostReply reply) {
1318 boolean previouslyKnown = reply.isKnown();
1319 reply.setKnown(true);
1320 eventBus.post(new MarkPostReplyKnownEvent(reply));
1321 if (!previouslyKnown) {
1322 touchConfiguration();
1327 * Creates a new album for the given Sone.
1330 * The Sone to create the album for
1332 * The parent of the album (may be {@code null} to create a
1334 * @return The new album
1336 public Album createAlbum(Sone sone, Album parent) {
1337 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1338 database.storeAlbum(album);
1339 parent.addAlbum(album);
1344 * Deletes the given album. The owner of the album has to be a local Sone,
1345 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1348 * The album to remove
1350 public void deleteAlbum(Album album) {
1351 checkNotNull(album, "album must not be null");
1352 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1353 if (!album.isEmpty()) {
1356 album.getParent().removeAlbum(album);
1357 database.removeAlbum(album);
1358 touchConfiguration();
1362 * Creates a new image.
1365 * The Sone creating the image
1367 * The album the image will be inserted into
1368 * @param temporaryImage
1369 * The temporary image to create the image from
1370 * @return The newly created image
1372 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1373 checkNotNull(sone, "sone must not be null");
1374 checkNotNull(album, "album must not be null");
1375 checkNotNull(temporaryImage, "temporaryImage must not be null");
1376 checkArgument(sone.isLocal(), "sone must be a local Sone");
1377 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1378 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1379 album.addImage(image);
1380 database.storeImage(image);
1381 imageInserter.insertImage(temporaryImage, image);
1386 * Deletes the given image. This method will also delete a matching
1389 * @see #deleteTemporaryImage(String)
1391 * The image to delete
1393 public void deleteImage(Image image) {
1394 checkNotNull(image, "image must not be null");
1395 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1396 deleteTemporaryImage(image.getId());
1397 image.getAlbum().removeImage(image);
1398 database.removeImage(image);
1399 touchConfiguration();
1403 * Creates a new temporary image.
1406 * The MIME type of the temporary image
1408 * The encoded data of the image
1409 * @return The temporary image
1411 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1412 TemporaryImage temporaryImage = new TemporaryImage();
1413 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1414 synchronized (temporaryImages) {
1415 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1417 return temporaryImage;
1421 * Deletes the temporary image with the given ID.
1424 * The ID of the temporary image to delete
1426 public void deleteTemporaryImage(String imageId) {
1427 checkNotNull(imageId, "imageId must not be null");
1428 synchronized (temporaryImages) {
1429 temporaryImages.remove(imageId);
1431 Image image = getImage(imageId, false);
1432 if (image != null) {
1433 imageInserter.cancelImageInsert(image);
1438 * Notifies the core that the configuration, either of the core or of a
1439 * single local Sone, has changed, and that the configuration should be
1442 public void touchConfiguration() {
1443 lastConfigurationUpdate = System.currentTimeMillis();
1454 public void serviceStart() {
1455 loadConfiguration();
1456 updateChecker.start();
1457 identityManager.start();
1458 webOfTrustUpdater.init();
1459 webOfTrustUpdater.start();
1467 public void serviceRun() {
1468 long lastSaved = System.currentTimeMillis();
1469 while (!shouldStop()) {
1471 long now = System.currentTimeMillis();
1472 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1473 for (Sone localSone : getLocalSones()) {
1474 saveSone(localSone);
1476 saveConfiguration();
1486 public void serviceStop() {
1487 localElementTicker.shutdownNow();
1488 synchronized (soneInserters) {
1489 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1490 soneInserter.getValue().stop();
1491 saveSone(soneInserter.getKey());
1494 saveConfiguration();
1496 webOfTrustUpdater.stop();
1497 updateChecker.stop();
1498 soneDownloader.stop();
1499 soneDownloaders.shutdown();
1500 identityManager.stop();
1508 * Saves the given Sone. This will persist all local settings for the given
1509 * Sone, such as the friends list and similar, private options.
1514 private synchronized void saveSone(Sone sone) {
1515 if (!sone.isLocal()) {
1516 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1519 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1520 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1524 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1526 /* save Sone into configuration. */
1527 String sonePrefix = "Sone/" + sone.getId();
1528 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1529 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1532 Profile profile = sone.getProfile();
1533 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1534 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1535 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1536 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1537 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1538 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1539 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1541 /* save profile fields. */
1542 int fieldCounter = 0;
1543 for (Field profileField : profile.getFields()) {
1544 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1545 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1546 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1548 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1551 int postCounter = 0;
1552 for (Post post : sone.getPosts()) {
1553 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1554 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1555 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1556 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1557 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1559 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1562 int replyCounter = 0;
1563 for (PostReply reply : sone.getReplies()) {
1564 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1565 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1566 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1567 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1568 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1570 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1572 /* save post likes. */
1573 int postLikeCounter = 0;
1574 for (String postId : sone.getLikedPostIds()) {
1575 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1577 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1579 /* save reply likes. */
1580 int replyLikeCounter = 0;
1581 for (String replyId : sone.getLikedReplyIds()) {
1582 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1584 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1587 int friendCounter = 0;
1588 for (String friendId : sone.getFriends()) {
1589 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1591 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1593 /* save albums. first, collect in a flat structure, top-level first. */
1594 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1596 int albumCounter = 0;
1597 for (Album album : albums) {
1598 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1599 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1600 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1601 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1602 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1603 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1605 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1608 int imageCounter = 0;
1609 for (Album album : albums) {
1610 for (Image image : album.getImages()) {
1611 if (!image.isInserted()) {
1614 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1615 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1616 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1617 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1618 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1619 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1620 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1621 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1622 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1625 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1628 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1629 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1630 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1631 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1632 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1633 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1635 configuration.save();
1637 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1639 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1640 } catch (ConfigurationException ce1) {
1641 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1646 * Saves the current options.
1648 private void saveConfiguration() {
1649 synchronized (configuration) {
1650 if (storingConfiguration) {
1651 logger.log(Level.FINE, "Already storing configuration…");
1654 storingConfiguration = true;
1657 /* store the options first. */
1659 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1660 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1661 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1662 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1663 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1664 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1665 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1666 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1667 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1668 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1669 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1670 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1672 /* save known Sones. */
1673 int soneCounter = 0;
1674 synchronized (knownSones) {
1675 for (String knownSoneId : knownSones) {
1676 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1678 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1681 /* save Sone following times. */
1683 synchronized (soneFollowingTimes) {
1684 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1685 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1686 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1689 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1692 /* save known posts. */
1695 /* save bookmarked posts. */
1696 int bookmarkedPostCounter = 0;
1697 synchronized (bookmarkedPosts) {
1698 for (String bookmarkedPostId : bookmarkedPosts) {
1699 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1702 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1705 configuration.save();
1707 } catch (ConfigurationException ce1) {
1708 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1709 } catch (DatabaseException de1) {
1710 logger.log(Level.SEVERE, "Could not save database!", de1);
1712 synchronized (configuration) {
1713 storingConfiguration = false;
1719 * Loads the configuration.
1721 private void loadConfiguration() {
1722 /* create options. */
1723 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE)));
1724 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1725 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1726 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1727 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1728 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1729 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1730 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1731 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1732 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false));
1733 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2));
1735 loadConfigurationValue("InsertionDelay");
1736 loadConfigurationValue("PostsPerPage");
1737 loadConfigurationValue("ImagesPerPage");
1738 loadConfigurationValue("CharactersPerPost");
1739 loadConfigurationValue("PostCutOffLength");
1740 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1741 loadConfigurationValue("PositiveTrust");
1742 loadConfigurationValue("NegativeTrust");
1743 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1744 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1745 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1747 /* load known Sones. */
1748 int soneCounter = 0;
1750 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1751 if (knownSoneId == null) {
1754 synchronized (knownSones) {
1755 knownSones.add(knownSoneId);
1759 /* load Sone following times. */
1762 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1763 if (soneId == null) {
1766 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1767 synchronized (soneFollowingTimes) {
1768 soneFollowingTimes.put(soneId, time);
1773 /* load bookmarked posts. */
1774 int bookmarkedPostCounter = 0;
1776 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1777 if (bookmarkedPostId == null) {
1780 synchronized (bookmarkedPosts) {
1781 bookmarkedPosts.add(bookmarkedPostId);
1788 * Loads an {@link Integer} configuration value for the option with the
1789 * given name, logging validation failures.
1792 * The name of the option to load
1794 private void loadConfigurationValue(String optionName) {
1796 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1797 } catch (IllegalArgumentException iae1) {
1798 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1803 * Notifies the core that a new {@link OwnIdentity} was added.
1805 * @param ownIdentityAddedEvent
1809 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1810 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1811 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1812 if (ownIdentity.hasContext("Sone")) {
1813 addLocalSone(ownIdentity);
1818 * Notifies the core that an {@link OwnIdentity} was removed.
1820 * @param ownIdentityRemovedEvent
1824 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1825 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1826 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1827 trustedIdentities.removeAll(ownIdentity);
1831 * Notifies the core that a new {@link Identity} was added.
1833 * @param identityAddedEvent
1837 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1838 Identity identity = identityAddedEvent.identity();
1839 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1840 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1841 addRemoteSone(identity);
1845 * Notifies the core that an {@link Identity} was updated.
1847 * @param identityUpdatedEvent
1851 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1852 Identity identity = identityUpdatedEvent.identity();
1853 final Sone sone = getRemoteSone(identity.getId());
1854 if (sone.isLocal()) {
1857 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1858 soneDownloader.addSone(sone);
1859 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1863 * Notifies the core that an {@link Identity} was removed.
1865 * @param identityRemovedEvent
1869 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1870 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1871 Identity identity = identityRemovedEvent.identity();
1872 trustedIdentities.remove(ownIdentity, identity);
1873 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1874 if (trustedIdentity.getKey().equals(ownIdentity)) {
1877 if (trustedIdentity.getValue().contains(identity)) {
1881 Optional<Sone> sone = getSone(identity.getId());
1882 if (!sone.isPresent()) {
1883 /* TODO - we don’t have the Sone anymore. should this happen? */
1886 database.removePosts(sone.get());
1887 for (Post post : sone.get().getPosts()) {
1888 eventBus.post(new PostRemovedEvent(post));
1890 database.removePostReplies(sone.get());
1891 for (PostReply reply : sone.get().getReplies()) {
1892 eventBus.post(new PostReplyRemovedEvent(reply));
1894 // TODO – implement in database
1895 // sones.remove(identity.getId());
1896 eventBus.post(new SoneRemovedEvent(sone.get()));
1900 * Deletes the temporary image.
1902 * @param imageInsertFinishedEvent
1906 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1907 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1908 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1909 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1910 touchConfiguration();
1914 class MarkPostKnown implements Runnable {
1916 private final Post post;
1918 public MarkPostKnown(Post post) {
1924 markPostKnown(post);
1930 class MarkReplyKnown implements Runnable {
1932 private final PostReply postReply;
1934 public MarkReplyKnown(PostReply postReply) {
1935 this.postReply = postReply;
1940 markReplyKnown(postReply);