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());
440 public Optional<PostReply> getPostReply(String replyId) {
441 return database.getPostReply(replyId);
445 public List<PostReply> getReplies(final String postId) {
446 return database.getReplies(postId);
450 * Returns all Sones that have liked the given post.
453 * The post to get the liking Sones for
454 * @return The Sones that like the given post
456 public Set<Sone> getLikes(Post post) {
457 Set<Sone> sones = new HashSet<Sone>();
458 for (Sone sone : getSones()) {
459 if (sone.getLikedPostIds().contains(post.getId())) {
467 * Returns all Sones that have liked the given reply.
470 * The reply to get the liking Sones for
471 * @return The Sones that like the given reply
473 public Set<Sone> getLikes(PostReply reply) {
474 Set<Sone> sones = new HashSet<Sone>();
475 for (Sone sone : getSones()) {
476 if (sone.getLikedReplyIds().contains(reply.getId())) {
484 * Returns whether the given post is bookmarked.
488 * @return {@code true} if the given post is bookmarked, {@code false}
491 public boolean isBookmarked(Post post) {
492 return isPostBookmarked(post.getId());
496 * Returns whether the post with the given ID is bookmarked.
499 * The ID of the post to check
500 * @return {@code true} if the post with the given ID is bookmarked, {@code
503 public boolean isPostBookmarked(String id) {
504 synchronized (bookmarkedPosts) {
505 return bookmarkedPosts.contains(id);
510 * Returns all currently known bookmarked posts.
512 * @return All bookmarked posts
514 public Set<Post> getBookmarkedPosts() {
515 Set<Post> posts = new HashSet<Post>();
516 synchronized (bookmarkedPosts) {
517 for (String bookmarkedPostId : bookmarkedPosts) {
518 Optional<Post> post = database.getPost(bookmarkedPostId);
519 if (post.isPresent()) {
520 posts.add(post.get());
527 public Optional<Album> getAlbum(String albumId) {
528 return database.getAlbum(albumId);
531 public Optional<Image> getImage(String imageId) {
532 return database.getImage(imageId);
536 * Returns the temporary image with the given ID.
539 * The ID of the temporary image
540 * @return The temporary image, or {@code null} if there is no temporary image
543 public TemporaryImage getTemporaryImage(String imageId) {
544 synchronized (temporaryImages) {
545 return temporaryImages.get(imageId);
554 * Locks the given Sone. A locked Sone will not be inserted by {@link
555 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
560 public void lockSone(Sone sone) {
561 synchronized (lockedSones) {
562 if (lockedSones.add(sone)) {
563 eventBus.post(new SoneLockedEvent(sone));
569 * Unlocks the given Sone.
573 * @see #lockSone(Sone)
575 public void unlockSone(Sone sone) {
576 synchronized (lockedSones) {
577 if (lockedSones.remove(sone)) {
578 eventBus.post(new SoneUnlockedEvent(sone));
584 * Adds a local Sone from the given own identity.
587 * The own identity to create a Sone from
588 * @return The added (or already existing) Sone
590 public Sone addLocalSone(OwnIdentity ownIdentity) {
591 if (ownIdentity == null) {
592 logger.log(Level.WARNING, "Given OwnIdentity is null!");
595 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
596 synchronized (sones) {
599 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
600 } catch (MalformedURLException mue1) {
601 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
604 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
605 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
607 /* TODO - load posts ’n stuff */
608 sones.put(ownIdentity.getId(), sone);
609 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
610 soneInserters.put(sone, soneInserter);
611 sone.setStatus(SoneStatus.idle);
613 soneInserter.start();
619 * Creates a new Sone for the given own identity.
622 * The own identity to create a Sone for
623 * @return The created Sone
625 public Sone createSone(OwnIdentity ownIdentity) {
626 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
627 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
630 Sone sone = addLocalSone(ownIdentity);
631 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
632 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
633 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
634 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
635 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
636 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
638 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
639 touchConfiguration();
644 * Adds the Sone of the given identity.
647 * The identity whose Sone to add
648 * @return The added or already existing Sone
650 public Sone addRemoteSone(Identity identity) {
651 if (identity == null) {
652 logger.log(Level.WARNING, "Given Identity is null!");
655 synchronized (sones) {
656 final Sone sone = database.newSoneBuilder().by(identity).build();
657 if (sone.isLocal()) {
660 sone.setIdentity(identity);
661 boolean newSone = sone.getRequestUri() == null;
662 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
663 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
665 synchronized (knownSones) {
666 newSone = !knownSones.contains(sone.getId());
668 sone.setKnown(!newSone);
670 eventBus.post(new NewSoneFoundEvent(sone));
671 for (Sone localSone : getLocalSones()) {
672 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
673 followSone(localSone, sone.getId());
678 soneDownloader.addSone(sone);
679 soneDownloaders.execute(new Runnable() {
682 @SuppressWarnings("synthetic-access")
684 soneDownloader.fetchSone(sone, sone.getRequestUri());
693 * Lets the given local Sone follow the Sone with the given ID.
696 * The local Sone that should follow another Sone
698 * The ID of the Sone to follow
700 public void followSone(Sone sone, String soneId) {
701 checkNotNull(sone, "sone must not be null");
702 checkNotNull(soneId, "soneId must not be null");
703 sone.addFriend(soneId);
704 synchronized (soneFollowingTimes) {
705 if (!soneFollowingTimes.containsKey(soneId)) {
706 long now = System.currentTimeMillis();
707 soneFollowingTimes.put(soneId, now);
708 Optional<Sone> followedSone = getSone(soneId);
709 if (!followedSone.isPresent()) {
712 for (Post post : followedSone.get().getPosts()) {
713 if (post.getTime() < now) {
717 for (PostReply reply : followedSone.get().getReplies()) {
718 if (reply.getTime() < now) {
719 markReplyKnown(reply);
724 touchConfiguration();
728 * Lets the given local Sone unfollow the Sone with the given ID.
731 * The local Sone that should unfollow another Sone
733 * The ID of the Sone being unfollowed
735 public void unfollowSone(Sone sone, String soneId) {
736 checkNotNull(sone, "sone must not be null");
737 checkNotNull(soneId, "soneId must not be null");
738 sone.removeFriend(soneId);
739 boolean unfollowedSoneStillFollowed = false;
740 for (Sone localSone : getLocalSones()) {
741 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
743 if (!unfollowedSoneStillFollowed) {
744 synchronized (soneFollowingTimes) {
745 soneFollowingTimes.remove(soneId);
748 touchConfiguration();
752 * Sets the trust value of the given origin Sone for the target Sone.
759 * The trust value (from {@code -100} to {@code 100})
761 public void setTrust(Sone origin, Sone target, int trustValue) {
762 checkNotNull(origin, "origin must not be null");
763 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
764 checkNotNull(target, "target must not be null");
765 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
766 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
770 * Removes any trust assignment for the given target Sone.
777 public void removeTrust(Sone origin, Sone target) {
778 checkNotNull(origin, "origin must not be null");
779 checkNotNull(target, "target must not be null");
780 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
781 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
785 * Assigns the configured positive trust value for the given target.
792 public void trustSone(Sone origin, Sone target) {
793 setTrust(origin, target, preferences.getPositiveTrust());
797 * Assigns the configured negative trust value for the given target.
804 public void distrustSone(Sone origin, Sone target) {
805 setTrust(origin, target, preferences.getNegativeTrust());
809 * Removes the trust assignment for the given target.
816 public void untrustSone(Sone origin, Sone target) {
817 removeTrust(origin, target);
821 * Updates the stored Sone with the given Sone.
826 public void updateSone(Sone sone) {
827 updateSone(sone, false);
831 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
832 * {@code true}, an older Sone than the current Sone can be given to restore an
837 * @param soneRescueMode
838 * {@code true} if the stored Sone should be updated regardless of the age of
841 public void updateSone(Sone sone, boolean soneRescueMode) {
842 Optional<Sone> storedSone = getSone(sone.getId());
843 if (storedSone.isPresent()) {
844 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
845 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
848 /* find removed posts. */
849 Collection<Post> existingPosts = database.getPosts(sone.getId());
850 for (Post oldPost : existingPosts) {
851 if (!sone.getPosts().contains(oldPost)) {
852 eventBus.post(new PostRemovedEvent(oldPost));
855 /* find new posts. */
856 for (Post newPost : sone.getPosts()) {
857 if (existingPosts.contains(newPost)) {
860 if (newPost.getTime() < getSoneFollowingTime(sone)) {
861 newPost.setKnown(true);
862 } else if (!newPost.isKnown()) {
863 eventBus.post(new NewPostFoundEvent(newPost));
867 database.storePosts(sone, sone.getPosts());
868 if (!soneRescueMode) {
869 for (PostReply reply : storedSone.get().getReplies()) {
870 if (!sone.getReplies().contains(reply)) {
871 eventBus.post(new PostReplyRemovedEvent(reply));
875 Set<PostReply> storedReplies = storedSone.get().getReplies();
876 for (PostReply reply : sone.getReplies()) {
877 if (storedReplies.contains(reply)) {
880 if (reply.getTime() < getSoneFollowingTime(sone)) {
881 reply.setKnown(true);
882 } else if (!reply.isKnown()) {
883 eventBus.post(new NewPostReplyFoundEvent(reply));
886 database.storePostReplies(sone, sone.getReplies());
887 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
888 database.removeAlbum(album);
889 for (Image image : album.getImages()) {
890 database.removeImage(image);
893 for (Album album : sone.getRootAlbum().getAlbums()) {
894 database.storeAlbum(album);
895 for (Image image : album.getImages()) {
896 database.storeImage(image);
899 synchronized (sones) {
900 sone.setOptions(storedSone.get().getOptions());
901 sone.setKnown(storedSone.get().isKnown());
902 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
903 if (sone.isLocal()) {
904 soneInserters.get(storedSone.get()).setSone(sone);
905 touchConfiguration();
907 sones.put(sone.getId(), sone);
913 * Deletes the given Sone. This will remove the Sone from the {@link
914 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
915 * context from its identity.
920 public void deleteSone(Sone sone) {
921 if (!(sone.getIdentity() instanceof OwnIdentity)) {
922 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
925 synchronized (sones) {
926 if (!getLocalSones().contains(sone)) {
927 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
930 sones.remove(sone.getId());
931 SoneInserter soneInserter = soneInserters.remove(sone);
934 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
935 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
937 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
938 } catch (ConfigurationException ce1) {
939 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
944 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
945 * known} before, a {@link MarkSoneKnownEvent} is fired.
948 * The Sone to mark as known
950 public void markSoneKnown(Sone sone) {
951 if (!sone.isKnown()) {
953 synchronized (knownSones) {
954 knownSones.add(sone.getId());
956 eventBus.post(new MarkSoneKnownEvent(sone));
957 touchConfiguration();
962 * Loads and updates the given Sone from the configuration. If any error is
963 * encountered, loading is aborted and the given Sone is not changed.
966 * The Sone to load and update
968 public void loadSone(Sone sone) {
969 if (!sone.isLocal()) {
970 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
973 logger.info(String.format("Loading local Sone: %s", sone));
975 /* initialize options. */
976 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
977 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
978 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
979 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
980 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
981 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
984 String sonePrefix = "Sone/" + sone.getId();
985 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
986 if (soneTime == null) {
987 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
990 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
993 Profile profile = new Profile(sone);
994 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
995 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
996 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
997 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
998 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
999 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1001 /* load profile fields. */
1003 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1004 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1005 if (fieldName == null) {
1008 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1009 profile.addField(fieldName).setValue(fieldValue);
1013 Set<Post> posts = new HashSet<Post>();
1015 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1016 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1017 if (postId == null) {
1020 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1021 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1022 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1023 if ((postTime == 0) || (postText == null)) {
1024 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1027 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
1028 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1029 postBuilder.to(of(postRecipientId));
1031 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1035 Set<PostReply> replies = new HashSet<PostReply>();
1037 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1038 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1039 if (replyId == null) {
1042 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1043 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1044 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1045 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1046 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1049 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1050 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1053 /* load post likes. */
1054 Set<String> likedPostIds = new HashSet<String>();
1056 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1057 if (likedPostId == null) {
1060 likedPostIds.add(likedPostId);
1063 /* load reply likes. */
1064 Set<String> likedReplyIds = new HashSet<String>();
1066 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1067 if (likedReplyId == null) {
1070 likedReplyIds.add(likedReplyId);
1074 Set<String> friends = new HashSet<String>();
1076 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1077 if (friendId == null) {
1080 friends.add(friendId);
1084 Map<String, Album> albums = Maps.newHashMap();
1085 int albumCounter = 0;
1087 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1088 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1089 if (albumId == null) {
1092 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1093 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1094 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1095 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1096 if ((albumTitle == null) || (albumDescription == null)) {
1097 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1100 Album parentAlbum = sone.getRootAlbum();
1101 if (albumParentId != null) {
1102 parentAlbum = albums.get(albumParentId);
1104 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1105 albums.put(album.getId(), album);
1109 int imageCounter = 0;
1111 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1112 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1113 if (imageId == null) {
1116 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1117 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1118 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1119 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1120 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1121 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1122 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1123 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1124 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1127 Album album = albums.get(albumId);
1128 if (album == null) {
1129 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1132 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1136 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1137 if (avatarId != null) {
1138 profile.setAvatar(getImage(avatarId).orNull());
1142 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1143 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1144 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1145 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1146 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1147 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1149 /* if we’re still here, Sone was loaded successfully. */
1150 synchronized (sone) {
1151 sone.setTime(soneTime);
1152 sone.setProfile(profile);
1153 sone.setPosts(posts);
1154 sone.setReplies(replies);
1155 sone.setLikePostIds(likedPostIds);
1156 sone.setLikeReplyIds(likedReplyIds);
1157 for (String friendId : friends) {
1158 followSone(sone, friendId);
1160 for (Album album : sone.getRootAlbum().getAlbums()) {
1163 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1165 synchronized (knownSones) {
1166 for (String friend : friends) {
1167 knownSones.add(friend);
1170 database.storePosts(sone, posts);
1171 for (Post post : posts) {
1172 post.setKnown(true);
1174 database.storePostReplies(sone, replies);
1175 for (PostReply reply : replies) {
1176 reply.setKnown(true);
1179 logger.info(String.format("Sone loaded successfully: %s", sone));
1183 * Deletes the given post.
1186 * The post to delete
1188 public void deletePost(Post post) {
1189 if (!post.getSone().isLocal()) {
1190 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1193 database.removePost(post);
1194 eventBus.post(new PostRemovedEvent(post));
1195 markPostKnown(post);
1196 touchConfiguration();
1200 * Marks the given post as known, if it is currently not a known post
1201 * (according to {@link Post#isKnown()}).
1204 * The post to mark as known
1206 public void markPostKnown(Post post) {
1207 post.setKnown(true);
1208 eventBus.post(new MarkPostKnownEvent(post));
1209 touchConfiguration();
1210 for (PostReply reply : getReplies(post.getId())) {
1211 markReplyKnown(reply);
1216 * Bookmarks the given post.
1219 * The post to bookmark
1221 public void bookmark(Post post) {
1222 bookmarkPost(post.getId());
1226 * Bookmarks the post with the given ID.
1229 * The ID of the post to bookmark
1231 public void bookmarkPost(String id) {
1232 synchronized (bookmarkedPosts) {
1233 bookmarkedPosts.add(id);
1238 * Removes the given post from the bookmarks.
1241 * The post to unbookmark
1243 public void unbookmark(Post post) {
1244 unbookmarkPost(post.getId());
1248 * Removes the post with the given ID from the bookmarks.
1251 * The ID of the post to unbookmark
1253 public void unbookmarkPost(String id) {
1254 synchronized (bookmarkedPosts) {
1255 bookmarkedPosts.remove(id);
1260 * Deletes the given reply.
1263 * The reply to delete
1265 public void deleteReply(PostReply reply) {
1266 Sone sone = reply.getSone();
1267 if (!sone.isLocal()) {
1268 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1271 database.removePostReply(reply);
1272 markReplyKnown(reply);
1273 sone.removeReply(reply);
1274 touchConfiguration();
1278 * Marks the given reply as known, if it is currently not a known reply
1279 * (according to {@link Reply#isKnown()}).
1282 * The reply to mark as known
1284 public void markReplyKnown(PostReply reply) {
1285 boolean previouslyKnown = reply.isKnown();
1286 reply.setKnown(true);
1287 eventBus.post(new MarkPostReplyKnownEvent(reply));
1288 if (!previouslyKnown) {
1289 touchConfiguration();
1294 * Creates a new image.
1297 * The Sone creating the image
1299 * The album the image will be inserted into
1300 * @param temporaryImage
1301 * The temporary image to create the image from
1302 * @return The newly created image
1304 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1305 checkNotNull(sone, "sone must not be null");
1306 checkNotNull(album, "album must not be null");
1307 checkNotNull(temporaryImage, "temporaryImage must not be null");
1308 checkArgument(sone.isLocal(), "sone must be a local Sone");
1309 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1310 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1311 imageInserter.insertImage(temporaryImage, image);
1316 * Deletes the given image. This method will also delete a matching temporary
1320 * The image to delete
1321 * @see #deleteTemporaryImage(TemporaryImage)
1323 public void deleteImage(Image image) {
1324 checkNotNull(image, "image must not be null");
1325 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1326 deleteTemporaryImage(image.getId());
1328 touchConfiguration();
1332 * Creates a new temporary image.
1335 * The MIME type of the temporary image
1337 * The encoded data of the image
1338 * @return The temporary image
1340 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1341 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1342 synchronized (temporaryImages) {
1343 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1345 return temporaryImage;
1349 * Deletes the given temporary image.
1351 * @param temporaryImage
1352 * The temporary image to delete
1354 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1355 checkNotNull(temporaryImage, "temporaryImage must not be null");
1356 deleteTemporaryImage(temporaryImage.getId());
1360 * Deletes the temporary image with the given ID.
1363 * The ID of the temporary image to delete
1365 public void deleteTemporaryImage(String imageId) {
1366 checkNotNull(imageId, "imageId must not be null");
1367 synchronized (temporaryImages) {
1368 temporaryImages.remove(imageId);
1370 Optional<Image> image = getImage(imageId);
1371 if (image.isPresent()) {
1372 imageInserter.cancelImageInsert(image.get());
1377 * Notifies the core that the configuration, either of the core or of a single
1378 * local Sone, has changed, and that the configuration should be saved.
1380 public void touchConfiguration() {
1381 lastConfigurationUpdate = System.currentTimeMillis();
1389 public void serviceStart() {
1390 loadConfiguration();
1391 updateChecker.start();
1392 identityManager.start();
1393 webOfTrustUpdater.init();
1394 webOfTrustUpdater.start();
1399 public void serviceRun() {
1400 long lastSaved = System.currentTimeMillis();
1401 while (!shouldStop()) {
1403 long now = System.currentTimeMillis();
1404 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1405 for (Sone localSone : getLocalSones()) {
1406 saveSone(localSone);
1408 saveConfiguration();
1415 public void serviceStop() {
1416 localElementTicker.shutdownNow();
1417 synchronized (sones) {
1418 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1419 soneInserter.getValue().stop();
1420 saveSone(soneInserter.getKey());
1423 saveConfiguration();
1425 webOfTrustUpdater.stop();
1426 updateChecker.stop();
1427 soneDownloader.stop();
1428 soneDownloaders.shutdown();
1429 identityManager.stop();
1437 * Saves the given Sone. This will persist all local settings for the given
1438 * Sone, such as the friends list and similar, private options.
1443 private synchronized void saveSone(Sone sone) {
1444 if (!sone.isLocal()) {
1445 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1448 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1449 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1453 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1455 /* save Sone into configuration. */
1456 String sonePrefix = "Sone/" + sone.getId();
1457 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1458 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1461 Profile profile = sone.getProfile();
1462 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1463 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1464 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1465 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1466 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1467 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1468 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1470 /* save profile fields. */
1471 int fieldCounter = 0;
1472 for (Field profileField : profile.getFields()) {
1473 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1474 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1475 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1477 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1480 int postCounter = 0;
1481 for (Post post : sone.getPosts()) {
1482 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1483 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1484 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1485 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1486 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1488 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1491 int replyCounter = 0;
1492 for (PostReply reply : sone.getReplies()) {
1493 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1494 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1495 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1496 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1497 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1499 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1501 /* save post likes. */
1502 int postLikeCounter = 0;
1503 for (String postId : sone.getLikedPostIds()) {
1504 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1506 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1508 /* save reply likes. */
1509 int replyLikeCounter = 0;
1510 for (String replyId : sone.getLikedReplyIds()) {
1511 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1513 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1516 int friendCounter = 0;
1517 for (String friendId : sone.getFriends()) {
1518 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1520 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1522 /* save albums. first, collect in a flat structure, top-level first. */
1523 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1525 int albumCounter = 0;
1526 for (Album album : albums) {
1527 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1528 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1529 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1530 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1531 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1532 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1534 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1537 int imageCounter = 0;
1538 for (Album album : albums) {
1539 for (Image image : album.getImages()) {
1540 if (!image.isInserted()) {
1543 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1544 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1545 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1546 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1547 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1548 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1549 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1550 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1551 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1554 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1557 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1558 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1559 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1560 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1561 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1562 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1564 configuration.save();
1566 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1568 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1569 } catch (ConfigurationException ce1) {
1570 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1574 /** Saves the current options. */
1575 private void saveConfiguration() {
1576 synchronized (configuration) {
1577 if (storingConfiguration) {
1578 logger.log(Level.FINE, "Already storing configuration…");
1581 storingConfiguration = true;
1584 /* store the options first. */
1586 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1587 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1588 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1589 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1590 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1591 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1592 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1593 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1594 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1595 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1596 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1597 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1599 /* save known Sones. */
1600 int soneCounter = 0;
1601 synchronized (knownSones) {
1602 for (String knownSoneId : knownSones) {
1603 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1605 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1608 /* save Sone following times. */
1610 synchronized (soneFollowingTimes) {
1611 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1612 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1613 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1616 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1619 /* save known posts. */
1622 /* save bookmarked posts. */
1623 int bookmarkedPostCounter = 0;
1624 synchronized (bookmarkedPosts) {
1625 for (String bookmarkedPostId : bookmarkedPosts) {
1626 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1629 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1632 configuration.save();
1634 } catch (ConfigurationException ce1) {
1635 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1636 } catch (DatabaseException de1) {
1637 logger.log(Level.SEVERE, "Could not save database!", de1);
1639 synchronized (configuration) {
1640 storingConfiguration = false;
1645 /** Loads the configuration. */
1646 private void loadConfiguration() {
1647 /* create options. */
1648 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1651 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1652 SoneInserter.setInsertionDelay(newValue);
1656 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1657 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1658 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1659 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1660 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1661 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1662 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1663 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1664 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1667 @SuppressWarnings("synthetic-access")
1668 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1669 fcpInterface.setActive(newValue);
1672 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1675 @SuppressWarnings("synthetic-access")
1676 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1677 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1682 loadConfigurationValue("InsertionDelay");
1683 loadConfigurationValue("PostsPerPage");
1684 loadConfigurationValue("ImagesPerPage");
1685 loadConfigurationValue("CharactersPerPost");
1686 loadConfigurationValue("PostCutOffLength");
1687 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1688 loadConfigurationValue("PositiveTrust");
1689 loadConfigurationValue("NegativeTrust");
1690 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1691 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1692 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1694 /* load known Sones. */
1695 int soneCounter = 0;
1697 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1698 if (knownSoneId == null) {
1701 synchronized (knownSones) {
1702 knownSones.add(knownSoneId);
1706 /* load Sone following times. */
1709 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1710 if (soneId == null) {
1713 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1714 synchronized (soneFollowingTimes) {
1715 soneFollowingTimes.put(soneId, time);
1720 /* load bookmarked posts. */
1721 int bookmarkedPostCounter = 0;
1723 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1724 if (bookmarkedPostId == null) {
1727 synchronized (bookmarkedPosts) {
1728 bookmarkedPosts.add(bookmarkedPostId);
1735 * Loads an {@link Integer} configuration value for the option with the given
1736 * name, logging validation failures.
1739 * The name of the option to load
1741 private void loadConfigurationValue(String optionName) {
1743 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1744 } catch (IllegalArgumentException iae1) {
1745 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1750 * Notifies the core that a new {@link OwnIdentity} was added.
1752 * @param ownIdentityAddedEvent
1756 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1757 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1758 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1759 if (ownIdentity.hasContext("Sone")) {
1760 addLocalSone(ownIdentity);
1765 * Notifies the core that an {@link OwnIdentity} was removed.
1767 * @param ownIdentityRemovedEvent
1771 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1772 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1773 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1774 trustedIdentities.removeAll(ownIdentity);
1778 * Notifies the core that a new {@link Identity} was added.
1780 * @param identityAddedEvent
1784 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1785 Identity identity = identityAddedEvent.identity();
1786 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1787 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1788 addRemoteSone(identity);
1792 * Notifies the core that an {@link Identity} was updated.
1794 * @param identityUpdatedEvent
1798 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1799 final Identity identity = identityUpdatedEvent.identity();
1800 soneDownloaders.execute(new Runnable() {
1803 @SuppressWarnings("synthetic-access")
1805 Optional<Sone> sone = getRemoteSone(identity.getId());
1806 sone.get().setIdentity(identity);
1807 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1808 soneDownloader.addSone(sone.get());
1809 soneDownloader.fetchSone(sone.get());
1815 * Notifies the core that an {@link Identity} was removed.
1817 * @param identityRemovedEvent
1821 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1822 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1823 Identity identity = identityRemovedEvent.identity();
1824 trustedIdentities.remove(ownIdentity, identity);
1825 boolean foundIdentity = false;
1826 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1827 if (trustedIdentity.getKey().equals(ownIdentity)) {
1830 if (trustedIdentity.getValue().contains(identity)) {
1831 foundIdentity = true;
1834 if (foundIdentity) {
1835 /* some local identity still trusts this identity, don’t remove. */
1838 Optional<Sone> sone = getSone(identity.getId());
1839 if (!sone.isPresent()) {
1840 /* TODO - we don’t have the Sone anymore. should this happen? */
1843 database.removePosts(sone.get());
1844 for (Post post : sone.get().getPosts()) {
1845 eventBus.post(new PostRemovedEvent(post));
1847 database.removePostReplies(sone.get());
1848 for (PostReply reply : sone.get().getReplies()) {
1849 eventBus.post(new PostReplyRemovedEvent(reply));
1851 synchronized (sones) {
1852 sones.remove(identity.getId());
1854 eventBus.post(new SoneRemovedEvent(sone.get()));
1858 * Deletes the temporary image.
1860 * @param imageInsertFinishedEvent
1864 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1865 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1866 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1867 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1868 touchConfiguration();
1871 public Optional<PostCreated> postCreated() {
1872 return Optional.<PostCreated>of(new PostCreated() {
1874 public void postCreated(final Post post) {
1875 if (post.isKnown()) {
1878 eventBus.post(new NewPostFoundEvent(post));
1879 if (post.getSone().isLocal()) {
1880 localElementTicker.schedule(new Runnable() {
1883 markPostKnown(post);
1885 }, 10, TimeUnit.SECONDS);
1891 public Optional<PostReplyCreated> postReplyCreated() {
1892 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1894 public void postReplyCreated(final PostReply postReply) {
1895 if (postReply.isKnown()) {
1898 eventBus.post(new NewPostReplyFoundEvent(postReply));
1899 if (postReply.getSone().isLocal()) {
1900 localElementTicker.schedule(new Runnable() {
1907 markReplyKnown(postReply);
1909 }, 10, TimeUnit.SECONDS);
1915 public Optional<ImageCreated> imageCreated() {
1916 return Optional.<ImageCreated>of(new ImageCreated() {
1918 public void imageCreated(Image image) {
1919 /* nothing happens here yet. */