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.ImageBuilder.ImageCreated;
73 import net.pterodactylus.sone.database.PostBuilder;
74 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
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, 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);
336 public Collection<Sone> getSones() {
337 synchronized (sones) {
338 return ImmutableSet.copyOf(sones.values());
343 public Optional<Sone> getSone(String id) {
344 synchronized (sones) {
345 return Optional.fromNullable(sones.get(id));
350 public Collection<Sone> getLocalSones() {
351 synchronized (sones) {
352 return from(sones.values()).filter(new Predicate<Sone>() {
355 public boolean apply(Sone sone) {
356 return sone.isLocal();
363 * Returns the local Sone with the given ID, optionally creating a new Sone.
367 * @return The Sone with the given ID, or {@code null}
369 public Optional<Sone> getLocalSone(String id) {
370 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
374 public Collection<Sone> getRemoteSones() {
375 synchronized (sones) {
376 return from(sones.values()).filter(new Predicate<Sone>() {
379 public boolean apply(Sone sone) {
380 return !sone.isLocal();
387 * Returns the remote Sone with the given ID.
390 * The ID of the remote Sone to get
391 * @return The Sone with the given ID
393 public Optional<Sone> getRemoteSone(String id) {
394 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
398 * Returns whether the given Sone has been modified.
401 * The Sone to check for modifications
402 * @return {@code true} if a modification has been detected in the Sone, {@code
405 public boolean isModifiedSone(Sone sone) {
406 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
410 * Returns the time when the given was first followed by any local Sone.
413 * The Sone to get the time for
414 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
415 * followed, or {@link Long#MAX_VALUE}
417 public long getSoneFollowingTime(Sone sone) {
418 synchronized (soneFollowingTimes) {
419 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
424 * Returns whether the target Sone is trusted by the origin Sone.
430 * @return {@code true} if the target Sone is trusted by the origin Sone
432 public boolean isSoneTrusted(Sone origin, Sone target) {
433 checkNotNull(origin, "origin must not be null");
434 checkNotNull(target, "target must not be null");
435 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
436 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
439 public Optional<Post> getPost(String postId) {
440 return database.getPost(postId);
443 public Collection<Post> getPosts(String soneId) {
444 return database.getPosts(soneId);
447 public Collection<Post> getDirectedPosts(final String recipientId) {
448 checkNotNull(recipientId, "recipient must not be null");
449 return database.getDirectedPosts(recipientId);
453 public Optional<PostReply> getPostReply(String replyId) {
454 return database.getPostReply(replyId);
458 public List<PostReply> getReplies(final String postId) {
459 return database.getReplies(postId);
463 * Returns all Sones that have liked the given post.
466 * The post to get the liking Sones for
467 * @return The Sones that like the given post
469 public Set<Sone> getLikes(Post post) {
470 Set<Sone> sones = new HashSet<Sone>();
471 for (Sone sone : getSones()) {
472 if (sone.getLikedPostIds().contains(post.getId())) {
480 * Returns all Sones that have liked the given reply.
483 * The reply to get the liking Sones for
484 * @return The Sones that like the given reply
486 public Set<Sone> getLikes(PostReply reply) {
487 Set<Sone> sones = new HashSet<Sone>();
488 for (Sone sone : getSones()) {
489 if (sone.getLikedReplyIds().contains(reply.getId())) {
497 * Returns whether the given post is bookmarked.
501 * @return {@code true} if the given post is bookmarked, {@code false}
504 public boolean isBookmarked(Post post) {
505 return isPostBookmarked(post.getId());
509 * Returns whether the post with the given ID is bookmarked.
512 * The ID of the post to check
513 * @return {@code true} if the post with the given ID is bookmarked, {@code
516 public boolean isPostBookmarked(String id) {
517 synchronized (bookmarkedPosts) {
518 return bookmarkedPosts.contains(id);
523 * Returns all currently known bookmarked posts.
525 * @return All bookmarked posts
527 public Set<Post> getBookmarkedPosts() {
528 Set<Post> posts = new HashSet<Post>();
529 synchronized (bookmarkedPosts) {
530 for (String bookmarkedPostId : bookmarkedPosts) {
531 Optional<Post> post = getPost(bookmarkedPostId);
532 if (post.isPresent()) {
533 posts.add(post.get());
540 public Optional<Album> getAlbum(String albumId) {
541 return database.getAlbum(albumId);
544 public Optional<Image> getImage(String imageId) {
545 return database.getImage(imageId);
549 * Returns the temporary image with the given ID.
552 * The ID of the temporary image
553 * @return The temporary image, or {@code null} if there is no temporary image
556 public TemporaryImage getTemporaryImage(String imageId) {
557 synchronized (temporaryImages) {
558 return temporaryImages.get(imageId);
567 * Locks the given Sone. A locked Sone will not be inserted by {@link
568 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
573 public void lockSone(Sone sone) {
574 synchronized (lockedSones) {
575 if (lockedSones.add(sone)) {
576 eventBus.post(new SoneLockedEvent(sone));
582 * Unlocks the given Sone.
586 * @see #lockSone(Sone)
588 public void unlockSone(Sone sone) {
589 synchronized (lockedSones) {
590 if (lockedSones.remove(sone)) {
591 eventBus.post(new SoneUnlockedEvent(sone));
597 * Adds a local Sone from the given own identity.
600 * The own identity to create a Sone from
601 * @return The added (or already existing) Sone
603 public Sone addLocalSone(OwnIdentity ownIdentity) {
604 if (ownIdentity == null) {
605 logger.log(Level.WARNING, "Given OwnIdentity is null!");
608 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
609 synchronized (sones) {
612 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
613 } catch (MalformedURLException mue1) {
614 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
617 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
618 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
620 /* TODO - load posts ’n stuff */
621 sones.put(ownIdentity.getId(), sone);
622 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
623 soneInserters.put(sone, soneInserter);
624 sone.setStatus(SoneStatus.idle);
626 soneInserter.start();
632 * Creates a new Sone for the given own identity.
635 * The own identity to create a Sone for
636 * @return The created Sone
638 public Sone createSone(OwnIdentity ownIdentity) {
639 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
640 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
643 Sone sone = addLocalSone(ownIdentity);
644 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
645 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
646 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
647 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
648 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
649 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
651 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
652 touchConfiguration();
657 * Adds the Sone of the given identity.
660 * The identity whose Sone to add
661 * @return The added or already existing Sone
663 public Sone addRemoteSone(Identity identity) {
664 if (identity == null) {
665 logger.log(Level.WARNING, "Given Identity is null!");
668 synchronized (sones) {
669 final Sone sone = database.newSoneBuilder().by(identity).build();
670 if (sone.isLocal()) {
673 sone.setIdentity(identity);
674 boolean newSone = sone.getRequestUri() == null;
675 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
676 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
678 synchronized (knownSones) {
679 newSone = !knownSones.contains(sone.getId());
681 sone.setKnown(!newSone);
683 eventBus.post(new NewSoneFoundEvent(sone));
684 for (Sone localSone : getLocalSones()) {
685 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
686 followSone(localSone, sone.getId());
691 soneDownloader.addSone(sone);
692 soneDownloaders.execute(new Runnable() {
695 @SuppressWarnings("synthetic-access")
697 soneDownloader.fetchSone(sone, sone.getRequestUri());
706 * Lets the given local Sone follow the Sone with the given ID.
709 * The local Sone that should follow another Sone
711 * The ID of the Sone to follow
713 public void followSone(Sone sone, String soneId) {
714 checkNotNull(sone, "sone must not be null");
715 checkNotNull(soneId, "soneId must not be null");
716 sone.addFriend(soneId);
717 synchronized (soneFollowingTimes) {
718 if (!soneFollowingTimes.containsKey(soneId)) {
719 long now = System.currentTimeMillis();
720 soneFollowingTimes.put(soneId, now);
721 Optional<Sone> followedSone = getSone(soneId);
722 if (!followedSone.isPresent()) {
725 for (Post post : followedSone.get().getPosts()) {
726 if (post.getTime() < now) {
730 for (PostReply reply : followedSone.get().getReplies()) {
731 if (reply.getTime() < now) {
732 markReplyKnown(reply);
737 touchConfiguration();
741 * Lets the given local Sone unfollow the Sone with the given ID.
744 * The local Sone that should unfollow another Sone
746 * The ID of the Sone being unfollowed
748 public void unfollowSone(Sone sone, String soneId) {
749 checkNotNull(sone, "sone must not be null");
750 checkNotNull(soneId, "soneId must not be null");
751 sone.removeFriend(soneId);
752 boolean unfollowedSoneStillFollowed = false;
753 for (Sone localSone : getLocalSones()) {
754 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
756 if (!unfollowedSoneStillFollowed) {
757 synchronized (soneFollowingTimes) {
758 soneFollowingTimes.remove(soneId);
761 touchConfiguration();
765 * Sets the trust value of the given origin Sone for the target Sone.
772 * The trust value (from {@code -100} to {@code 100})
774 public void setTrust(Sone origin, Sone target, int trustValue) {
775 checkNotNull(origin, "origin must not be null");
776 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
777 checkNotNull(target, "target must not be null");
778 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
779 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
783 * Removes any trust assignment for the given target Sone.
790 public void removeTrust(Sone origin, Sone target) {
791 checkNotNull(origin, "origin must not be null");
792 checkNotNull(target, "target must not be null");
793 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
794 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
798 * Assigns the configured positive trust value for the given target.
805 public void trustSone(Sone origin, Sone target) {
806 setTrust(origin, target, preferences.getPositiveTrust());
810 * Assigns the configured negative trust value for the given target.
817 public void distrustSone(Sone origin, Sone target) {
818 setTrust(origin, target, preferences.getNegativeTrust());
822 * Removes the trust assignment for the given target.
829 public void untrustSone(Sone origin, Sone target) {
830 removeTrust(origin, target);
834 * Updates the stored Sone with the given Sone.
839 public void updateSone(Sone sone) {
840 updateSone(sone, false);
844 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
845 * {@code true}, an older Sone than the current Sone can be given to restore an
850 * @param soneRescueMode
851 * {@code true} if the stored Sone should be updated regardless of the age of
854 public void updateSone(Sone sone, boolean soneRescueMode) {
855 Optional<Sone> storedSone = getSone(sone.getId());
856 if (storedSone.isPresent()) {
857 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
858 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
861 /* find removed posts. */
862 Collection<Post> existingPosts = database.getPosts(sone.getId());
863 for (Post oldPost : existingPosts) {
864 if (!sone.getPosts().contains(oldPost)) {
865 eventBus.post(new PostRemovedEvent(oldPost));
868 /* find new posts. */
869 for (Post newPost : sone.getPosts()) {
870 if (existingPosts.contains(newPost)) {
873 if (newPost.getTime() < getSoneFollowingTime(sone)) {
874 newPost.setKnown(true);
875 } else if (!newPost.isKnown()) {
876 eventBus.post(new NewPostFoundEvent(newPost));
880 database.storePosts(sone, sone.getPosts());
881 if (!soneRescueMode) {
882 for (PostReply reply : storedSone.get().getReplies()) {
883 if (!sone.getReplies().contains(reply)) {
884 eventBus.post(new PostReplyRemovedEvent(reply));
888 Set<PostReply> storedReplies = storedSone.get().getReplies();
889 for (PostReply reply : sone.getReplies()) {
890 if (storedReplies.contains(reply)) {
893 if (reply.getTime() < getSoneFollowingTime(sone)) {
894 reply.setKnown(true);
895 } else if (!reply.isKnown()) {
896 eventBus.post(new NewPostReplyFoundEvent(reply));
899 database.storePostReplies(sone, sone.getReplies());
900 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
901 database.removeAlbum(album);
902 for (Image image : album.getImages()) {
903 database.removeImage(image);
906 for (Album album : sone.getRootAlbum().getAlbums()) {
907 database.storeAlbum(album);
908 for (Image image : album.getImages()) {
909 database.storeImage(image);
912 synchronized (sones) {
913 sone.setOptions(storedSone.get().getOptions());
914 sone.setKnown(storedSone.get().isKnown());
915 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
916 if (sone.isLocal()) {
917 soneInserters.get(storedSone.get()).setSone(sone);
918 touchConfiguration();
920 sones.put(sone.getId(), sone);
926 * Deletes the given Sone. This will remove the Sone from the {@link
927 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
928 * context from its identity.
933 public void deleteSone(Sone sone) {
934 if (!(sone.getIdentity() instanceof OwnIdentity)) {
935 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
938 synchronized (sones) {
939 if (!getLocalSones().contains(sone)) {
940 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
943 sones.remove(sone.getId());
944 SoneInserter soneInserter = soneInserters.remove(sone);
947 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
948 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
950 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
951 } catch (ConfigurationException ce1) {
952 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
957 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
958 * known} before, a {@link MarkSoneKnownEvent} is fired.
961 * The Sone to mark as known
963 public void markSoneKnown(Sone sone) {
964 if (!sone.isKnown()) {
966 synchronized (knownSones) {
967 knownSones.add(sone.getId());
969 eventBus.post(new MarkSoneKnownEvent(sone));
970 touchConfiguration();
975 * Loads and updates the given Sone from the configuration. If any error is
976 * encountered, loading is aborted and the given Sone is not changed.
979 * The Sone to load and update
981 public void loadSone(Sone sone) {
982 if (!sone.isLocal()) {
983 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
986 logger.info(String.format("Loading local Sone: %s", sone));
988 /* initialize options. */
989 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
990 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
991 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
992 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
993 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
994 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
997 String sonePrefix = "Sone/" + sone.getId();
998 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
999 if (soneTime == null) {
1000 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1003 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1006 Profile profile = new Profile(sone);
1007 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1008 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1009 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1010 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1011 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1012 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1014 /* load profile fields. */
1016 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1017 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1018 if (fieldName == null) {
1021 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1022 profile.addField(fieldName).setValue(fieldValue);
1026 Set<Post> posts = new HashSet<Post>();
1028 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1029 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1030 if (postId == null) {
1033 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1034 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1035 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1036 if ((postTime == 0) || (postText == null)) {
1037 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1040 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
1041 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1042 postBuilder.to(of(postRecipientId));
1044 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1048 Set<PostReply> replies = new HashSet<PostReply>();
1050 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1051 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1052 if (replyId == null) {
1055 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1056 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1057 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1058 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1059 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1062 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1063 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1066 /* load post likes. */
1067 Set<String> likedPostIds = new HashSet<String>();
1069 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1070 if (likedPostId == null) {
1073 likedPostIds.add(likedPostId);
1076 /* load reply likes. */
1077 Set<String> likedReplyIds = new HashSet<String>();
1079 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1080 if (likedReplyId == null) {
1083 likedReplyIds.add(likedReplyId);
1087 Set<String> friends = new HashSet<String>();
1089 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1090 if (friendId == null) {
1093 friends.add(friendId);
1097 Map<String, Album> albums = Maps.newHashMap();
1098 int albumCounter = 0;
1100 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1101 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1102 if (albumId == null) {
1105 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1106 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1107 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1108 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1109 if ((albumTitle == null) || (albumDescription == null)) {
1110 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1113 Album parentAlbum = sone.getRootAlbum();
1114 if (albumParentId != null) {
1115 parentAlbum = albums.get(albumParentId);
1117 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1118 albums.put(album.getId(), album);
1122 int imageCounter = 0;
1124 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1125 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1126 if (imageId == null) {
1129 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1130 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1131 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1132 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1133 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1134 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1135 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1136 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1137 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1140 Album album = albums.get(albumId);
1141 if (album == null) {
1142 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1145 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1149 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1150 if (avatarId != null) {
1151 profile.setAvatar(getImage(avatarId).orNull());
1155 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1156 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1157 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1158 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1159 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1160 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1162 /* if we’re still here, Sone was loaded successfully. */
1163 synchronized (sone) {
1164 sone.setTime(soneTime);
1165 sone.setProfile(profile);
1166 sone.setPosts(posts);
1167 sone.setReplies(replies);
1168 sone.setLikePostIds(likedPostIds);
1169 sone.setLikeReplyIds(likedReplyIds);
1170 for (String friendId : friends) {
1171 followSone(sone, friendId);
1173 for (Album album : sone.getRootAlbum().getAlbums()) {
1176 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1178 synchronized (knownSones) {
1179 for (String friend : friends) {
1180 knownSones.add(friend);
1183 database.storePosts(sone, posts);
1184 for (Post post : posts) {
1185 post.setKnown(true);
1187 database.storePostReplies(sone, replies);
1188 for (PostReply reply : replies) {
1189 reply.setKnown(true);
1192 logger.info(String.format("Sone loaded successfully: %s", sone));
1196 * Deletes the given post.
1199 * The post to delete
1201 public void deletePost(Post post) {
1202 if (!post.getSone().isLocal()) {
1203 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1206 database.removePost(post);
1207 eventBus.post(new PostRemovedEvent(post));
1208 markPostKnown(post);
1209 touchConfiguration();
1213 * Marks the given post as known, if it is currently not a known post
1214 * (according to {@link Post#isKnown()}).
1217 * The post to mark as known
1219 public void markPostKnown(Post post) {
1220 post.setKnown(true);
1221 eventBus.post(new MarkPostKnownEvent(post));
1222 touchConfiguration();
1223 for (PostReply reply : getReplies(post.getId())) {
1224 markReplyKnown(reply);
1229 * Bookmarks the given post.
1232 * The post to bookmark
1234 public void bookmark(Post post) {
1235 bookmarkPost(post.getId());
1239 * Bookmarks the post with the given ID.
1242 * The ID of the post to bookmark
1244 public void bookmarkPost(String id) {
1245 synchronized (bookmarkedPosts) {
1246 bookmarkedPosts.add(id);
1251 * Removes the given post from the bookmarks.
1254 * The post to unbookmark
1256 public void unbookmark(Post post) {
1257 unbookmarkPost(post.getId());
1261 * Removes the post with the given ID from the bookmarks.
1264 * The ID of the post to unbookmark
1266 public void unbookmarkPost(String id) {
1267 synchronized (bookmarkedPosts) {
1268 bookmarkedPosts.remove(id);
1273 * Deletes the given reply.
1276 * The reply to delete
1278 public void deleteReply(PostReply reply) {
1279 Sone sone = reply.getSone();
1280 if (!sone.isLocal()) {
1281 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1284 database.removePostReply(reply);
1285 markReplyKnown(reply);
1286 sone.removeReply(reply);
1287 touchConfiguration();
1291 * Marks the given reply as known, if it is currently not a known reply
1292 * (according to {@link Reply#isKnown()}).
1295 * The reply to mark as known
1297 public void markReplyKnown(PostReply reply) {
1298 boolean previouslyKnown = reply.isKnown();
1299 reply.setKnown(true);
1300 eventBus.post(new MarkPostReplyKnownEvent(reply));
1301 if (!previouslyKnown) {
1302 touchConfiguration();
1307 * Creates a new image.
1310 * The Sone creating the image
1312 * The album the image will be inserted into
1313 * @param temporaryImage
1314 * The temporary image to create the image from
1315 * @return The newly created image
1317 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1318 checkNotNull(sone, "sone must not be null");
1319 checkNotNull(album, "album must not be null");
1320 checkNotNull(temporaryImage, "temporaryImage must not be null");
1321 checkArgument(sone.isLocal(), "sone must be a local Sone");
1322 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1323 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1324 imageInserter.insertImage(temporaryImage, image);
1329 * Deletes the given image. This method will also delete a matching temporary
1333 * The image to delete
1334 * @see #deleteTemporaryImage(TemporaryImage)
1336 public void deleteImage(Image image) {
1337 checkNotNull(image, "image must not be null");
1338 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1339 deleteTemporaryImage(image.getId());
1341 touchConfiguration();
1345 * Creates a new temporary image.
1348 * The MIME type of the temporary image
1350 * The encoded data of the image
1351 * @return The temporary image
1353 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1354 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1355 synchronized (temporaryImages) {
1356 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1358 return temporaryImage;
1362 * Deletes the given temporary image.
1364 * @param temporaryImage
1365 * The temporary image to delete
1367 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1368 checkNotNull(temporaryImage, "temporaryImage must not be null");
1369 deleteTemporaryImage(temporaryImage.getId());
1373 * Deletes the temporary image with the given ID.
1376 * The ID of the temporary image to delete
1378 public void deleteTemporaryImage(String imageId) {
1379 checkNotNull(imageId, "imageId must not be null");
1380 synchronized (temporaryImages) {
1381 temporaryImages.remove(imageId);
1383 Optional<Image> image = getImage(imageId);
1384 if (image.isPresent()) {
1385 imageInserter.cancelImageInsert(image.get());
1390 * Notifies the core that the configuration, either of the core or of a single
1391 * local Sone, has changed, and that the configuration should be saved.
1393 public void touchConfiguration() {
1394 lastConfigurationUpdate = System.currentTimeMillis();
1402 public void serviceStart() {
1403 loadConfiguration();
1404 updateChecker.start();
1405 identityManager.start();
1406 webOfTrustUpdater.init();
1407 webOfTrustUpdater.start();
1412 public void serviceRun() {
1413 long lastSaved = System.currentTimeMillis();
1414 while (!shouldStop()) {
1416 long now = System.currentTimeMillis();
1417 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1418 for (Sone localSone : getLocalSones()) {
1419 saveSone(localSone);
1421 saveConfiguration();
1428 public void serviceStop() {
1429 localElementTicker.shutdownNow();
1430 synchronized (sones) {
1431 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1432 soneInserter.getValue().stop();
1433 saveSone(soneInserter.getKey());
1436 saveConfiguration();
1438 webOfTrustUpdater.stop();
1439 updateChecker.stop();
1440 soneDownloader.stop();
1441 soneDownloaders.shutdown();
1442 identityManager.stop();
1450 * Saves the given Sone. This will persist all local settings for the given
1451 * Sone, such as the friends list and similar, private options.
1456 private synchronized void saveSone(Sone sone) {
1457 if (!sone.isLocal()) {
1458 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1461 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1462 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1466 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1468 /* save Sone into configuration. */
1469 String sonePrefix = "Sone/" + sone.getId();
1470 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1471 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1474 Profile profile = sone.getProfile();
1475 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1476 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1477 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1478 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1479 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1480 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1481 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1483 /* save profile fields. */
1484 int fieldCounter = 0;
1485 for (Field profileField : profile.getFields()) {
1486 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1487 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1488 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1490 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1493 int postCounter = 0;
1494 for (Post post : sone.getPosts()) {
1495 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1496 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1497 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1498 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1499 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1501 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1504 int replyCounter = 0;
1505 for (PostReply reply : sone.getReplies()) {
1506 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1507 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1508 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1509 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1510 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1512 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1514 /* save post likes. */
1515 int postLikeCounter = 0;
1516 for (String postId : sone.getLikedPostIds()) {
1517 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1519 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1521 /* save reply likes. */
1522 int replyLikeCounter = 0;
1523 for (String replyId : sone.getLikedReplyIds()) {
1524 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1526 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1529 int friendCounter = 0;
1530 for (String friendId : sone.getFriends()) {
1531 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1533 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1535 /* save albums. first, collect in a flat structure, top-level first. */
1536 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1538 int albumCounter = 0;
1539 for (Album album : albums) {
1540 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1541 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1542 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1543 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1544 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1545 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1547 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1550 int imageCounter = 0;
1551 for (Album album : albums) {
1552 for (Image image : album.getImages()) {
1553 if (!image.isInserted()) {
1556 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1557 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1558 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1559 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1560 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1561 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1562 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1563 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1564 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1567 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1570 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1571 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1572 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1573 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1574 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1575 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1577 configuration.save();
1579 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1581 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1582 } catch (ConfigurationException ce1) {
1583 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1587 /** Saves the current options. */
1588 private void saveConfiguration() {
1589 synchronized (configuration) {
1590 if (storingConfiguration) {
1591 logger.log(Level.FINE, "Already storing configuration…");
1594 storingConfiguration = true;
1597 /* store the options first. */
1599 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1600 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1601 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1602 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1603 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1604 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1605 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1606 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1607 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1608 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1609 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1610 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1612 /* save known Sones. */
1613 int soneCounter = 0;
1614 synchronized (knownSones) {
1615 for (String knownSoneId : knownSones) {
1616 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1618 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1621 /* save Sone following times. */
1623 synchronized (soneFollowingTimes) {
1624 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1625 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1626 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1629 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1632 /* save known posts. */
1635 /* save bookmarked posts. */
1636 int bookmarkedPostCounter = 0;
1637 synchronized (bookmarkedPosts) {
1638 for (String bookmarkedPostId : bookmarkedPosts) {
1639 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1642 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1645 configuration.save();
1647 } catch (ConfigurationException ce1) {
1648 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1649 } catch (DatabaseException de1) {
1650 logger.log(Level.SEVERE, "Could not save database!", de1);
1652 synchronized (configuration) {
1653 storingConfiguration = false;
1658 /** Loads the configuration. */
1659 private void loadConfiguration() {
1660 /* create options. */
1661 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1664 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1665 SoneInserter.setInsertionDelay(newValue);
1669 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1670 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1671 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1672 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1673 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1674 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1675 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1676 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1677 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1680 @SuppressWarnings("synthetic-access")
1681 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1682 fcpInterface.setActive(newValue);
1685 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1688 @SuppressWarnings("synthetic-access")
1689 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1690 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1695 loadConfigurationValue("InsertionDelay");
1696 loadConfigurationValue("PostsPerPage");
1697 loadConfigurationValue("ImagesPerPage");
1698 loadConfigurationValue("CharactersPerPost");
1699 loadConfigurationValue("PostCutOffLength");
1700 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1701 loadConfigurationValue("PositiveTrust");
1702 loadConfigurationValue("NegativeTrust");
1703 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1704 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1705 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1707 /* load known Sones. */
1708 int soneCounter = 0;
1710 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1711 if (knownSoneId == null) {
1714 synchronized (knownSones) {
1715 knownSones.add(knownSoneId);
1719 /* load Sone following times. */
1722 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1723 if (soneId == null) {
1726 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1727 synchronized (soneFollowingTimes) {
1728 soneFollowingTimes.put(soneId, time);
1733 /* load bookmarked posts. */
1734 int bookmarkedPostCounter = 0;
1736 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1737 if (bookmarkedPostId == null) {
1740 synchronized (bookmarkedPosts) {
1741 bookmarkedPosts.add(bookmarkedPostId);
1748 * Loads an {@link Integer} configuration value for the option with the given
1749 * name, logging validation failures.
1752 * The name of the option to load
1754 private void loadConfigurationValue(String optionName) {
1756 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1757 } catch (IllegalArgumentException iae1) {
1758 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1763 * Notifies the core that a new {@link OwnIdentity} was added.
1765 * @param ownIdentityAddedEvent
1769 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1770 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1771 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1772 if (ownIdentity.hasContext("Sone")) {
1773 addLocalSone(ownIdentity);
1778 * Notifies the core that an {@link OwnIdentity} was removed.
1780 * @param ownIdentityRemovedEvent
1784 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1785 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1786 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1787 trustedIdentities.removeAll(ownIdentity);
1791 * Notifies the core that a new {@link Identity} was added.
1793 * @param identityAddedEvent
1797 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1798 Identity identity = identityAddedEvent.identity();
1799 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1800 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1801 addRemoteSone(identity);
1805 * Notifies the core that an {@link Identity} was updated.
1807 * @param identityUpdatedEvent
1811 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1812 final Identity identity = identityUpdatedEvent.identity();
1813 soneDownloaders.execute(new Runnable() {
1816 @SuppressWarnings("synthetic-access")
1818 Optional<Sone> sone = getRemoteSone(identity.getId());
1819 sone.get().setIdentity(identity);
1820 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1821 soneDownloader.addSone(sone.get());
1822 soneDownloader.fetchSone(sone.get());
1828 * Notifies the core that an {@link Identity} was removed.
1830 * @param identityRemovedEvent
1834 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1835 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1836 Identity identity = identityRemovedEvent.identity();
1837 trustedIdentities.remove(ownIdentity, identity);
1838 boolean foundIdentity = false;
1839 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1840 if (trustedIdentity.getKey().equals(ownIdentity)) {
1843 if (trustedIdentity.getValue().contains(identity)) {
1844 foundIdentity = true;
1847 if (foundIdentity) {
1848 /* some local identity still trusts this identity, don’t remove. */
1851 Optional<Sone> sone = getSone(identity.getId());
1852 if (!sone.isPresent()) {
1853 /* TODO - we don’t have the Sone anymore. should this happen? */
1856 database.removePosts(sone.get());
1857 for (Post post : sone.get().getPosts()) {
1858 eventBus.post(new PostRemovedEvent(post));
1860 database.removePostReplies(sone.get());
1861 for (PostReply reply : sone.get().getReplies()) {
1862 eventBus.post(new PostReplyRemovedEvent(reply));
1864 synchronized (sones) {
1865 sones.remove(identity.getId());
1867 eventBus.post(new SoneRemovedEvent(sone.get()));
1871 * Deletes the temporary image.
1873 * @param imageInsertFinishedEvent
1877 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1878 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1879 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1880 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1881 touchConfiguration();
1884 public Optional<PostCreated> postCreated() {
1885 return Optional.<PostCreated>of(new PostCreated() {
1887 public void postCreated(final Post post) {
1888 if (post.isKnown()) {
1891 eventBus.post(new NewPostFoundEvent(post));
1892 if (post.getSone().isLocal()) {
1893 localElementTicker.schedule(new Runnable() {
1896 markPostKnown(post);
1898 }, 10, TimeUnit.SECONDS);
1904 public Optional<PostReplyCreated> postReplyCreated() {
1905 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1907 public void postReplyCreated(final PostReply postReply) {
1908 if (postReply.isKnown()) {
1911 eventBus.post(new NewPostReplyFoundEvent(postReply));
1912 if (postReply.getSone().isLocal()) {
1913 localElementTicker.schedule(new Runnable() {
1920 markReplyKnown(postReply);
1922 }, 10, TimeUnit.SECONDS);
1928 public Optional<ImageCreated> imageCreated() {
1929 return Optional.<ImageCreated>of(new ImageCreated() {
1931 public void imageCreated(Image image) {
1932 /* nothing happens here yet. */