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.of;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.collect.FluentIterable.from;
25 import static net.pterodactylus.sone.data.Identified.GET_ID;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import java.net.MalformedURLException;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.sone.core.Options.DefaultOption;
44 import net.pterodactylus.sone.core.Options.Option;
45 import net.pterodactylus.sone.core.Options.OptionWatcher;
46 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
47 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
49 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
50 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
51 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
52 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
53 import net.pterodactylus.sone.core.event.PostRemovedEvent;
54 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneLockedEvent;
56 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
58 import net.pterodactylus.sone.data.Album;
59 import net.pterodactylus.sone.data.Client;
60 import net.pterodactylus.sone.data.Image;
61 import net.pterodactylus.sone.data.Post;
62 import net.pterodactylus.sone.data.PostReply;
63 import net.pterodactylus.sone.data.Profile;
64 import net.pterodactylus.sone.data.Profile.Field;
65 import net.pterodactylus.sone.data.Reply;
66 import net.pterodactylus.sone.data.Sone;
67 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
68 import net.pterodactylus.sone.data.Sone.SoneStatus;
69 import net.pterodactylus.sone.data.TemporaryImage;
70 import net.pterodactylus.sone.database.Database;
71 import net.pterodactylus.sone.database.DatabaseException;
72 import net.pterodactylus.sone.database.PostBuilder;
73 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
74 import net.pterodactylus.sone.database.PostProvider;
75 import net.pterodactylus.sone.database.PostReplyBuilder;
76 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
77 import net.pterodactylus.sone.database.PostReplyProvider;
78 import net.pterodactylus.sone.database.SoneProvider;
79 import net.pterodactylus.sone.fcp.FcpInterface;
80 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
81 import net.pterodactylus.sone.freenet.wot.Identity;
82 import net.pterodactylus.sone.freenet.wot.IdentityManager;
83 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
84 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
89 import net.pterodactylus.sone.main.SonePlugin;
90 import net.pterodactylus.sone.utils.IntegerRangePredicate;
91 import net.pterodactylus.util.config.Configuration;
92 import net.pterodactylus.util.config.ConfigurationException;
93 import net.pterodactylus.util.logging.Logging;
94 import net.pterodactylus.util.number.Numbers;
95 import net.pterodactylus.util.service.AbstractService;
96 import net.pterodactylus.util.thread.NamedThreadFactory;
98 import freenet.keys.FreenetURI;
100 import com.google.common.base.Optional;
101 import com.google.common.base.Predicate;
102 import com.google.common.base.Predicates;
103 import com.google.common.collect.HashMultimap;
104 import com.google.common.collect.ImmutableSet;
105 import com.google.common.collect.Maps;
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;
115 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
117 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
120 private static final Logger logger = Logging.getLogger(Core.class);
122 /** The start time. */
123 private final long startupTime = System.currentTimeMillis();
126 private final Options options = new Options();
128 /** The preferences. */
129 private final Preferences preferences = new Preferences(options);
131 /** The event bus. */
132 private final EventBus eventBus;
134 /** The configuration. */
135 private Configuration configuration;
137 /** Whether we’re currently saving the configuration. */
138 private boolean storingConfiguration = false;
140 /** The identity manager. */
141 private final IdentityManager identityManager;
143 /** Interface to freenet. */
144 private final FreenetInterface freenetInterface;
146 /** The Sone downloader. */
147 private final SoneDownloader soneDownloader;
149 /** The image inserter. */
150 private final ImageInserter imageInserter;
152 /** Sone downloader thread-pool. */
153 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
155 /** The update checker. */
156 private final UpdateChecker updateChecker;
158 /** The trust updater. */
159 private final WebOfTrustUpdater webOfTrustUpdater;
161 /** The FCP interface. */
162 private volatile FcpInterface fcpInterface;
164 /** The times Sones were followed. */
165 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
167 /** Locked local Sones. */
168 /* synchronize on itself. */
169 private final Set<Sone> lockedSones = new HashSet<Sone>();
171 /** Sone inserters. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
175 /** Sone rescuers. */
176 /* synchronize access on this on sones. */
177 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
180 /* synchronize access on this on itself. */
181 private final Map<String, Sone> sones = new HashMap<String, Sone>();
183 /** All known Sones. */
184 private final Set<String> knownSones = new HashSet<String>();
186 /** The post database. */
187 private final Database database;
189 /** All bookmarked posts. */
190 /* synchronize access on itself. */
191 private final Set<String> bookmarkedPosts = new HashSet<String>();
193 /** Trusted identities, sorted by own identities. */
194 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
222 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = new SoneDownloader(this, freenetInterface);
228 this.imageInserter = new ImageInserter(freenetInterface);
229 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
232 this.database = database;
240 * Returns the time Sone was started.
242 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
244 public long getStartupTime() {
249 * Sets the configuration to use. This will automatically save the current
250 * configuration to the given configuration.
252 * @param configuration
253 * The new configuration to use
255 public void setConfiguration(Configuration configuration) {
256 this.configuration = configuration;
257 touchConfiguration();
261 * Returns the options used by the core.
263 * @return The options of the core
265 public Preferences getPreferences() {
270 * Returns the identity manager used by the core.
272 * @return The identity manager
274 public IdentityManager getIdentityManager() {
275 return identityManager;
279 * Returns the update checker.
281 * @return The update checker
283 public UpdateChecker getUpdateChecker() {
284 return updateChecker;
288 * Sets the FCP interface to use.
290 * @param fcpInterface
291 * The FCP interface to use
293 public void setFcpInterface(FcpInterface fcpInterface) {
294 this.fcpInterface = fcpInterface;
297 public Database getDatabase() {
302 * Returns the Sone rescuer for the given local Sone.
305 * The local Sone to get the rescuer for
306 * @return The Sone rescuer for the given Sone
308 public SoneRescuer getSoneRescuer(Sone sone) {
309 checkNotNull(sone, "sone must not be null");
310 checkArgument(sone.isLocal(), "sone must be local");
311 synchronized (sones) {
312 SoneRescuer soneRescuer = soneRescuers.get(sone);
313 if (soneRescuer == null) {
314 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
315 soneRescuers.put(sone, soneRescuer);
323 * Returns whether the given Sone is currently locked.
327 * @return {@code true} if the Sone is locked, {@code false} if it is not
329 public boolean isLocked(Sone sone) {
330 synchronized (lockedSones) {
331 return lockedSones.contains(sone);
335 /** {@inheritDocs} */
337 public Collection<Sone> getSones() {
338 synchronized (sones) {
339 return ImmutableSet.copyOf(sones.values());
344 * Returns the Sone with the given ID, regardless whether it’s local or
348 * The ID of the Sone to get
349 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Optional<Sone> getSone(String id) {
354 synchronized (sones) {
355 return Optional.fromNullable(sones.get(id));
359 /** {@inheritDocs} */
361 public Collection<Sone> getLocalSones() {
362 synchronized (sones) {
363 return from(sones.values()).filter(new Predicate<Sone>() {
366 public boolean apply(Sone sone) {
367 return sone.isLocal();
374 * Returns the local Sone with the given ID, optionally creating a new Sone.
378 * @return The Sone with the given ID, or {@code null}
380 public Optional<Sone> getLocalSone(String id) {
381 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
384 /** {@inheritDocs} */
386 public Collection<Sone> getRemoteSones() {
387 synchronized (sones) {
388 return from(sones.values()).filter(new Predicate<Sone>() {
391 public boolean apply(Sone sone) {
392 return !sone.isLocal();
399 * Returns the remote Sone with the given ID.
402 * The ID of the remote Sone to get
403 * @return The Sone with the given ID
405 public Optional<Sone> getRemoteSone(String id) {
406 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
410 * Returns whether the given Sone has been modified.
413 * The Sone to check for modifications
414 * @return {@code true} if a modification has been detected in the Sone, {@code
417 public boolean isModifiedSone(Sone sone) {
418 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
422 * Returns the time when the given was first followed by any local Sone.
425 * The Sone to get the time for
426 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
427 * followed, or {@link Long#MAX_VALUE}
429 public long getSoneFollowingTime(Sone sone) {
430 synchronized (soneFollowingTimes) {
431 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
436 * Returns whether the target Sone is trusted by the origin Sone.
442 * @return {@code true} if the target Sone is trusted by the origin Sone
444 public boolean isSoneTrusted(Sone origin, Sone target) {
445 checkNotNull(origin, "origin must not be null");
446 checkNotNull(target, "target must not be null");
447 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
448 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
453 public Optional<Post> getPost(String postId) {
454 return database.getPost(postId);
457 /** {@inheritDocs} */
459 public Collection<Post> getPosts(String soneId) {
460 return database.getPosts(soneId);
465 public Collection<Post> getDirectedPosts(final String recipientId) {
466 checkNotNull(recipientId, "recipient must not be null");
467 return database.getDirectedPosts(recipientId);
472 public Optional<PostReply> getPostReply(String replyId) {
473 return database.getPostReply(replyId);
478 public List<PostReply> getReplies(final String postId) {
479 return database.getReplies(postId);
483 * Returns all Sones that have liked the given post.
486 * The post to get the liking Sones for
487 * @return The Sones that like the given post
489 public Set<Sone> getLikes(Post post) {
490 Set<Sone> sones = new HashSet<Sone>();
491 for (Sone sone : getSones()) {
492 if (sone.getLikedPostIds().contains(post.getId())) {
500 * Returns all Sones that have liked the given reply.
503 * The reply to get the liking Sones for
504 * @return The Sones that like the given reply
506 public Set<Sone> getLikes(PostReply reply) {
507 Set<Sone> sones = new HashSet<Sone>();
508 for (Sone sone : getSones()) {
509 if (sone.getLikedReplyIds().contains(reply.getId())) {
517 * Returns whether the given post is bookmarked.
521 * @return {@code true} if the given post is bookmarked, {@code false}
524 public boolean isBookmarked(Post post) {
525 return isPostBookmarked(post.getId());
529 * Returns whether the post with the given ID is bookmarked.
532 * The ID of the post to check
533 * @return {@code true} if the post with the given ID is bookmarked, {@code
536 public boolean isPostBookmarked(String id) {
537 synchronized (bookmarkedPosts) {
538 return bookmarkedPosts.contains(id);
543 * Returns all currently known bookmarked posts.
545 * @return All bookmarked posts
547 public Set<Post> getBookmarkedPosts() {
548 Set<Post> posts = new HashSet<Post>();
549 synchronized (bookmarkedPosts) {
550 for (String bookmarkedPostId : bookmarkedPosts) {
551 Optional<Post> post = getPost(bookmarkedPostId);
552 if (post.isPresent()) {
553 posts.add(post.get());
560 public Optional<Album> getAlbum(String albumId) {
561 return database.getAlbum(albumId);
564 public Optional<Image> getImage(String imageId) {
565 return database.getImage(imageId);
569 * Returns the temporary image with the given ID.
572 * The ID of the temporary image
573 * @return The temporary image, or {@code null} if there is no temporary image
576 public TemporaryImage getTemporaryImage(String imageId) {
577 synchronized (temporaryImages) {
578 return temporaryImages.get(imageId);
587 * Locks the given Sone. A locked Sone will not be inserted by {@link
588 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
593 public void lockSone(Sone sone) {
594 synchronized (lockedSones) {
595 if (lockedSones.add(sone)) {
596 eventBus.post(new SoneLockedEvent(sone));
602 * Unlocks the given Sone.
606 * @see #lockSone(Sone)
608 public void unlockSone(Sone sone) {
609 synchronized (lockedSones) {
610 if (lockedSones.remove(sone)) {
611 eventBus.post(new SoneUnlockedEvent(sone));
617 * Adds a local Sone from the given own identity.
620 * The own identity to create a Sone from
621 * @return The added (or already existing) Sone
623 public Sone addLocalSone(OwnIdentity ownIdentity) {
624 if (ownIdentity == null) {
625 logger.log(Level.WARNING, "Given OwnIdentity is null!");
628 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
629 synchronized (sones) {
632 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
633 } catch (MalformedURLException mue1) {
634 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
637 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
638 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
640 /* TODO - load posts ’n stuff */
641 sones.put(ownIdentity.getId(), sone);
642 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
643 soneInserters.put(sone, soneInserter);
644 sone.setStatus(SoneStatus.idle);
646 soneInserter.start();
652 * Creates a new Sone for the given own identity.
655 * The own identity to create a Sone for
656 * @return The created Sone
658 public Sone createSone(OwnIdentity ownIdentity) {
659 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
660 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
663 Sone sone = addLocalSone(ownIdentity);
664 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
665 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
666 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
667 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
668 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
669 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
671 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
672 touchConfiguration();
677 * Adds the Sone of the given identity.
680 * The identity whose Sone to add
681 * @return The added or already existing Sone
683 public Sone addRemoteSone(Identity identity) {
684 if (identity == null) {
685 logger.log(Level.WARNING, "Given Identity is null!");
688 synchronized (sones) {
689 final Sone sone = database.newSoneBuilder().by(identity).build();
690 if (sone.isLocal()) {
693 sone.setIdentity(identity);
694 boolean newSone = sone.getRequestUri() == null;
695 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
696 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
698 synchronized (knownSones) {
699 newSone = !knownSones.contains(sone.getId());
701 sone.setKnown(!newSone);
703 eventBus.post(new NewSoneFoundEvent(sone));
704 for (Sone localSone : getLocalSones()) {
705 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
706 followSone(localSone, sone.getId());
711 soneDownloader.addSone(sone);
712 soneDownloaders.execute(new Runnable() {
715 @SuppressWarnings("synthetic-access")
717 soneDownloader.fetchSone(sone, sone.getRequestUri());
726 * Lets the given local Sone follow the Sone with the given ID.
729 * The local Sone that should follow another Sone
731 * The ID of the Sone to follow
733 public void followSone(Sone sone, String soneId) {
734 checkNotNull(sone, "sone must not be null");
735 checkNotNull(soneId, "soneId must not be null");
736 sone.addFriend(soneId);
737 synchronized (soneFollowingTimes) {
738 if (!soneFollowingTimes.containsKey(soneId)) {
739 long now = System.currentTimeMillis();
740 soneFollowingTimes.put(soneId, now);
741 Optional<Sone> followedSone = getSone(soneId);
742 if (!followedSone.isPresent()) {
745 for (Post post : followedSone.get().getPosts()) {
746 if (post.getTime() < now) {
750 for (PostReply reply : followedSone.get().getReplies()) {
751 if (reply.getTime() < now) {
752 markReplyKnown(reply);
757 touchConfiguration();
761 * Lets the given local Sone unfollow the Sone with the given ID.
764 * The local Sone that should unfollow another Sone
766 * The ID of the Sone being unfollowed
768 public void unfollowSone(Sone sone, String soneId) {
769 checkNotNull(sone, "sone must not be null");
770 checkNotNull(soneId, "soneId must not be null");
771 sone.removeFriend(soneId);
772 boolean unfollowedSoneStillFollowed = false;
773 for (Sone localSone : getLocalSones()) {
774 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
776 if (!unfollowedSoneStillFollowed) {
777 synchronized (soneFollowingTimes) {
778 soneFollowingTimes.remove(soneId);
781 touchConfiguration();
785 * Sets the trust value of the given origin Sone for the target Sone.
792 * The trust value (from {@code -100} to {@code 100})
794 public void setTrust(Sone origin, Sone target, int trustValue) {
795 checkNotNull(origin, "origin must not be null");
796 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
797 checkNotNull(target, "target must not be null");
798 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
799 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
803 * Removes any trust assignment for the given target Sone.
810 public void removeTrust(Sone origin, Sone target) {
811 checkNotNull(origin, "origin must not be null");
812 checkNotNull(target, "target must not be null");
813 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
814 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
818 * Assigns the configured positive trust value for the given target.
825 public void trustSone(Sone origin, Sone target) {
826 setTrust(origin, target, preferences.getPositiveTrust());
830 * Assigns the configured negative trust value for the given target.
837 public void distrustSone(Sone origin, Sone target) {
838 setTrust(origin, target, preferences.getNegativeTrust());
842 * Removes the trust assignment for the given target.
849 public void untrustSone(Sone origin, Sone target) {
850 removeTrust(origin, target);
854 * Updates the stored Sone with the given Sone.
859 public void updateSone(Sone sone) {
860 updateSone(sone, false);
864 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
865 * {@code true}, an older Sone than the current Sone can be given to restore an
870 * @param soneRescueMode
871 * {@code true} if the stored Sone should be updated regardless of the age of
874 public void updateSone(Sone sone, boolean soneRescueMode) {
875 Optional<Sone> storedSone = getSone(sone.getId());
876 if (storedSone.isPresent()) {
877 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
878 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
881 /* find removed posts. */
882 Collection<Post> existingPosts = database.getPosts(sone.getId());
883 for (Post oldPost : existingPosts) {
884 if (!sone.getPosts().contains(oldPost)) {
885 eventBus.post(new PostRemovedEvent(oldPost));
888 /* find new posts. */
889 for (Post newPost : sone.getPosts()) {
890 if (existingPosts.contains(newPost)) {
893 if (newPost.getTime() < getSoneFollowingTime(sone)) {
894 newPost.setKnown(true);
895 } else if (!newPost.isKnown()) {
896 eventBus.post(new NewPostFoundEvent(newPost));
900 database.storePosts(sone, sone.getPosts());
901 if (!soneRescueMode) {
902 for (PostReply reply : storedSone.get().getReplies()) {
903 if (!sone.getReplies().contains(reply)) {
904 eventBus.post(new PostReplyRemovedEvent(reply));
908 Set<PostReply> storedReplies = storedSone.get().getReplies();
909 for (PostReply reply : sone.getReplies()) {
910 if (storedReplies.contains(reply)) {
913 if (reply.getTime() < getSoneFollowingTime(sone)) {
914 reply.setKnown(true);
915 } else if (!reply.isKnown()) {
916 eventBus.post(new NewPostReplyFoundEvent(reply));
919 database.storePostReplies(sone, sone.getReplies());
920 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
921 database.removeAlbum(album);
922 for (Image image : album.getImages()) {
923 database.removeImage(image);
926 for (Album album : sone.getRootAlbum().getAlbums()) {
927 database.storeAlbum(album);
928 for (Image image : album.getImages()) {
929 database.storeImage(image);
932 synchronized (sones) {
933 sone.setOptions(storedSone.get().getOptions());
934 sone.setKnown(storedSone.get().isKnown());
935 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
936 if (sone.isLocal()) {
937 soneInserters.get(storedSone.get()).setSone(sone);
938 touchConfiguration();
940 sones.put(sone.getId(), sone);
946 * Deletes the given Sone. This will remove the Sone from the {@link
947 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
948 * context from its identity.
953 public void deleteSone(Sone sone) {
954 if (!(sone.getIdentity() instanceof OwnIdentity)) {
955 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
958 synchronized (sones) {
959 if (!getLocalSones().contains(sone)) {
960 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
963 sones.remove(sone.getId());
964 SoneInserter soneInserter = soneInserters.remove(sone);
967 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
968 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
970 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
971 } catch (ConfigurationException ce1) {
972 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
977 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
978 * known} before, a {@link MarkSoneKnownEvent} is fired.
981 * The Sone to mark as known
983 public void markSoneKnown(Sone sone) {
984 if (!sone.isKnown()) {
986 synchronized (knownSones) {
987 knownSones.add(sone.getId());
989 eventBus.post(new MarkSoneKnownEvent(sone));
990 touchConfiguration();
995 * Loads and updates the given Sone from the configuration. If any error is
996 * encountered, loading is aborted and the given Sone is not changed.
999 * The Sone to load and update
1001 public void loadSone(Sone sone) {
1002 if (!sone.isLocal()) {
1003 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1006 logger.info(String.format("Loading local Sone: %s", sone));
1008 /* initialize options. */
1009 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1010 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1011 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1012 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1013 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1014 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1017 String sonePrefix = "Sone/" + sone.getId();
1018 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1019 if (soneTime == null) {
1020 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1023 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1026 Profile profile = new Profile(sone);
1027 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1028 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1029 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1030 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1031 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1032 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1034 /* load profile fields. */
1036 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1037 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1038 if (fieldName == null) {
1041 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1042 profile.addField(fieldName).setValue(fieldValue);
1046 Set<Post> posts = new HashSet<Post>();
1048 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1049 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1050 if (postId == null) {
1053 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1054 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1055 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1056 if ((postTime == 0) || (postText == null)) {
1057 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1060 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
1061 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1062 postBuilder.to(of(postRecipientId));
1064 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1068 Set<PostReply> replies = new HashSet<PostReply>();
1070 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1071 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1072 if (replyId == null) {
1075 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1076 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1077 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1078 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1079 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1082 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1083 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1086 /* load post likes. */
1087 Set<String> likedPostIds = new HashSet<String>();
1089 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1090 if (likedPostId == null) {
1093 likedPostIds.add(likedPostId);
1096 /* load reply likes. */
1097 Set<String> likedReplyIds = new HashSet<String>();
1099 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1100 if (likedReplyId == null) {
1103 likedReplyIds.add(likedReplyId);
1107 Set<String> friends = new HashSet<String>();
1109 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1110 if (friendId == null) {
1113 friends.add(friendId);
1117 Map<String, Album> albums = Maps.newHashMap();
1118 int albumCounter = 0;
1120 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1121 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1122 if (albumId == null) {
1125 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1126 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1127 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1128 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1129 if ((albumTitle == null) || (albumDescription == null)) {
1130 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1133 Album parentAlbum = sone.getRootAlbum();
1134 if (albumParentId != null) {
1135 parentAlbum = albums.get(albumParentId);
1137 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1138 albums.put(album.getId(), album);
1142 int imageCounter = 0;
1144 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1145 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1146 if (imageId == null) {
1149 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1150 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1151 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1152 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1153 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1154 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1155 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1156 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1157 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1160 Album album = albums.get(albumId);
1161 if (album == null) {
1162 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1165 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1169 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1170 if (avatarId != null) {
1171 profile.setAvatar(getImage(avatarId).orNull());
1175 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1176 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1177 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1178 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1179 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1180 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1182 /* if we’re still here, Sone was loaded successfully. */
1183 synchronized (sone) {
1184 sone.setTime(soneTime);
1185 sone.setProfile(profile);
1186 sone.setPosts(posts);
1187 sone.setReplies(replies);
1188 sone.setLikePostIds(likedPostIds);
1189 sone.setLikeReplyIds(likedReplyIds);
1190 for (String friendId : friends) {
1191 followSone(sone, friendId);
1193 for (Album album : sone.getRootAlbum().getAlbums()) {
1196 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1198 synchronized (knownSones) {
1199 for (String friend : friends) {
1200 knownSones.add(friend);
1203 database.storePosts(sone, posts);
1204 for (Post post : posts) {
1205 post.setKnown(true);
1207 database.storePostReplies(sone, replies);
1208 for (PostReply reply : replies) {
1209 reply.setKnown(true);
1212 logger.info(String.format("Sone loaded successfully: %s", sone));
1216 * Deletes the given post.
1219 * The post to delete
1221 public void deletePost(Post post) {
1222 if (!post.getSone().isLocal()) {
1223 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1226 database.removePost(post);
1227 eventBus.post(new PostRemovedEvent(post));
1228 markPostKnown(post);
1229 touchConfiguration();
1233 * Marks the given post as known, if it is currently not a known post
1234 * (according to {@link Post#isKnown()}).
1237 * The post to mark as known
1239 public void markPostKnown(Post post) {
1240 post.setKnown(true);
1241 eventBus.post(new MarkPostKnownEvent(post));
1242 touchConfiguration();
1243 for (PostReply reply : getReplies(post.getId())) {
1244 markReplyKnown(reply);
1249 * Bookmarks the given post.
1252 * The post to bookmark
1254 public void bookmark(Post post) {
1255 bookmarkPost(post.getId());
1259 * Bookmarks the post with the given ID.
1262 * The ID of the post to bookmark
1264 public void bookmarkPost(String id) {
1265 synchronized (bookmarkedPosts) {
1266 bookmarkedPosts.add(id);
1271 * Removes the given post from the bookmarks.
1274 * The post to unbookmark
1276 public void unbookmark(Post post) {
1277 unbookmarkPost(post.getId());
1281 * Removes the post with the given ID from the bookmarks.
1284 * The ID of the post to unbookmark
1286 public void unbookmarkPost(String id) {
1287 synchronized (bookmarkedPosts) {
1288 bookmarkedPosts.remove(id);
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 image.
1330 * The Sone creating the image
1332 * The album the image will be inserted into
1333 * @param temporaryImage
1334 * The temporary image to create the image from
1335 * @return The newly created image
1337 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1338 checkNotNull(sone, "sone must not be null");
1339 checkNotNull(album, "album must not be null");
1340 checkNotNull(temporaryImage, "temporaryImage must not be null");
1341 checkArgument(sone.isLocal(), "sone must be a local Sone");
1342 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1343 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1344 imageInserter.insertImage(temporaryImage, image);
1349 * Deletes the given image. This method will also delete a matching temporary
1353 * The image to delete
1354 * @see #deleteTemporaryImage(TemporaryImage)
1356 public void deleteImage(Image image) {
1357 checkNotNull(image, "image must not be null");
1358 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1359 deleteTemporaryImage(image.getId());
1361 touchConfiguration();
1365 * Creates a new temporary image.
1368 * The MIME type of the temporary image
1370 * The encoded data of the image
1371 * @return The temporary image
1373 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1374 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1375 synchronized (temporaryImages) {
1376 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1378 return temporaryImage;
1382 * Deletes the given temporary image.
1384 * @param temporaryImage
1385 * The temporary image to delete
1387 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1388 checkNotNull(temporaryImage, "temporaryImage must not be null");
1389 deleteTemporaryImage(temporaryImage.getId());
1393 * Deletes the temporary image with the given ID.
1396 * The ID of the temporary image to delete
1398 public void deleteTemporaryImage(String imageId) {
1399 checkNotNull(imageId, "imageId must not be null");
1400 synchronized (temporaryImages) {
1401 temporaryImages.remove(imageId);
1403 Optional<Image> image = getImage(imageId);
1404 if (image.isPresent()) {
1405 imageInserter.cancelImageInsert(image.get());
1410 * Notifies the core that the configuration, either of the core or of a single
1411 * local Sone, has changed, and that the configuration should be saved.
1413 public void touchConfiguration() {
1414 lastConfigurationUpdate = System.currentTimeMillis();
1421 /** Starts the core. */
1423 public void serviceStart() {
1424 loadConfiguration();
1425 updateChecker.start();
1426 identityManager.start();
1427 webOfTrustUpdater.init();
1428 webOfTrustUpdater.start();
1432 /** {@inheritDoc} */
1434 public void serviceRun() {
1435 long lastSaved = System.currentTimeMillis();
1436 while (!shouldStop()) {
1438 long now = System.currentTimeMillis();
1439 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1440 for (Sone localSone : getLocalSones()) {
1441 saveSone(localSone);
1443 saveConfiguration();
1449 /** Stops the core. */
1451 public void serviceStop() {
1452 localElementTicker.shutdownNow();
1453 synchronized (sones) {
1454 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1455 soneInserter.getValue().stop();
1456 saveSone(soneInserter.getKey());
1459 saveConfiguration();
1461 webOfTrustUpdater.stop();
1462 updateChecker.stop();
1463 soneDownloader.stop();
1464 soneDownloaders.shutdown();
1465 identityManager.stop();
1473 * Saves the given Sone. This will persist all local settings for the given
1474 * Sone, such as the friends list and similar, private options.
1479 private synchronized void saveSone(Sone sone) {
1480 if (!sone.isLocal()) {
1481 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1484 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1485 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1489 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1491 /* save Sone into configuration. */
1492 String sonePrefix = "Sone/" + sone.getId();
1493 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1494 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1497 Profile profile = sone.getProfile();
1498 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1499 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1500 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1501 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1502 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1503 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1504 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1506 /* save profile fields. */
1507 int fieldCounter = 0;
1508 for (Field profileField : profile.getFields()) {
1509 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1510 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1511 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1513 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1516 int postCounter = 0;
1517 for (Post post : sone.getPosts()) {
1518 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1519 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1520 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1521 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1522 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1524 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1527 int replyCounter = 0;
1528 for (PostReply reply : sone.getReplies()) {
1529 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1530 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1531 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1532 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1533 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1535 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1537 /* save post likes. */
1538 int postLikeCounter = 0;
1539 for (String postId : sone.getLikedPostIds()) {
1540 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1542 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1544 /* save reply likes. */
1545 int replyLikeCounter = 0;
1546 for (String replyId : sone.getLikedReplyIds()) {
1547 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1549 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1552 int friendCounter = 0;
1553 for (String friendId : sone.getFriends()) {
1554 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1556 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1558 /* save albums. first, collect in a flat structure, top-level first. */
1559 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1561 int albumCounter = 0;
1562 for (Album album : albums) {
1563 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1564 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1565 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1566 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1567 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1568 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1570 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1573 int imageCounter = 0;
1574 for (Album album : albums) {
1575 for (Image image : album.getImages()) {
1576 if (!image.isInserted()) {
1579 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1580 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1581 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1582 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1583 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1584 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1585 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1586 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1587 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1590 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1593 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1594 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1595 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1596 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1597 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1598 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1600 configuration.save();
1602 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1604 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1605 } catch (ConfigurationException ce1) {
1606 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1610 /** Saves the current options. */
1611 private void saveConfiguration() {
1612 synchronized (configuration) {
1613 if (storingConfiguration) {
1614 logger.log(Level.FINE, "Already storing configuration…");
1617 storingConfiguration = true;
1620 /* store the options first. */
1622 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1623 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1624 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1625 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1626 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1627 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1628 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1629 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1630 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1631 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1632 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1633 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1635 /* save known Sones. */
1636 int soneCounter = 0;
1637 synchronized (knownSones) {
1638 for (String knownSoneId : knownSones) {
1639 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1641 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1644 /* save Sone following times. */
1646 synchronized (soneFollowingTimes) {
1647 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1648 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1649 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1652 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1655 /* save known posts. */
1658 /* save bookmarked posts. */
1659 int bookmarkedPostCounter = 0;
1660 synchronized (bookmarkedPosts) {
1661 for (String bookmarkedPostId : bookmarkedPosts) {
1662 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1665 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1668 configuration.save();
1670 } catch (ConfigurationException ce1) {
1671 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1672 } catch (DatabaseException de1) {
1673 logger.log(Level.SEVERE, "Could not save database!", de1);
1675 synchronized (configuration) {
1676 storingConfiguration = false;
1681 /** Loads the configuration. */
1682 private void loadConfiguration() {
1683 /* create options. */
1684 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1687 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1688 SoneInserter.setInsertionDelay(newValue);
1692 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1693 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1694 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1695 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1696 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1697 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1698 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1699 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1700 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1703 @SuppressWarnings("synthetic-access")
1704 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1705 fcpInterface.setActive(newValue);
1708 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1711 @SuppressWarnings("synthetic-access")
1712 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1713 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1718 loadConfigurationValue("InsertionDelay");
1719 loadConfigurationValue("PostsPerPage");
1720 loadConfigurationValue("ImagesPerPage");
1721 loadConfigurationValue("CharactersPerPost");
1722 loadConfigurationValue("PostCutOffLength");
1723 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1724 loadConfigurationValue("PositiveTrust");
1725 loadConfigurationValue("NegativeTrust");
1726 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1727 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1728 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1730 /* load known Sones. */
1731 int soneCounter = 0;
1733 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1734 if (knownSoneId == null) {
1737 synchronized (knownSones) {
1738 knownSones.add(knownSoneId);
1742 /* load Sone following times. */
1745 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1746 if (soneId == null) {
1749 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1750 synchronized (soneFollowingTimes) {
1751 soneFollowingTimes.put(soneId, time);
1756 /* load bookmarked posts. */
1757 int bookmarkedPostCounter = 0;
1759 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1760 if (bookmarkedPostId == null) {
1763 synchronized (bookmarkedPosts) {
1764 bookmarkedPosts.add(bookmarkedPostId);
1771 * Loads an {@link Integer} configuration value for the option with the given
1772 * name, logging validation failures.
1775 * The name of the option to load
1777 private void loadConfigurationValue(String optionName) {
1779 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1780 } catch (IllegalArgumentException iae1) {
1781 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1786 * Notifies the core that a new {@link OwnIdentity} was added.
1788 * @param ownIdentityAddedEvent
1792 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1793 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1794 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1795 if (ownIdentity.hasContext("Sone")) {
1796 addLocalSone(ownIdentity);
1801 * Notifies the core that an {@link OwnIdentity} was removed.
1803 * @param ownIdentityRemovedEvent
1807 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1808 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1809 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1810 trustedIdentities.removeAll(ownIdentity);
1814 * Notifies the core that a new {@link Identity} was added.
1816 * @param identityAddedEvent
1820 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1821 Identity identity = identityAddedEvent.identity();
1822 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1823 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1824 addRemoteSone(identity);
1828 * Notifies the core that an {@link Identity} was updated.
1830 * @param identityUpdatedEvent
1834 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1835 final Identity identity = identityUpdatedEvent.identity();
1836 soneDownloaders.execute(new Runnable() {
1839 @SuppressWarnings("synthetic-access")
1841 Optional<Sone> sone = getRemoteSone(identity.getId());
1842 sone.get().setIdentity(identity);
1843 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1844 soneDownloader.addSone(sone.get());
1845 soneDownloader.fetchSone(sone.get());
1851 * Notifies the core that an {@link Identity} was removed.
1853 * @param identityRemovedEvent
1857 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1858 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1859 Identity identity = identityRemovedEvent.identity();
1860 trustedIdentities.remove(ownIdentity, identity);
1861 boolean foundIdentity = false;
1862 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1863 if (trustedIdentity.getKey().equals(ownIdentity)) {
1866 if (trustedIdentity.getValue().contains(identity)) {
1867 foundIdentity = true;
1870 if (foundIdentity) {
1871 /* some local identity still trusts this identity, don’t remove. */
1874 Optional<Sone> sone = getSone(identity.getId());
1875 if (!sone.isPresent()) {
1876 /* TODO - we don’t have the Sone anymore. should this happen? */
1879 database.removePosts(sone.get());
1880 for (Post post : sone.get().getPosts()) {
1881 eventBus.post(new PostRemovedEvent(post));
1883 database.removePostReplies(sone.get());
1884 for (PostReply reply : sone.get().getReplies()) {
1885 eventBus.post(new PostReplyRemovedEvent(reply));
1887 synchronized (sones) {
1888 sones.remove(identity.getId());
1890 eventBus.post(new SoneRemovedEvent(sone.get()));
1894 * Deletes the temporary image.
1896 * @param imageInsertFinishedEvent
1900 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1901 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1902 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1903 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1904 touchConfiguration();
1907 public Optional<PostCreated> postCreated() {
1908 return Optional.<PostCreated>of(new PostCreated() {
1910 public void postCreated(final Post post) {
1911 if (post.isKnown()) {
1914 eventBus.post(new NewPostFoundEvent(post));
1915 if (post.getSone().isLocal()) {
1916 localElementTicker.schedule(new Runnable() {
1919 markPostKnown(post);
1921 }, 10, TimeUnit.SECONDS);
1927 public Optional<PostReplyCreated> postReplyCreated() {
1928 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1930 public void postReplyCreated(final PostReply postReply) {
1931 if (postReply.isKnown()) {
1934 eventBus.post(new NewPostReplyFoundEvent(postReply));
1935 if (postReply.getSone().isLocal()) {
1936 localElementTicker.schedule(new Runnable() {
1943 markReplyKnown(postReply);
1945 }, 10, TimeUnit.SECONDS);