2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static net.pterodactylus.sone.data.Identified.GET_ID;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.net.MalformedURLException;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ScheduledExecutorService;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.core.Options.DefaultOption;
43 import net.pterodactylus.sone.core.Options.Option;
44 import net.pterodactylus.sone.core.Options.OptionWatcher;
45 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
46 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
49 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
50 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
51 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
52 import net.pterodactylus.sone.core.event.PostRemovedEvent;
53 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneLockedEvent;
55 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.database.Database;
70 import net.pterodactylus.sone.database.DatabaseException;
71 import net.pterodactylus.sone.database.PostBuilder;
72 import net.pterodactylus.sone.database.PostProvider;
73 import net.pterodactylus.sone.database.PostReplyBuilder;
74 import net.pterodactylus.sone.database.PostReplyProvider;
75 import net.pterodactylus.sone.database.SoneProvider;
76 import net.pterodactylus.sone.fcp.FcpInterface;
77 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
78 import net.pterodactylus.sone.freenet.wot.Identity;
79 import net.pterodactylus.sone.freenet.wot.IdentityManager;
80 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
86 import net.pterodactylus.sone.main.SonePlugin;
87 import net.pterodactylus.sone.utils.IntegerRangePredicate;
88 import net.pterodactylus.util.config.Configuration;
89 import net.pterodactylus.util.config.ConfigurationException;
90 import net.pterodactylus.util.logging.Logging;
91 import net.pterodactylus.util.number.Numbers;
92 import net.pterodactylus.util.service.AbstractService;
93 import net.pterodactylus.util.thread.NamedThreadFactory;
95 import freenet.keys.FreenetURI;
97 import com.google.common.base.Optional;
98 import com.google.common.base.Predicate;
99 import com.google.common.base.Predicates;
100 import com.google.common.collect.HashMultimap;
101 import com.google.common.collect.ImmutableSet;
102 import com.google.common.collect.Maps;
103 import com.google.common.collect.Multimap;
104 import com.google.common.collect.Multimaps;
105 import com.google.common.eventbus.EventBus;
106 import com.google.common.eventbus.Subscribe;
107 import com.google.inject.Inject;
112 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
114 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
117 private static final Logger logger = Logging.getLogger(Core.class);
119 /** The start time. */
120 private final long startupTime = System.currentTimeMillis();
123 private final Options options = new Options();
125 /** The preferences. */
126 private final Preferences preferences = new Preferences(options);
128 /** The event bus. */
129 private final EventBus eventBus;
131 /** The configuration. */
132 private Configuration configuration;
134 /** Whether we’re currently saving the configuration. */
135 private boolean storingConfiguration = false;
137 /** The identity manager. */
138 private final IdentityManager identityManager;
140 /** Interface to freenet. */
141 private final FreenetInterface freenetInterface;
143 /** The Sone downloader. */
144 private final SoneDownloader soneDownloader;
146 /** The image inserter. */
147 private final ImageInserter imageInserter;
149 /** Sone downloader thread-pool. */
150 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
152 /** The update checker. */
153 private final UpdateChecker updateChecker;
155 /** The trust updater. */
156 private final WebOfTrustUpdater webOfTrustUpdater;
158 /** The FCP interface. */
159 private volatile FcpInterface fcpInterface;
161 /** The times Sones were followed. */
162 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
164 /** Locked local Sones. */
165 /* synchronize on itself. */
166 private final Set<Sone> lockedSones = new HashSet<Sone>();
168 /** Sone inserters. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
172 /** Sone rescuers. */
173 /* synchronize access on this on sones. */
174 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
177 /* synchronize access on this on itself. */
178 private final Map<String, Sone> sones = new HashMap<String, Sone>();
180 /** All known Sones. */
181 private final Set<String> knownSones = new HashSet<String>();
183 /** The post database. */
184 private final Database database;
186 /** All bookmarked posts. */
187 /* synchronize access on itself. */
188 private final Set<String> bookmarkedPosts = new HashSet<String>();
190 /** Trusted identities, sorted by own identities. */
191 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
193 /** All temporary images. */
194 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
196 /** Ticker for threads that mark own elements as known. */
197 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
199 /** The time the configuration was last touched. */
200 private volatile long lastConfigurationUpdate;
203 * Creates a new core.
205 * @param configuration
206 * The configuration of the core
207 * @param freenetInterface
208 * The freenet interface
209 * @param identityManager
210 * The identity manager
211 * @param webOfTrustUpdater
212 * The WebOfTrust updater
219 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
221 this.configuration = configuration;
222 this.freenetInterface = freenetInterface;
223 this.identityManager = identityManager;
224 this.soneDownloader = new SoneDownloader(this, freenetInterface);
225 this.imageInserter = new ImageInserter(freenetInterface);
226 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
227 this.webOfTrustUpdater = webOfTrustUpdater;
228 this.eventBus = eventBus;
229 this.database = database;
237 * Returns the time Sone was started.
239 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
241 public long getStartupTime() {
246 * Sets the configuration to use. This will automatically save the current
247 * configuration to the given configuration.
249 * @param configuration
250 * The new configuration to use
252 public void setConfiguration(Configuration configuration) {
253 this.configuration = configuration;
254 touchConfiguration();
258 * Returns the options used by the core.
260 * @return The options of the core
262 public Preferences getPreferences() {
267 * Returns the identity manager used by the core.
269 * @return The identity manager
271 public IdentityManager getIdentityManager() {
272 return identityManager;
276 * Returns the update checker.
278 * @return The update checker
280 public UpdateChecker getUpdateChecker() {
281 return updateChecker;
285 * Sets the FCP interface to use.
287 * @param fcpInterface
288 * The FCP interface to use
290 public void setFcpInterface(FcpInterface fcpInterface) {
291 this.fcpInterface = fcpInterface;
294 public Database getDatabase() {
299 * Returns the Sone rescuer for the given local Sone.
302 * The local Sone to get the rescuer for
303 * @return The Sone rescuer for the given Sone
305 public SoneRescuer getSoneRescuer(Sone sone) {
306 checkNotNull(sone, "sone must not be null");
307 checkArgument(sone.isLocal(), "sone must be local");
308 synchronized (sones) {
309 SoneRescuer soneRescuer = soneRescuers.get(sone);
310 if (soneRescuer == null) {
311 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
312 soneRescuers.put(sone, soneRescuer);
320 * Returns whether the given Sone is currently locked.
324 * @return {@code true} if the Sone is locked, {@code false} if it is not
326 public boolean isLocked(Sone sone) {
327 synchronized (lockedSones) {
328 return lockedSones.contains(sone);
332 /** {@inheritDocs} */
334 public Collection<Sone> getSones() {
335 synchronized (sones) {
336 return ImmutableSet.copyOf(sones.values());
341 * Returns the Sone with the given ID, regardless whether it’s local or
345 * The ID of the Sone to get
346 * @return The Sone with the given ID, or {@code null} if there is no such
350 public Optional<Sone> getSone(String id) {
351 synchronized (sones) {
352 return Optional.fromNullable(sones.get(id));
356 /** {@inheritDocs} */
358 public Collection<Sone> getLocalSones() {
359 synchronized (sones) {
360 return from(sones.values()).filter(new Predicate<Sone>() {
363 public boolean apply(Sone sone) {
364 return sone.isLocal();
371 * Returns the local Sone with the given ID, optionally creating a new Sone.
375 * @return The Sone with the given ID, or {@code null}
377 public Optional<Sone> getLocalSone(String id) {
378 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
381 /** {@inheritDocs} */
383 public Collection<Sone> getRemoteSones() {
384 synchronized (sones) {
385 return from(sones.values()).filter(new Predicate<Sone>() {
388 public boolean apply(Sone sone) {
389 return !sone.isLocal();
396 * Returns the remote Sone with the given ID.
399 * The ID of the remote Sone to get
400 * @return The Sone with the given ID
402 public Optional<Sone> getRemoteSone(String id) {
403 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
407 * Returns whether the given Sone has been modified.
410 * The Sone to check for modifications
411 * @return {@code true} if a modification has been detected in the Sone, {@code
414 public boolean isModifiedSone(Sone sone) {
415 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
419 * Returns the time when the given was first followed by any local Sone.
422 * The Sone to get the time for
423 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
424 * followed, or {@link Long#MAX_VALUE}
426 public long getSoneFollowingTime(Sone sone) {
427 synchronized (soneFollowingTimes) {
428 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
433 * Returns whether the target Sone is trusted by the origin Sone.
439 * @return {@code true} if the target Sone is trusted by the origin Sone
441 public boolean isSoneTrusted(Sone origin, Sone target) {
442 checkNotNull(origin, "origin must not be null");
443 checkNotNull(target, "target must not be null");
444 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
445 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
450 public Optional<Post> getPost(String postId) {
451 return database.getPost(postId);
454 /** {@inheritDocs} */
456 public Collection<Post> getPosts(String soneId) {
457 return database.getPosts(soneId);
462 public Collection<Post> getDirectedPosts(final String recipientId) {
463 checkNotNull(recipientId, "recipient must not be null");
464 return database.getDirectedPosts(recipientId);
468 * Returns a post reply builder.
470 * @return A new post reply builder
472 public PostReplyBuilder postReplyBuilder() {
473 return database.newPostReplyBuilder();
478 public Optional<PostReply> getPostReply(String replyId) {
479 return database.getPostReply(replyId);
484 public List<PostReply> getReplies(final String postId) {
485 return database.getReplies(postId);
489 * Returns all Sones that have liked the given post.
492 * The post to get the liking Sones for
493 * @return The Sones that like the given post
495 public Set<Sone> getLikes(Post post) {
496 Set<Sone> sones = new HashSet<Sone>();
497 for (Sone sone : getSones()) {
498 if (sone.getLikedPostIds().contains(post.getId())) {
506 * Returns all Sones that have liked the given reply.
509 * The reply to get the liking Sones for
510 * @return The Sones that like the given reply
512 public Set<Sone> getLikes(PostReply reply) {
513 Set<Sone> sones = new HashSet<Sone>();
514 for (Sone sone : getSones()) {
515 if (sone.getLikedReplyIds().contains(reply.getId())) {
523 * Returns whether the given post is bookmarked.
527 * @return {@code true} if the given post is bookmarked, {@code false}
530 public boolean isBookmarked(Post post) {
531 return isPostBookmarked(post.getId());
535 * Returns whether the post with the given ID is bookmarked.
538 * The ID of the post to check
539 * @return {@code true} if the post with the given ID is bookmarked, {@code
542 public boolean isPostBookmarked(String id) {
543 synchronized (bookmarkedPosts) {
544 return bookmarkedPosts.contains(id);
549 * Returns all currently known bookmarked posts.
551 * @return All bookmarked posts
553 public Set<Post> getBookmarkedPosts() {
554 Set<Post> posts = new HashSet<Post>();
555 synchronized (bookmarkedPosts) {
556 for (String bookmarkedPostId : bookmarkedPosts) {
557 Optional<Post> post = getPost(bookmarkedPostId);
558 if (post.isPresent()) {
559 posts.add(post.get());
566 public Optional<Album> getAlbum(String albumId) {
567 return database.getAlbum(albumId);
570 public Optional<Image> getImage(String imageId) {
571 return database.getImage(imageId);
575 * Returns the temporary image with the given ID.
578 * The ID of the temporary image
579 * @return The temporary image, or {@code null} if there is no temporary image
582 public TemporaryImage getTemporaryImage(String imageId) {
583 synchronized (temporaryImages) {
584 return temporaryImages.get(imageId);
593 * Locks the given Sone. A locked Sone will not be inserted by {@link
594 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
599 public void lockSone(Sone sone) {
600 synchronized (lockedSones) {
601 if (lockedSones.add(sone)) {
602 eventBus.post(new SoneLockedEvent(sone));
608 * Unlocks the given Sone.
612 * @see #lockSone(Sone)
614 public void unlockSone(Sone sone) {
615 synchronized (lockedSones) {
616 if (lockedSones.remove(sone)) {
617 eventBus.post(new SoneUnlockedEvent(sone));
623 * Adds a local Sone from the given own identity.
626 * The own identity to create a Sone from
627 * @return The added (or already existing) Sone
629 public Sone addLocalSone(OwnIdentity ownIdentity) {
630 if (ownIdentity == null) {
631 logger.log(Level.WARNING, "Given OwnIdentity is null!");
634 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
635 synchronized (sones) {
638 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
639 } catch (MalformedURLException mue1) {
640 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
643 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
644 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
646 /* TODO - load posts ’n stuff */
647 sones.put(ownIdentity.getId(), sone);
648 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
649 soneInserters.put(sone, soneInserter);
650 sone.setStatus(SoneStatus.idle);
652 soneInserter.start();
658 * Creates a new Sone for the given own identity.
661 * The own identity to create a Sone for
662 * @return The created Sone
664 public Sone createSone(OwnIdentity ownIdentity) {
665 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
666 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
669 Sone sone = addLocalSone(ownIdentity);
670 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
671 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
672 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
673 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
674 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
675 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
677 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
678 touchConfiguration();
683 * Adds the Sone of the given identity.
686 * The identity whose Sone to add
687 * @return The added or already existing Sone
689 public Sone addRemoteSone(Identity identity) {
690 if (identity == null) {
691 logger.log(Level.WARNING, "Given Identity is null!");
694 synchronized (sones) {
695 final Sone sone = database.newSoneBuilder().by(identity).build();
696 if (sone.isLocal()) {
699 sone.setIdentity(identity);
700 boolean newSone = sone.getRequestUri() == null;
701 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
702 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
704 synchronized (knownSones) {
705 newSone = !knownSones.contains(sone.getId());
707 sone.setKnown(!newSone);
709 eventBus.post(new NewSoneFoundEvent(sone));
710 for (Sone localSone : getLocalSones()) {
711 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
712 followSone(localSone, sone.getId());
717 soneDownloader.addSone(sone);
718 soneDownloaders.execute(new Runnable() {
721 @SuppressWarnings("synthetic-access")
723 soneDownloader.fetchSone(sone, sone.getRequestUri());
732 * Lets the given local Sone follow the Sone with the given ID.
735 * The local Sone that should follow another Sone
737 * The ID of the Sone to follow
739 public void followSone(Sone sone, String soneId) {
740 checkNotNull(sone, "sone must not be null");
741 checkNotNull(soneId, "soneId must not be null");
742 sone.addFriend(soneId);
743 synchronized (soneFollowingTimes) {
744 if (!soneFollowingTimes.containsKey(soneId)) {
745 long now = System.currentTimeMillis();
746 soneFollowingTimes.put(soneId, now);
747 Optional<Sone> followedSone = getSone(soneId);
748 if (!followedSone.isPresent()) {
751 for (Post post : followedSone.get().getPosts()) {
752 if (post.getTime() < now) {
756 for (PostReply reply : followedSone.get().getReplies()) {
757 if (reply.getTime() < now) {
758 markReplyKnown(reply);
763 touchConfiguration();
767 * Lets the given local Sone unfollow the Sone with the given ID.
770 * The local Sone that should unfollow another Sone
772 * The ID of the Sone being unfollowed
774 public void unfollowSone(Sone sone, String soneId) {
775 checkNotNull(sone, "sone must not be null");
776 checkNotNull(soneId, "soneId must not be null");
777 sone.removeFriend(soneId);
778 boolean unfollowedSoneStillFollowed = false;
779 for (Sone localSone : getLocalSones()) {
780 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
782 if (!unfollowedSoneStillFollowed) {
783 synchronized (soneFollowingTimes) {
784 soneFollowingTimes.remove(soneId);
787 touchConfiguration();
791 * Sets the trust value of the given origin Sone for the target Sone.
798 * The trust value (from {@code -100} to {@code 100})
800 public void setTrust(Sone origin, Sone target, int trustValue) {
801 checkNotNull(origin, "origin must not be null");
802 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
803 checkNotNull(target, "target must not be null");
804 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
805 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
809 * Removes any trust assignment for the given target Sone.
816 public void removeTrust(Sone origin, Sone target) {
817 checkNotNull(origin, "origin must not be null");
818 checkNotNull(target, "target must not be null");
819 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
820 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
824 * Assigns the configured positive trust value for the given target.
831 public void trustSone(Sone origin, Sone target) {
832 setTrust(origin, target, preferences.getPositiveTrust());
836 * Assigns the configured negative trust value for the given target.
843 public void distrustSone(Sone origin, Sone target) {
844 setTrust(origin, target, preferences.getNegativeTrust());
848 * Removes the trust assignment for the given target.
855 public void untrustSone(Sone origin, Sone target) {
856 removeTrust(origin, target);
860 * Updates the stored Sone with the given Sone.
865 public void updateSone(Sone sone) {
866 updateSone(sone, false);
870 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
871 * {@code true}, an older Sone than the current Sone can be given to restore an
876 * @param soneRescueMode
877 * {@code true} if the stored Sone should be updated regardless of the age of
880 public void updateSone(Sone sone, boolean soneRescueMode) {
881 Optional<Sone> storedSone = getSone(sone.getId());
882 if (storedSone.isPresent()) {
883 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
884 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
887 /* find removed posts. */
888 Collection<Post> existingPosts = database.getPosts(sone.getId());
889 for (Post oldPost : existingPosts) {
890 if (!sone.getPosts().contains(oldPost)) {
891 eventBus.post(new PostRemovedEvent(oldPost));
894 /* find new posts. */
895 for (Post newPost : sone.getPosts()) {
896 if (existingPosts.contains(newPost)) {
899 if (newPost.getTime() < getSoneFollowingTime(sone)) {
900 newPost.setKnown(true);
901 } else if (!newPost.isKnown()) {
902 eventBus.post(new NewPostFoundEvent(newPost));
906 database.storePosts(sone, sone.getPosts());
907 if (!soneRescueMode) {
908 for (PostReply reply : storedSone.get().getReplies()) {
909 if (!sone.getReplies().contains(reply)) {
910 eventBus.post(new PostReplyRemovedEvent(reply));
914 Set<PostReply> storedReplies = storedSone.get().getReplies();
915 for (PostReply reply : sone.getReplies()) {
916 if (storedReplies.contains(reply)) {
919 if (reply.getTime() < getSoneFollowingTime(sone)) {
920 reply.setKnown(true);
921 } else if (!reply.isKnown()) {
922 eventBus.post(new NewPostReplyFoundEvent(reply));
925 database.storePostReplies(sone, sone.getReplies());
926 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
927 database.removeAlbum(album);
928 for (Image image : album.getImages()) {
929 database.removeImage(image);
932 for (Album album : sone.getRootAlbum().getAlbums()) {
933 database.storeAlbum(album);
934 for (Image image : album.getImages()) {
935 database.storeImage(image);
938 synchronized (sones) {
939 sone.setOptions(storedSone.get().getOptions());
940 sone.setKnown(storedSone.get().isKnown());
941 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
942 if (sone.isLocal()) {
943 soneInserters.get(storedSone.get()).setSone(sone);
944 touchConfiguration();
946 sones.put(sone.getId(), sone);
952 * Deletes the given Sone. This will remove the Sone from the {@link
953 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
954 * context from its identity.
959 public void deleteSone(Sone sone) {
960 if (!(sone.getIdentity() instanceof OwnIdentity)) {
961 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
964 synchronized (sones) {
965 if (!getLocalSones().contains(sone)) {
966 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
969 sones.remove(sone.getId());
970 SoneInserter soneInserter = soneInserters.remove(sone);
973 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
974 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
976 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
977 } catch (ConfigurationException ce1) {
978 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
983 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
984 * known} before, a {@link MarkSoneKnownEvent} is fired.
987 * The Sone to mark as known
989 public void markSoneKnown(Sone sone) {
990 if (!sone.isKnown()) {
992 synchronized (knownSones) {
993 knownSones.add(sone.getId());
995 eventBus.post(new MarkSoneKnownEvent(sone));
996 touchConfiguration();
1001 * Loads and updates the given Sone from the configuration. If any error is
1002 * encountered, loading is aborted and the given Sone is not changed.
1005 * The Sone to load and update
1007 public void loadSone(Sone sone) {
1008 if (!sone.isLocal()) {
1009 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1012 logger.info(String.format("Loading local Sone: %s", sone));
1014 /* initialize options. */
1015 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1016 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1017 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1018 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1019 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1020 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1023 String sonePrefix = "Sone/" + sone.getId();
1024 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1025 if (soneTime == null) {
1026 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1029 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1032 Profile profile = new Profile(sone);
1033 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1034 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1035 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1036 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1037 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1038 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1040 /* load profile fields. */
1042 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1043 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1044 if (fieldName == null) {
1047 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1048 profile.addField(fieldName).setValue(fieldValue);
1052 Set<Post> posts = new HashSet<Post>();
1054 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1055 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1056 if (postId == null) {
1059 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1060 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1061 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1062 if ((postTime == 0) || (postText == null)) {
1063 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1066 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
1067 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1068 postBuilder.to(postRecipientId);
1070 posts.add(postBuilder.build());
1074 Set<PostReply> replies = new HashSet<PostReply>();
1076 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1077 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1078 if (replyId == null) {
1081 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1082 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1083 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1084 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1085 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1088 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1089 replies.add(postReplyBuilder.build());
1092 /* load post likes. */
1093 Set<String> likedPostIds = new HashSet<String>();
1095 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1096 if (likedPostId == null) {
1099 likedPostIds.add(likedPostId);
1102 /* load reply likes. */
1103 Set<String> likedReplyIds = new HashSet<String>();
1105 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1106 if (likedReplyId == null) {
1109 likedReplyIds.add(likedReplyId);
1113 Set<String> friends = new HashSet<String>();
1115 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1116 if (friendId == null) {
1119 friends.add(friendId);
1123 Map<String, Album> albums = Maps.newHashMap();
1124 int albumCounter = 0;
1126 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1127 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1128 if (albumId == null) {
1131 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1132 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1133 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1134 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1135 if ((albumTitle == null) || (albumDescription == null)) {
1136 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1139 Album parentAlbum = sone.getRootAlbum();
1140 if (albumParentId != null) {
1141 parentAlbum = albums.get(albumParentId);
1143 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1144 albums.put(album.getId(), album);
1148 int imageCounter = 0;
1150 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1151 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1152 if (imageId == null) {
1155 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1156 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1157 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1158 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1159 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1160 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1161 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1162 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1163 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1166 Album album = albums.get(albumId);
1167 if (album == null) {
1168 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1171 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1175 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1176 if (avatarId != null) {
1177 profile.setAvatar(getImage(avatarId).orNull());
1181 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1182 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1183 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1184 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1185 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1186 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1188 /* if we’re still here, Sone was loaded successfully. */
1189 synchronized (sone) {
1190 sone.setTime(soneTime);
1191 sone.setProfile(profile);
1192 sone.setPosts(posts);
1193 sone.setReplies(replies);
1194 sone.setLikePostIds(likedPostIds);
1195 sone.setLikeReplyIds(likedReplyIds);
1196 for (String friendId : friends) {
1197 followSone(sone, friendId);
1199 for (Album album : sone.getRootAlbum().getAlbums()) {
1202 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1204 synchronized (knownSones) {
1205 for (String friend : friends) {
1206 knownSones.add(friend);
1209 database.storePosts(sone, posts);
1210 for (Post post : posts) {
1211 post.setKnown(true);
1213 database.storePostReplies(sone, replies);
1214 for (PostReply reply : replies) {
1215 reply.setKnown(true);
1218 logger.info(String.format("Sone loaded successfully: %s", sone));
1222 * Creates a new post.
1225 * The Sone that creates the post
1227 * The text of the post
1228 * @return The created post
1230 public Post createPost(Sone sone, String text) {
1231 return createPost(sone, System.currentTimeMillis(), text);
1235 * Creates a new post.
1238 * The Sone that creates the post
1240 * The time of the post
1242 * The text of the post
1243 * @return The created post
1245 public Post createPost(Sone sone, long time, String text) {
1246 return createPost(sone, null, time, text);
1250 * Creates a new post.
1253 * The Sone that creates the post
1255 * The recipient Sone, or {@code null} if this post does not have a
1258 * The text of the post
1259 * @return The created post
1261 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1262 return createPost(sone, recipient, System.currentTimeMillis(), text);
1266 * Creates a new post.
1269 * The Sone that creates the post
1271 * The recipient Sone, or {@code null} if this post does not have a
1274 * The time of the post
1276 * The text of the post
1277 * @return The created post
1279 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1280 checkNotNull(text, "text must not be null");
1281 checkArgument(text.trim().length() > 0, "text must not be empty");
1282 if (!sone.isLocal()) {
1283 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1286 PostBuilder postBuilder = sone.newPostBuilder();
1287 postBuilder.randomId().withTime(time).withText(text.trim());
1288 if (recipient.isPresent()) {
1289 postBuilder.to(recipient.get().getId());
1291 final Post post = postBuilder.build();
1292 database.storePost(post);
1293 eventBus.post(new NewPostFoundEvent(post));
1295 touchConfiguration();
1296 localElementTicker.schedule(new Runnable() {
1303 markPostKnown(post);
1305 }, 10, TimeUnit.SECONDS);
1310 * Deletes the given post.
1313 * The post to delete
1315 public void deletePost(Post post) {
1316 if (!post.getSone().isLocal()) {
1317 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1320 database.removePost(post);
1321 eventBus.post(new PostRemovedEvent(post));
1322 markPostKnown(post);
1323 touchConfiguration();
1327 * Marks the given post as known, if it is currently not a known post
1328 * (according to {@link Post#isKnown()}).
1331 * The post to mark as known
1333 public void markPostKnown(Post post) {
1334 post.setKnown(true);
1335 eventBus.post(new MarkPostKnownEvent(post));
1336 touchConfiguration();
1337 for (PostReply reply : getReplies(post.getId())) {
1338 markReplyKnown(reply);
1343 * Bookmarks the given post.
1346 * The post to bookmark
1348 public void bookmark(Post post) {
1349 bookmarkPost(post.getId());
1353 * Bookmarks the post with the given ID.
1356 * The ID of the post to bookmark
1358 public void bookmarkPost(String id) {
1359 synchronized (bookmarkedPosts) {
1360 bookmarkedPosts.add(id);
1365 * Removes the given post from the bookmarks.
1368 * The post to unbookmark
1370 public void unbookmark(Post post) {
1371 unbookmarkPost(post.getId());
1375 * Removes the post with the given ID from the bookmarks.
1378 * The ID of the post to unbookmark
1380 public void unbookmarkPost(String id) {
1381 synchronized (bookmarkedPosts) {
1382 bookmarkedPosts.remove(id);
1387 * Creates a new reply.
1390 * The Sone that creates the reply
1392 * The post that this reply refers to
1394 * The text of the reply
1395 * @return The created reply
1397 public PostReply createReply(Sone sone, Post post, String text) {
1398 checkNotNull(text, "text must not be null");
1399 checkArgument(text.trim().length() > 0, "text must not be empty");
1400 if (!sone.isLocal()) {
1401 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1404 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1405 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1406 final PostReply reply = postReplyBuilder.build();
1407 database.storePostReply(reply);
1408 eventBus.post(new NewPostReplyFoundEvent(reply));
1409 sone.addReply(reply);
1410 touchConfiguration();
1411 localElementTicker.schedule(new Runnable() {
1418 markReplyKnown(reply);
1420 }, 10, TimeUnit.SECONDS);
1425 * Deletes the given reply.
1428 * The reply to delete
1430 public void deleteReply(PostReply reply) {
1431 Sone sone = reply.getSone();
1432 if (!sone.isLocal()) {
1433 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1436 database.removePostReply(reply);
1437 markReplyKnown(reply);
1438 sone.removeReply(reply);
1439 touchConfiguration();
1443 * Marks the given reply as known, if it is currently not a known reply
1444 * (according to {@link Reply#isKnown()}).
1447 * The reply to mark as known
1449 public void markReplyKnown(PostReply reply) {
1450 boolean previouslyKnown = reply.isKnown();
1451 reply.setKnown(true);
1452 eventBus.post(new MarkPostReplyKnownEvent(reply));
1453 if (!previouslyKnown) {
1454 touchConfiguration();
1459 * Creates a new image.
1462 * The Sone creating the image
1464 * The album the image will be inserted into
1465 * @param temporaryImage
1466 * The temporary image to create the image from
1467 * @return The newly created image
1469 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1470 checkNotNull(sone, "sone must not be null");
1471 checkNotNull(album, "album must not be null");
1472 checkNotNull(temporaryImage, "temporaryImage must not be null");
1473 checkArgument(sone.isLocal(), "sone must be a local Sone");
1474 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1475 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1476 imageInserter.insertImage(temporaryImage, image);
1481 * Deletes the given image. This method will also delete a matching temporary
1485 * The image to delete
1486 * @see #deleteTemporaryImage(TemporaryImage)
1488 public void deleteImage(Image image) {
1489 checkNotNull(image, "image must not be null");
1490 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1491 deleteTemporaryImage(image.getId());
1493 touchConfiguration();
1497 * Creates a new temporary image.
1500 * The MIME type of the temporary image
1502 * The encoded data of the image
1503 * @return The temporary image
1505 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1506 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1507 synchronized (temporaryImages) {
1508 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1510 return temporaryImage;
1514 * Deletes the given temporary image.
1516 * @param temporaryImage
1517 * The temporary image to delete
1519 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1520 checkNotNull(temporaryImage, "temporaryImage must not be null");
1521 deleteTemporaryImage(temporaryImage.getId());
1525 * Deletes the temporary image with the given ID.
1528 * The ID of the temporary image to delete
1530 public void deleteTemporaryImage(String imageId) {
1531 checkNotNull(imageId, "imageId must not be null");
1532 synchronized (temporaryImages) {
1533 temporaryImages.remove(imageId);
1535 Optional<Image> image = getImage(imageId);
1536 if (image.isPresent()) {
1537 imageInserter.cancelImageInsert(image.get());
1542 * Notifies the core that the configuration, either of the core or of a single
1543 * local Sone, has changed, and that the configuration should be saved.
1545 public void touchConfiguration() {
1546 lastConfigurationUpdate = System.currentTimeMillis();
1553 /** Starts the core. */
1555 public void serviceStart() {
1556 loadConfiguration();
1557 updateChecker.start();
1558 identityManager.start();
1559 webOfTrustUpdater.init();
1560 webOfTrustUpdater.start();
1564 /** {@inheritDoc} */
1566 public void serviceRun() {
1567 long lastSaved = System.currentTimeMillis();
1568 while (!shouldStop()) {
1570 long now = System.currentTimeMillis();
1571 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1572 for (Sone localSone : getLocalSones()) {
1573 saveSone(localSone);
1575 saveConfiguration();
1581 /** Stops the core. */
1583 public void serviceStop() {
1584 localElementTicker.shutdownNow();
1585 synchronized (sones) {
1586 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1587 soneInserter.getValue().stop();
1588 saveSone(soneInserter.getKey());
1591 saveConfiguration();
1593 webOfTrustUpdater.stop();
1594 updateChecker.stop();
1595 soneDownloader.stop();
1596 soneDownloaders.shutdown();
1597 identityManager.stop();
1605 * Saves the given Sone. This will persist all local settings for the given
1606 * Sone, such as the friends list and similar, private options.
1611 private synchronized void saveSone(Sone sone) {
1612 if (!sone.isLocal()) {
1613 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1616 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1617 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1621 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1623 /* save Sone into configuration. */
1624 String sonePrefix = "Sone/" + sone.getId();
1625 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1626 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1629 Profile profile = sone.getProfile();
1630 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1631 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1632 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1633 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1634 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1635 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1636 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1638 /* save profile fields. */
1639 int fieldCounter = 0;
1640 for (Field profileField : profile.getFields()) {
1641 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1642 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1643 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1645 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1648 int postCounter = 0;
1649 for (Post post : sone.getPosts()) {
1650 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1651 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1652 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1653 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1654 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1656 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1659 int replyCounter = 0;
1660 for (PostReply reply : sone.getReplies()) {
1661 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1662 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1663 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1664 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1665 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1667 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1669 /* save post likes. */
1670 int postLikeCounter = 0;
1671 for (String postId : sone.getLikedPostIds()) {
1672 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1674 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1676 /* save reply likes. */
1677 int replyLikeCounter = 0;
1678 for (String replyId : sone.getLikedReplyIds()) {
1679 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1681 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1684 int friendCounter = 0;
1685 for (String friendId : sone.getFriends()) {
1686 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1688 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1690 /* save albums. first, collect in a flat structure, top-level first. */
1691 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1693 int albumCounter = 0;
1694 for (Album album : albums) {
1695 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1696 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1697 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1698 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1699 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1700 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1702 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1705 int imageCounter = 0;
1706 for (Album album : albums) {
1707 for (Image image : album.getImages()) {
1708 if (!image.isInserted()) {
1711 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1712 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1713 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1714 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1715 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1716 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1717 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1718 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1719 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1722 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1725 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1726 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1727 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1728 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1729 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1730 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1732 configuration.save();
1734 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1736 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1737 } catch (ConfigurationException ce1) {
1738 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1742 /** Saves the current options. */
1743 private void saveConfiguration() {
1744 synchronized (configuration) {
1745 if (storingConfiguration) {
1746 logger.log(Level.FINE, "Already storing configuration…");
1749 storingConfiguration = true;
1752 /* store the options first. */
1754 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1755 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1756 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1757 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1758 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1759 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1760 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1761 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1762 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1763 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1764 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1765 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1767 /* save known Sones. */
1768 int soneCounter = 0;
1769 synchronized (knownSones) {
1770 for (String knownSoneId : knownSones) {
1771 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1773 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1776 /* save Sone following times. */
1778 synchronized (soneFollowingTimes) {
1779 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1780 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1781 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1784 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1787 /* save known posts. */
1790 /* save bookmarked posts. */
1791 int bookmarkedPostCounter = 0;
1792 synchronized (bookmarkedPosts) {
1793 for (String bookmarkedPostId : bookmarkedPosts) {
1794 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1797 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1800 configuration.save();
1802 } catch (ConfigurationException ce1) {
1803 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1804 } catch (DatabaseException de1) {
1805 logger.log(Level.SEVERE, "Could not save database!", de1);
1807 synchronized (configuration) {
1808 storingConfiguration = false;
1813 /** Loads the configuration. */
1814 private void loadConfiguration() {
1815 /* create options. */
1816 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1819 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1820 SoneInserter.setInsertionDelay(newValue);
1824 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1825 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1826 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1827 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1828 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1829 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1830 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1831 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1832 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1835 @SuppressWarnings("synthetic-access")
1836 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1837 fcpInterface.setActive(newValue);
1840 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1843 @SuppressWarnings("synthetic-access")
1844 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1845 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1850 loadConfigurationValue("InsertionDelay");
1851 loadConfigurationValue("PostsPerPage");
1852 loadConfigurationValue("ImagesPerPage");
1853 loadConfigurationValue("CharactersPerPost");
1854 loadConfigurationValue("PostCutOffLength");
1855 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1856 loadConfigurationValue("PositiveTrust");
1857 loadConfigurationValue("NegativeTrust");
1858 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1859 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1860 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1862 /* load known Sones. */
1863 int soneCounter = 0;
1865 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1866 if (knownSoneId == null) {
1869 synchronized (knownSones) {
1870 knownSones.add(knownSoneId);
1874 /* load Sone following times. */
1877 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1878 if (soneId == null) {
1881 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1882 synchronized (soneFollowingTimes) {
1883 soneFollowingTimes.put(soneId, time);
1888 /* load bookmarked posts. */
1889 int bookmarkedPostCounter = 0;
1891 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1892 if (bookmarkedPostId == null) {
1895 synchronized (bookmarkedPosts) {
1896 bookmarkedPosts.add(bookmarkedPostId);
1903 * Loads an {@link Integer} configuration value for the option with the given
1904 * name, logging validation failures.
1907 * The name of the option to load
1909 private void loadConfigurationValue(String optionName) {
1911 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1912 } catch (IllegalArgumentException iae1) {
1913 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1918 * Notifies the core that a new {@link OwnIdentity} was added.
1920 * @param ownIdentityAddedEvent
1924 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1925 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1926 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1927 if (ownIdentity.hasContext("Sone")) {
1928 addLocalSone(ownIdentity);
1933 * Notifies the core that an {@link OwnIdentity} was removed.
1935 * @param ownIdentityRemovedEvent
1939 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1940 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1941 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1942 trustedIdentities.removeAll(ownIdentity);
1946 * Notifies the core that a new {@link Identity} was added.
1948 * @param identityAddedEvent
1952 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1953 Identity identity = identityAddedEvent.identity();
1954 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1955 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1956 addRemoteSone(identity);
1960 * Notifies the core that an {@link Identity} was updated.
1962 * @param identityUpdatedEvent
1966 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1967 final Identity identity = identityUpdatedEvent.identity();
1968 soneDownloaders.execute(new Runnable() {
1971 @SuppressWarnings("synthetic-access")
1973 Optional<Sone> sone = getRemoteSone(identity.getId());
1974 sone.get().setIdentity(identity);
1975 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1976 soneDownloader.addSone(sone.get());
1977 soneDownloader.fetchSone(sone.get());
1983 * Notifies the core that an {@link Identity} was removed.
1985 * @param identityRemovedEvent
1989 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1990 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1991 Identity identity = identityRemovedEvent.identity();
1992 trustedIdentities.remove(ownIdentity, identity);
1993 boolean foundIdentity = false;
1994 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1995 if (trustedIdentity.getKey().equals(ownIdentity)) {
1998 if (trustedIdentity.getValue().contains(identity)) {
1999 foundIdentity = true;
2002 if (foundIdentity) {
2003 /* some local identity still trusts this identity, don’t remove. */
2006 Optional<Sone> sone = getSone(identity.getId());
2007 if (!sone.isPresent()) {
2008 /* TODO - we don’t have the Sone anymore. should this happen? */
2011 database.removePosts(sone.get());
2012 for (Post post : sone.get().getPosts()) {
2013 eventBus.post(new PostRemovedEvent(post));
2015 database.removePostReplies(sone.get());
2016 for (PostReply reply : sone.get().getReplies()) {
2017 eventBus.post(new PostReplyRemovedEvent(reply));
2019 synchronized (sones) {
2020 sones.remove(identity.getId());
2022 eventBus.post(new SoneRemovedEvent(sone.get()));
2026 * Deletes the temporary image.
2028 * @param imageInsertFinishedEvent
2032 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2033 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2034 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2035 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2036 touchConfiguration();