2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static net.pterodactylus.sone.data.Identified.GET_ID;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.net.MalformedURLException;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ScheduledExecutorService;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.core.Options.DefaultOption;
43 import net.pterodactylus.sone.core.Options.Option;
44 import net.pterodactylus.sone.core.Options.OptionWatcher;
45 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
46 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
49 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
50 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
51 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
52 import net.pterodactylus.sone.core.event.PostRemovedEvent;
53 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneLockedEvent;
55 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.database.Database;
70 import net.pterodactylus.sone.database.DatabaseException;
71 import net.pterodactylus.sone.database.PostBuilder;
72 import net.pterodactylus.sone.database.PostProvider;
73 import net.pterodactylus.sone.database.PostReplyBuilder;
74 import net.pterodactylus.sone.database.PostReplyProvider;
75 import net.pterodactylus.sone.database.SoneProvider;
76 import net.pterodactylus.sone.fcp.FcpInterface;
77 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
78 import net.pterodactylus.sone.freenet.wot.Identity;
79 import net.pterodactylus.sone.freenet.wot.IdentityManager;
80 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
86 import net.pterodactylus.sone.main.SonePlugin;
87 import net.pterodactylus.sone.utils.IntegerRangePredicate;
88 import net.pterodactylus.util.config.Configuration;
89 import net.pterodactylus.util.config.ConfigurationException;
90 import net.pterodactylus.util.logging.Logging;
91 import net.pterodactylus.util.number.Numbers;
92 import net.pterodactylus.util.service.AbstractService;
93 import net.pterodactylus.util.thread.NamedThreadFactory;
95 import freenet.keys.FreenetURI;
97 import com.google.common.base.Optional;
98 import com.google.common.base.Predicate;
99 import com.google.common.base.Predicates;
100 import com.google.common.collect.HashMultimap;
101 import com.google.common.collect.ImmutableSet;
102 import com.google.common.collect.Maps;
103 import com.google.common.collect.Multimap;
104 import com.google.common.collect.Multimaps;
105 import com.google.common.eventbus.EventBus;
106 import com.google.common.eventbus.Subscribe;
107 import com.google.inject.Inject;
112 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
114 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
117 private static final Logger logger = Logging.getLogger(Core.class);
119 /** The start time. */
120 private final long startupTime = System.currentTimeMillis();
123 private final Options options = new Options();
125 /** The preferences. */
126 private final Preferences preferences = new Preferences(options);
128 /** The event bus. */
129 private final EventBus eventBus;
131 /** The configuration. */
132 private Configuration configuration;
134 /** Whether we’re currently saving the configuration. */
135 private boolean storingConfiguration = false;
137 /** The identity manager. */
138 private final IdentityManager identityManager;
140 /** Interface to freenet. */
141 private final FreenetInterface freenetInterface;
143 /** The Sone downloader. */
144 private final SoneDownloader soneDownloader;
146 /** The image inserter. */
147 private final ImageInserter imageInserter;
149 /** Sone downloader thread-pool. */
150 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
152 /** The update checker. */
153 private final UpdateChecker updateChecker;
155 /** The trust updater. */
156 private final WebOfTrustUpdater webOfTrustUpdater;
158 /** The FCP interface. */
159 private volatile FcpInterface fcpInterface;
161 /** The times Sones were followed. */
162 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
164 /** Locked local Sones. */
165 /* synchronize on itself. */
166 private final Set<Sone> lockedSones = new HashSet<Sone>();
168 /** Sone inserters. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
172 /** Sone rescuers. */
173 /* synchronize access on this on sones. */
174 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
177 /* synchronize access on this on itself. */
178 private final Map<String, Sone> sones = new HashMap<String, Sone>();
180 /** All known Sones. */
181 private final Set<String> knownSones = new HashSet<String>();
183 /** The post database. */
184 private final Database database;
186 /** All bookmarked posts. */
187 /* synchronize access on itself. */
188 private final Set<String> bookmarkedPosts = new HashSet<String>();
190 /** Trusted identities, sorted by own identities. */
191 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
193 /** All temporary images. */
194 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
196 /** Ticker for threads that mark own elements as known. */
197 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
199 /** The time the configuration was last touched. */
200 private volatile long lastConfigurationUpdate;
203 * Creates a new core.
205 * @param configuration
206 * The configuration of the core
207 * @param freenetInterface
208 * The freenet interface
209 * @param identityManager
210 * The identity manager
211 * @param webOfTrustUpdater
212 * The WebOfTrust updater
219 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
221 this.configuration = configuration;
222 this.freenetInterface = freenetInterface;
223 this.identityManager = identityManager;
224 this.soneDownloader = new SoneDownloader(this, freenetInterface);
225 this.imageInserter = new ImageInserter(freenetInterface);
226 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
227 this.webOfTrustUpdater = webOfTrustUpdater;
228 this.eventBus = eventBus;
229 this.database = database;
237 * Returns the time Sone was started.
239 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
241 public long getStartupTime() {
246 * Sets the configuration to use. This will automatically save the current
247 * configuration to the given configuration.
249 * @param configuration
250 * The new configuration to use
252 public void setConfiguration(Configuration configuration) {
253 this.configuration = configuration;
254 touchConfiguration();
258 * Returns the options used by the core.
260 * @return The options of the core
262 public Preferences getPreferences() {
267 * Returns the identity manager used by the core.
269 * @return The identity manager
271 public IdentityManager getIdentityManager() {
272 return identityManager;
276 * Returns the update checker.
278 * @return The update checker
280 public UpdateChecker getUpdateChecker() {
281 return updateChecker;
285 * Sets the FCP interface to use.
287 * @param fcpInterface
288 * The FCP interface to use
290 public void setFcpInterface(FcpInterface fcpInterface) {
291 this.fcpInterface = fcpInterface;
295 * Returns the Sone rescuer for the given local Sone.
298 * The local Sone to get the rescuer for
299 * @return The Sone rescuer for the given Sone
301 public SoneRescuer getSoneRescuer(Sone sone) {
302 checkNotNull(sone, "sone must not be null");
303 checkArgument(sone.isLocal(), "sone must be local");
304 synchronized (sones) {
305 SoneRescuer soneRescuer = soneRescuers.get(sone);
306 if (soneRescuer == null) {
307 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
308 soneRescuers.put(sone, soneRescuer);
316 * Returns whether the given Sone is currently locked.
320 * @return {@code true} if the Sone is locked, {@code false} if it is not
322 public boolean isLocked(Sone sone) {
323 synchronized (lockedSones) {
324 return lockedSones.contains(sone);
328 /** {@inheritDocs} */
330 public Collection<Sone> getSones() {
331 synchronized (sones) {
332 return ImmutableSet.copyOf(sones.values());
337 * Returns the Sone with the given ID, regardless whether it’s local or
341 * The ID of the Sone to get
342 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Optional<Sone> getSone(String id) {
347 synchronized (sones) {
348 return Optional.fromNullable(sones.get(id));
352 /** {@inheritDocs} */
354 public Collection<Sone> getLocalSones() {
355 synchronized (sones) {
356 return from(sones.values()).filter(new Predicate<Sone>() {
359 public boolean apply(Sone sone) {
360 return sone.isLocal();
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 Optional<Sone> getLocalSone(String id) {
374 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
377 /** {@inheritDocs} */
379 public Collection<Sone> getRemoteSones() {
380 synchronized (sones) {
381 return from(sones.values()).filter(new Predicate<Sone>() {
384 public boolean apply(Sone sone) {
385 return !sone.isLocal();
392 * 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 Optional<Sone> getRemoteSone(String id) {
399 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
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, {@code
410 public boolean isModifiedSone(Sone sone) {
411 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
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 been
420 * 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 whether the target Sone is trusted by the origin Sone.
435 * @return {@code true} if the target Sone is trusted by the origin Sone
437 public boolean isSoneTrusted(Sone origin, Sone target) {
438 checkNotNull(origin, "origin must not be null");
439 checkNotNull(target, "target must not be null");
440 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
441 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
445 * Returns a post builder.
447 * @return A new post builder
449 public PostBuilder postBuilder() {
450 return database.newPostBuilder();
455 public Optional<Post> getPost(String postId) {
456 return database.getPost(postId);
459 /** {@inheritDocs} */
461 public Collection<Post> getPosts(String soneId) {
462 return database.getPosts(soneId);
467 public Collection<Post> getDirectedPosts(final String recipientId) {
468 checkNotNull(recipientId, "recipient must not be null");
469 return database.getDirectedPosts(recipientId);
473 * Returns a post reply builder.
475 * @return A new post reply builder
477 public PostReplyBuilder postReplyBuilder() {
478 return database.newPostReplyBuilder();
483 public Optional<PostReply> getPostReply(String replyId) {
484 return database.getPostReply(replyId);
489 public List<PostReply> getReplies(final String postId) {
490 return database.getReplies(postId);
494 * Returns all Sones that have liked the given post.
497 * The post to get the liking Sones for
498 * @return The Sones that like the given post
500 public Set<Sone> getLikes(Post post) {
501 Set<Sone> sones = new HashSet<Sone>();
502 for (Sone sone : getSones()) {
503 if (sone.getLikedPostIds().contains(post.getId())) {
511 * Returns all Sones that have liked the given reply.
514 * The reply to get the liking Sones for
515 * @return The Sones that like the given reply
517 public Set<Sone> getLikes(PostReply reply) {
518 Set<Sone> sones = new HashSet<Sone>();
519 for (Sone sone : getSones()) {
520 if (sone.getLikedReplyIds().contains(reply.getId())) {
528 * Returns whether the given post is bookmarked.
532 * @return {@code true} if the given post is bookmarked, {@code false}
535 public boolean isBookmarked(Post post) {
536 return isPostBookmarked(post.getId());
540 * Returns whether the post with the given ID is bookmarked.
543 * The ID of the post to check
544 * @return {@code true} if the post with the given ID is bookmarked, {@code
547 public boolean isPostBookmarked(String id) {
548 synchronized (bookmarkedPosts) {
549 return bookmarkedPosts.contains(id);
554 * Returns all currently known bookmarked posts.
556 * @return All bookmarked posts
558 public Set<Post> getBookmarkedPosts() {
559 Set<Post> posts = new HashSet<Post>();
560 synchronized (bookmarkedPosts) {
561 for (String bookmarkedPostId : bookmarkedPosts) {
562 Optional<Post> post = getPost(bookmarkedPostId);
563 if (post.isPresent()) {
564 posts.add(post.get());
571 public Optional<Album> getAlbum(String albumId) {
572 return database.getAlbum(albumId);
575 public Optional<Image> getImage(String imageId) {
576 return database.getImage(imageId);
580 * Returns the temporary image with the given ID.
583 * The ID of the temporary image
584 * @return The temporary image, or {@code null} if there is no temporary image
587 public TemporaryImage getTemporaryImage(String imageId) {
588 synchronized (temporaryImages) {
589 return temporaryImages.get(imageId);
598 * Locks the given Sone. A locked Sone will not be inserted by {@link
599 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
604 public void lockSone(Sone sone) {
605 synchronized (lockedSones) {
606 if (lockedSones.add(sone)) {
607 eventBus.post(new SoneLockedEvent(sone));
613 * Unlocks the given Sone.
617 * @see #lockSone(Sone)
619 public void unlockSone(Sone sone) {
620 synchronized (lockedSones) {
621 if (lockedSones.remove(sone)) {
622 eventBus.post(new SoneUnlockedEvent(sone));
628 * Adds a local Sone from the given own identity.
631 * The own identity to create a Sone from
632 * @return The added (or already existing) Sone
634 public Sone addLocalSone(OwnIdentity ownIdentity) {
635 if (ownIdentity == null) {
636 logger.log(Level.WARNING, "Given OwnIdentity is null!");
639 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
640 synchronized (sones) {
643 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
644 } catch (MalformedURLException mue1) {
645 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
648 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
649 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
651 /* TODO - load posts ’n stuff */
652 sones.put(ownIdentity.getId(), sone);
653 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
654 soneInserters.put(sone, soneInserter);
655 sone.setStatus(SoneStatus.idle);
657 soneInserter.start();
663 * Creates a new Sone for the given own identity.
666 * The own identity to create a Sone for
667 * @return The created Sone
669 public Sone createSone(OwnIdentity ownIdentity) {
670 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
671 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
674 Sone sone = addLocalSone(ownIdentity);
675 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
676 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
677 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
678 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
679 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
680 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
682 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
683 touchConfiguration();
688 * Adds the Sone of the given identity.
691 * The identity whose Sone to add
692 * @return The added or already existing Sone
694 public Sone addRemoteSone(Identity identity) {
695 if (identity == null) {
696 logger.log(Level.WARNING, "Given Identity is null!");
699 synchronized (sones) {
700 final Sone sone = database.newSoneBuilder().by(identity).build();
701 if (sone.isLocal()) {
704 sone.setIdentity(identity);
705 boolean newSone = sone.getRequestUri() == null;
706 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
707 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
709 synchronized (knownSones) {
710 newSone = !knownSones.contains(sone.getId());
712 sone.setKnown(!newSone);
714 eventBus.post(new NewSoneFoundEvent(sone));
715 for (Sone localSone : getLocalSones()) {
716 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
717 followSone(localSone, sone.getId());
722 soneDownloader.addSone(sone);
723 soneDownloaders.execute(new Runnable() {
726 @SuppressWarnings("synthetic-access")
728 soneDownloader.fetchSone(sone, sone.getRequestUri());
737 * Lets the given local Sone follow the Sone with the given ID.
740 * The local Sone that should follow another Sone
742 * The ID of the Sone to follow
744 public void followSone(Sone sone, String soneId) {
745 checkNotNull(sone, "sone must not be null");
746 checkNotNull(soneId, "soneId must not be null");
747 sone.addFriend(soneId);
748 synchronized (soneFollowingTimes) {
749 if (!soneFollowingTimes.containsKey(soneId)) {
750 long now = System.currentTimeMillis();
751 soneFollowingTimes.put(soneId, now);
752 Optional<Sone> followedSone = getSone(soneId);
753 if (!followedSone.isPresent()) {
756 for (Post post : followedSone.get().getPosts()) {
757 if (post.getTime() < now) {
761 for (PostReply reply : followedSone.get().getReplies()) {
762 if (reply.getTime() < now) {
763 markReplyKnown(reply);
768 touchConfiguration();
772 * Lets the given local Sone unfollow the Sone with the given ID.
775 * The local Sone that should unfollow another Sone
777 * The ID of the Sone being unfollowed
779 public void unfollowSone(Sone sone, String soneId) {
780 checkNotNull(sone, "sone must not be null");
781 checkNotNull(soneId, "soneId must not be null");
782 sone.removeFriend(soneId);
783 boolean unfollowedSoneStillFollowed = false;
784 for (Sone localSone : getLocalSones()) {
785 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
787 if (!unfollowedSoneStillFollowed) {
788 synchronized (soneFollowingTimes) {
789 soneFollowingTimes.remove(soneId);
792 touchConfiguration();
796 * Sets the trust value of the given origin Sone for the target Sone.
803 * The trust value (from {@code -100} to {@code 100})
805 public void setTrust(Sone origin, Sone target, int trustValue) {
806 checkNotNull(origin, "origin must not be null");
807 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
808 checkNotNull(target, "target must not be null");
809 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
810 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
814 * Removes any trust assignment for the given target Sone.
821 public void removeTrust(Sone origin, Sone target) {
822 checkNotNull(origin, "origin must not be null");
823 checkNotNull(target, "target must not be null");
824 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
825 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
829 * Assigns the configured positive trust value for the given target.
836 public void trustSone(Sone origin, Sone target) {
837 setTrust(origin, target, preferences.getPositiveTrust());
841 * Assigns the configured negative trust value for the given target.
848 public void distrustSone(Sone origin, Sone target) {
849 setTrust(origin, target, preferences.getNegativeTrust());
853 * Removes the trust assignment for the given target.
860 public void untrustSone(Sone origin, Sone target) {
861 removeTrust(origin, target);
865 * Updates the stored Sone with the given Sone.
870 public void updateSone(Sone sone) {
871 updateSone(sone, false);
875 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
876 * {@code true}, an older Sone than the current Sone can be given to restore an
881 * @param soneRescueMode
882 * {@code true} if the stored Sone should be updated regardless of the age of
885 public void updateSone(Sone sone, boolean soneRescueMode) {
886 Optional<Sone> storedSone = getSone(sone.getId());
887 if (storedSone.isPresent()) {
888 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
889 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
892 /* find removed posts. */
893 Collection<Post> existingPosts = database.getPosts(sone.getId());
894 for (Post oldPost : existingPosts) {
895 if (!sone.getPosts().contains(oldPost)) {
896 eventBus.post(new PostRemovedEvent(oldPost));
899 /* find new posts. */
900 for (Post newPost : sone.getPosts()) {
901 if (existingPosts.contains(newPost)) {
904 if (newPost.getTime() < getSoneFollowingTime(sone)) {
905 newPost.setKnown(true);
906 } else if (!newPost.isKnown()) {
907 eventBus.post(new NewPostFoundEvent(newPost));
911 database.storePosts(sone, sone.getPosts());
912 if (!soneRescueMode) {
913 for (PostReply reply : storedSone.get().getReplies()) {
914 if (!sone.getReplies().contains(reply)) {
915 eventBus.post(new PostReplyRemovedEvent(reply));
919 Set<PostReply> storedReplies = storedSone.get().getReplies();
920 for (PostReply reply : sone.getReplies()) {
921 if (storedReplies.contains(reply)) {
924 if (reply.getTime() < getSoneFollowingTime(sone)) {
925 reply.setKnown(true);
926 } else if (!reply.isKnown()) {
927 eventBus.post(new NewPostReplyFoundEvent(reply));
930 database.storePostReplies(sone, sone.getReplies());
931 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
932 database.removeAlbum(album);
933 for (Image image : album.getImages()) {
934 database.removeImage(image);
937 for (Album album : sone.getRootAlbum().getAlbums()) {
938 database.storeAlbum(album);
939 for (Image image : album.getImages()) {
940 database.storeImage(image);
943 synchronized (sones) {
944 sone.setOptions(storedSone.get().getOptions());
945 sone.setKnown(storedSone.get().isKnown());
946 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
947 if (sone.isLocal()) {
948 soneInserters.get(storedSone.get()).setSone(sone);
949 touchConfiguration();
951 sones.put(sone.getId(), sone);
957 * Deletes the given Sone. This will remove the Sone from the {@link
958 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
959 * context from its identity.
964 public void deleteSone(Sone sone) {
965 if (!(sone.getIdentity() instanceof OwnIdentity)) {
966 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
969 synchronized (sones) {
970 if (!getLocalSones().contains(sone)) {
971 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
974 sones.remove(sone.getId());
975 SoneInserter soneInserter = soneInserters.remove(sone);
978 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
979 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
981 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
982 } catch (ConfigurationException ce1) {
983 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
988 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
989 * known} before, a {@link MarkSoneKnownEvent} is fired.
992 * The Sone to mark as known
994 public void markSoneKnown(Sone sone) {
995 if (!sone.isKnown()) {
997 synchronized (knownSones) {
998 knownSones.add(sone.getId());
1000 eventBus.post(new MarkSoneKnownEvent(sone));
1001 touchConfiguration();
1006 * Loads and updates the given Sone from the configuration. If any error is
1007 * encountered, loading is aborted and the given Sone is not changed.
1010 * The Sone to load and update
1012 public void loadSone(Sone sone) {
1013 if (!sone.isLocal()) {
1014 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1017 logger.info(String.format("Loading local Sone: %s", sone));
1019 /* initialize options. */
1020 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1021 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1022 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1023 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1024 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1025 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1028 String sonePrefix = "Sone/" + sone.getId();
1029 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1030 if (soneTime == null) {
1031 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1034 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1037 Profile profile = new Profile(sone);
1038 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1039 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1040 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1041 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1042 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1043 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1045 /* load profile fields. */
1047 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1048 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1049 if (fieldName == null) {
1052 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1053 profile.addField(fieldName).setValue(fieldValue);
1057 Set<Post> posts = new HashSet<Post>();
1059 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1060 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1061 if (postId == null) {
1064 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1065 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1066 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1067 if ((postTime == 0) || (postText == null)) {
1068 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1071 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1072 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1073 postBuilder.to(postRecipientId);
1075 posts.add(postBuilder.build());
1079 Set<PostReply> replies = new HashSet<PostReply>();
1081 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1082 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1083 if (replyId == null) {
1086 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1087 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1088 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1089 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1090 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1093 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1094 replies.add(postReplyBuilder.build());
1097 /* load post likes. */
1098 Set<String> likedPostIds = new HashSet<String>();
1100 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1101 if (likedPostId == null) {
1104 likedPostIds.add(likedPostId);
1107 /* load reply likes. */
1108 Set<String> likedReplyIds = new HashSet<String>();
1110 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1111 if (likedReplyId == null) {
1114 likedReplyIds.add(likedReplyId);
1118 Set<String> friends = new HashSet<String>();
1120 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1121 if (friendId == null) {
1124 friends.add(friendId);
1128 Map<String, Album> albums = Maps.newHashMap();
1129 int albumCounter = 0;
1131 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1132 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1133 if (albumId == null) {
1136 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1137 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1138 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1139 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1140 if ((albumTitle == null) || (albumDescription == null)) {
1141 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1144 Album parentAlbum = sone.getRootAlbum();
1145 if (albumParentId != null) {
1146 parentAlbum = albums.get(albumParentId);
1148 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1149 albums.put(album.getId(), album);
1153 int imageCounter = 0;
1155 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1156 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1157 if (imageId == null) {
1160 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1161 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1162 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1163 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1164 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1165 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1166 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1167 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1168 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1171 Album album = albums.get(albumId);
1172 if (album == null) {
1173 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1176 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1180 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1181 if (avatarId != null) {
1182 profile.setAvatar(getImage(avatarId).orNull());
1186 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1187 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1188 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1189 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1190 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1191 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1193 /* if we’re still here, Sone was loaded successfully. */
1194 synchronized (sone) {
1195 sone.setTime(soneTime);
1196 sone.setProfile(profile);
1197 sone.setPosts(posts);
1198 sone.setReplies(replies);
1199 sone.setLikePostIds(likedPostIds);
1200 sone.setLikeReplyIds(likedReplyIds);
1201 for (String friendId : friends) {
1202 followSone(sone, friendId);
1204 for (Album album : sone.getRootAlbum().getAlbums()) {
1207 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1209 synchronized (knownSones) {
1210 for (String friend : friends) {
1211 knownSones.add(friend);
1214 database.storePosts(sone, posts);
1215 for (Post post : posts) {
1216 post.setKnown(true);
1218 database.storePostReplies(sone, replies);
1219 for (PostReply reply : replies) {
1220 reply.setKnown(true);
1223 logger.info(String.format("Sone loaded successfully: %s", sone));
1227 * Creates a new post.
1230 * The Sone that creates the post
1232 * The text of the post
1233 * @return The created post
1235 public Post createPost(Sone sone, String text) {
1236 return createPost(sone, System.currentTimeMillis(), text);
1240 * Creates a new post.
1243 * The Sone that creates the post
1245 * The time of the post
1247 * The text of the post
1248 * @return The created post
1250 public Post createPost(Sone sone, long time, String text) {
1251 return createPost(sone, null, time, text);
1255 * Creates a new post.
1258 * The Sone that creates the post
1260 * The recipient Sone, or {@code null} if this post does not have a
1263 * The text of the post
1264 * @return The created post
1266 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1267 return createPost(sone, recipient, System.currentTimeMillis(), text);
1271 * Creates a new post.
1274 * The Sone that creates the post
1276 * The recipient Sone, or {@code null} if this post does not have a
1279 * The time of the post
1281 * The text of the post
1282 * @return The created post
1284 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1285 checkNotNull(text, "text must not be null");
1286 checkArgument(text.trim().length() > 0, "text must not be empty");
1287 if (!sone.isLocal()) {
1288 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1291 PostBuilder postBuilder = database.newPostBuilder();
1292 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1293 if (recipient.isPresent()) {
1294 postBuilder.to(recipient.get().getId());
1296 final Post post = postBuilder.build();
1297 database.storePost(post);
1298 eventBus.post(new NewPostFoundEvent(post));
1300 touchConfiguration();
1301 localElementTicker.schedule(new Runnable() {
1308 markPostKnown(post);
1310 }, 10, TimeUnit.SECONDS);
1315 * Deletes the given post.
1318 * The post to delete
1320 public void deletePost(Post post) {
1321 if (!post.getSone().isLocal()) {
1322 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1325 database.removePost(post);
1326 eventBus.post(new PostRemovedEvent(post));
1327 markPostKnown(post);
1328 touchConfiguration();
1332 * Marks the given post as known, if it is currently not a known post
1333 * (according to {@link Post#isKnown()}).
1336 * The post to mark as known
1338 public void markPostKnown(Post post) {
1339 post.setKnown(true);
1340 eventBus.post(new MarkPostKnownEvent(post));
1341 touchConfiguration();
1342 for (PostReply reply : getReplies(post.getId())) {
1343 markReplyKnown(reply);
1348 * Bookmarks the given post.
1351 * The post to bookmark
1353 public void bookmark(Post post) {
1354 bookmarkPost(post.getId());
1358 * Bookmarks the post with the given ID.
1361 * The ID of the post to bookmark
1363 public void bookmarkPost(String id) {
1364 synchronized (bookmarkedPosts) {
1365 bookmarkedPosts.add(id);
1370 * Removes the given post from the bookmarks.
1373 * The post to unbookmark
1375 public void unbookmark(Post post) {
1376 unbookmarkPost(post.getId());
1380 * Removes the post with the given ID from the bookmarks.
1383 * The ID of the post to unbookmark
1385 public void unbookmarkPost(String id) {
1386 synchronized (bookmarkedPosts) {
1387 bookmarkedPosts.remove(id);
1392 * Creates a new reply.
1395 * The Sone that creates the reply
1397 * The post that this reply refers to
1399 * The text of the reply
1400 * @return The created reply
1402 public PostReply createReply(Sone sone, Post post, String text) {
1403 checkNotNull(text, "text must not be null");
1404 checkArgument(text.trim().length() > 0, "text must not be empty");
1405 if (!sone.isLocal()) {
1406 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1409 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1410 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1411 final PostReply reply = postReplyBuilder.build();
1412 database.storePostReply(reply);
1413 eventBus.post(new NewPostReplyFoundEvent(reply));
1414 sone.addReply(reply);
1415 touchConfiguration();
1416 localElementTicker.schedule(new Runnable() {
1423 markReplyKnown(reply);
1425 }, 10, TimeUnit.SECONDS);
1430 * Deletes the given reply.
1433 * The reply to delete
1435 public void deleteReply(PostReply reply) {
1436 Sone sone = reply.getSone();
1437 if (!sone.isLocal()) {
1438 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1441 database.removePostReply(reply);
1442 markReplyKnown(reply);
1443 sone.removeReply(reply);
1444 touchConfiguration();
1448 * Marks the given reply as known, if it is currently not a known reply
1449 * (according to {@link Reply#isKnown()}).
1452 * The reply to mark as known
1454 public void markReplyKnown(PostReply reply) {
1455 boolean previouslyKnown = reply.isKnown();
1456 reply.setKnown(true);
1457 eventBus.post(new MarkPostReplyKnownEvent(reply));
1458 if (!previouslyKnown) {
1459 touchConfiguration();
1464 * Creates a new image.
1467 * The Sone creating the image
1469 * The album the image will be inserted into
1470 * @param temporaryImage
1471 * The temporary image to create the image from
1472 * @return The newly created image
1474 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1475 checkNotNull(sone, "sone must not be null");
1476 checkNotNull(album, "album must not be null");
1477 checkNotNull(temporaryImage, "temporaryImage must not be null");
1478 checkArgument(sone.isLocal(), "sone must be a local Sone");
1479 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1480 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1481 imageInserter.insertImage(temporaryImage, image);
1486 * Deletes the given image. This method will also delete a matching temporary
1490 * The image to delete
1491 * @see #deleteTemporaryImage(TemporaryImage)
1493 public void deleteImage(Image image) {
1494 checkNotNull(image, "image must not be null");
1495 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1496 deleteTemporaryImage(image.getId());
1498 touchConfiguration();
1502 * Creates a new temporary image.
1505 * The MIME type of the temporary image
1507 * The encoded data of the image
1508 * @return The temporary image
1510 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1511 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1512 synchronized (temporaryImages) {
1513 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1515 return temporaryImage;
1519 * Deletes the given temporary image.
1521 * @param temporaryImage
1522 * The temporary image to delete
1524 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1525 checkNotNull(temporaryImage, "temporaryImage must not be null");
1526 deleteTemporaryImage(temporaryImage.getId());
1530 * Deletes the temporary image with the given ID.
1533 * The ID of the temporary image to delete
1535 public void deleteTemporaryImage(String imageId) {
1536 checkNotNull(imageId, "imageId must not be null");
1537 synchronized (temporaryImages) {
1538 temporaryImages.remove(imageId);
1540 Optional<Image> image = getImage(imageId);
1541 if (image.isPresent()) {
1542 imageInserter.cancelImageInsert(image.get());
1547 * Notifies the core that the configuration, either of the core or of a single
1548 * local Sone, has changed, and that the configuration should be saved.
1550 public void touchConfiguration() {
1551 lastConfigurationUpdate = System.currentTimeMillis();
1558 /** Starts the core. */
1560 public void serviceStart() {
1561 loadConfiguration();
1562 updateChecker.start();
1563 identityManager.start();
1564 webOfTrustUpdater.init();
1565 webOfTrustUpdater.start();
1569 /** {@inheritDoc} */
1571 public void serviceRun() {
1572 long lastSaved = System.currentTimeMillis();
1573 while (!shouldStop()) {
1575 long now = System.currentTimeMillis();
1576 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1577 for (Sone localSone : getLocalSones()) {
1578 saveSone(localSone);
1580 saveConfiguration();
1586 /** Stops the core. */
1588 public void serviceStop() {
1589 localElementTicker.shutdownNow();
1590 synchronized (sones) {
1591 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1592 soneInserter.getValue().stop();
1593 saveSone(soneInserter.getKey());
1596 saveConfiguration();
1598 webOfTrustUpdater.stop();
1599 updateChecker.stop();
1600 soneDownloader.stop();
1601 soneDownloaders.shutdown();
1602 identityManager.stop();
1610 * Saves the given Sone. This will persist all local settings for the given
1611 * Sone, such as the friends list and similar, private options.
1616 private synchronized void saveSone(Sone sone) {
1617 if (!sone.isLocal()) {
1618 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1621 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1622 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1626 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1628 /* save Sone into configuration. */
1629 String sonePrefix = "Sone/" + sone.getId();
1630 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1631 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1634 Profile profile = sone.getProfile();
1635 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1636 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1637 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1638 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1639 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1640 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1641 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1643 /* save profile fields. */
1644 int fieldCounter = 0;
1645 for (Field profileField : profile.getFields()) {
1646 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1647 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1648 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1650 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1653 int postCounter = 0;
1654 for (Post post : sone.getPosts()) {
1655 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1656 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1657 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1658 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1659 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1661 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1664 int replyCounter = 0;
1665 for (PostReply reply : sone.getReplies()) {
1666 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1667 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1668 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1669 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1670 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1672 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1674 /* save post likes. */
1675 int postLikeCounter = 0;
1676 for (String postId : sone.getLikedPostIds()) {
1677 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1679 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1681 /* save reply likes. */
1682 int replyLikeCounter = 0;
1683 for (String replyId : sone.getLikedReplyIds()) {
1684 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1686 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1689 int friendCounter = 0;
1690 for (String friendId : sone.getFriends()) {
1691 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1693 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1695 /* save albums. first, collect in a flat structure, top-level first. */
1696 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1698 int albumCounter = 0;
1699 for (Album album : albums) {
1700 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1701 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1702 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1703 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1704 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1705 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1707 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1710 int imageCounter = 0;
1711 for (Album album : albums) {
1712 for (Image image : album.getImages()) {
1713 if (!image.isInserted()) {
1716 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1717 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1718 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1719 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1720 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1721 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1722 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1723 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1724 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1727 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1730 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1731 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1732 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1733 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1734 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1735 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1737 configuration.save();
1739 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1741 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1742 } catch (ConfigurationException ce1) {
1743 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1747 /** Saves the current options. */
1748 private void saveConfiguration() {
1749 synchronized (configuration) {
1750 if (storingConfiguration) {
1751 logger.log(Level.FINE, "Already storing configuration…");
1754 storingConfiguration = true;
1757 /* store the options first. */
1759 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1760 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1761 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1762 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1763 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1764 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1765 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1766 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1767 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1768 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1769 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1770 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1772 /* save known Sones. */
1773 int soneCounter = 0;
1774 synchronized (knownSones) {
1775 for (String knownSoneId : knownSones) {
1776 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1778 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1781 /* save Sone following times. */
1783 synchronized (soneFollowingTimes) {
1784 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1785 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1786 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1789 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1792 /* save known posts. */
1795 /* save bookmarked posts. */
1796 int bookmarkedPostCounter = 0;
1797 synchronized (bookmarkedPosts) {
1798 for (String bookmarkedPostId : bookmarkedPosts) {
1799 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1802 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1805 configuration.save();
1807 } catch (ConfigurationException ce1) {
1808 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1809 } catch (DatabaseException de1) {
1810 logger.log(Level.SEVERE, "Could not save database!", de1);
1812 synchronized (configuration) {
1813 storingConfiguration = false;
1818 /** Loads the configuration. */
1819 private void loadConfiguration() {
1820 /* create options. */
1821 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1824 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1825 SoneInserter.setInsertionDelay(newValue);
1829 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1830 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1831 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1832 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1833 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1834 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1835 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1836 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1837 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1840 @SuppressWarnings("synthetic-access")
1841 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1842 fcpInterface.setActive(newValue);
1845 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1848 @SuppressWarnings("synthetic-access")
1849 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1850 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1855 loadConfigurationValue("InsertionDelay");
1856 loadConfigurationValue("PostsPerPage");
1857 loadConfigurationValue("ImagesPerPage");
1858 loadConfigurationValue("CharactersPerPost");
1859 loadConfigurationValue("PostCutOffLength");
1860 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1861 loadConfigurationValue("PositiveTrust");
1862 loadConfigurationValue("NegativeTrust");
1863 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1864 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1865 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1867 /* load known Sones. */
1868 int soneCounter = 0;
1870 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1871 if (knownSoneId == null) {
1874 synchronized (knownSones) {
1875 knownSones.add(knownSoneId);
1879 /* load Sone following times. */
1882 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1883 if (soneId == null) {
1886 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1887 synchronized (soneFollowingTimes) {
1888 soneFollowingTimes.put(soneId, time);
1893 /* load bookmarked posts. */
1894 int bookmarkedPostCounter = 0;
1896 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1897 if (bookmarkedPostId == null) {
1900 synchronized (bookmarkedPosts) {
1901 bookmarkedPosts.add(bookmarkedPostId);
1908 * Loads an {@link Integer} configuration value for the option with the given
1909 * name, logging validation failures.
1912 * The name of the option to load
1914 private void loadConfigurationValue(String optionName) {
1916 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1917 } catch (IllegalArgumentException iae1) {
1918 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1923 * Notifies the core that a new {@link OwnIdentity} was added.
1925 * @param ownIdentityAddedEvent
1929 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1930 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1931 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1932 if (ownIdentity.hasContext("Sone")) {
1933 addLocalSone(ownIdentity);
1938 * Notifies the core that an {@link OwnIdentity} was removed.
1940 * @param ownIdentityRemovedEvent
1944 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1945 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1946 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1947 trustedIdentities.removeAll(ownIdentity);
1951 * Notifies the core that a new {@link Identity} was added.
1953 * @param identityAddedEvent
1957 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1958 Identity identity = identityAddedEvent.identity();
1959 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1960 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1961 addRemoteSone(identity);
1965 * Notifies the core that an {@link Identity} was updated.
1967 * @param identityUpdatedEvent
1971 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1972 final Identity identity = identityUpdatedEvent.identity();
1973 soneDownloaders.execute(new Runnable() {
1976 @SuppressWarnings("synthetic-access")
1978 Optional<Sone> sone = getRemoteSone(identity.getId());
1979 sone.get().setIdentity(identity);
1980 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1981 soneDownloader.addSone(sone.get());
1982 soneDownloader.fetchSone(sone.get());
1988 * Notifies the core that an {@link Identity} was removed.
1990 * @param identityRemovedEvent
1994 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1995 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1996 Identity identity = identityRemovedEvent.identity();
1997 trustedIdentities.remove(ownIdentity, identity);
1998 boolean foundIdentity = false;
1999 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2000 if (trustedIdentity.getKey().equals(ownIdentity)) {
2003 if (trustedIdentity.getValue().contains(identity)) {
2004 foundIdentity = true;
2007 if (foundIdentity) {
2008 /* some local identity still trusts this identity, don’t remove. */
2011 Optional<Sone> sone = getSone(identity.getId());
2012 if (!sone.isPresent()) {
2013 /* TODO - we don’t have the Sone anymore. should this happen? */
2016 database.removePosts(sone.get());
2017 for (Post post : sone.get().getPosts()) {
2018 eventBus.post(new PostRemovedEvent(post));
2020 database.removePostReplies(sone.get());
2021 for (PostReply reply : sone.get().getReplies()) {
2022 eventBus.post(new PostReplyRemovedEvent(reply));
2024 synchronized (sones) {
2025 sones.remove(identity.getId());
2027 eventBus.post(new SoneRemovedEvent(sone.get()));
2031 * Deletes the temporary image.
2033 * @param imageInsertFinishedEvent
2037 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2038 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2039 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2040 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2041 touchConfiguration();