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 net.pterodactylus.sone.data.Identified.GET_ID;
24 import java.net.MalformedURLException;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
39 import net.pterodactylus.sone.core.Options.DefaultOption;
40 import net.pterodactylus.sone.core.Options.Option;
41 import net.pterodactylus.sone.core.Options.OptionWatcher;
42 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
43 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
46 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
47 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
48 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
49 import net.pterodactylus.sone.core.event.PostRemovedEvent;
50 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.SoneImpl;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.database.Database;
68 import net.pterodactylus.sone.database.DatabaseException;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneProvider;
74 import net.pterodactylus.sone.fcp.FcpInterface;
75 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
93 import freenet.keys.FreenetURI;
95 import com.google.common.base.Optional;
96 import com.google.common.base.Predicate;
97 import com.google.common.base.Predicates;
98 import com.google.common.collect.FluentIterable;
99 import com.google.common.collect.HashMultimap;
100 import com.google.common.collect.ImmutableSet;
101 import com.google.common.collect.Maps;
102 import com.google.common.collect.Multimap;
103 import com.google.common.collect.Multimaps;
104 import com.google.common.eventbus.EventBus;
105 import com.google.common.eventbus.Subscribe;
106 import com.google.inject.Inject;
111 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
113 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
116 private static final Logger logger = Logging.getLogger(Core.class);
118 /** The start time. */
119 private final long startupTime = System.currentTimeMillis();
122 private final Options options = new Options();
124 /** The preferences. */
125 private final Preferences preferences = new Preferences(options);
127 /** The event bus. */
128 private final EventBus eventBus;
130 /** The configuration. */
131 private Configuration configuration;
133 /** Whether we’re currently saving the configuration. */
134 private boolean storingConfiguration = false;
136 /** The identity manager. */
137 private final IdentityManager identityManager;
139 /** Interface to freenet. */
140 private final FreenetInterface freenetInterface;
142 /** The Sone downloader. */
143 private final SoneDownloader soneDownloader;
145 /** The image inserter. */
146 private final ImageInserter imageInserter;
148 /** Sone downloader thread-pool. */
149 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151 /** The update checker. */
152 private final UpdateChecker updateChecker;
154 /** The trust updater. */
155 private final WebOfTrustUpdater webOfTrustUpdater;
157 /** The FCP interface. */
158 private volatile FcpInterface fcpInterface;
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
176 /* synchronize access on this on itself. */
177 private final Map<String, Sone> sones = new HashMap<String, Sone>();
179 /** All known Sones. */
180 private final Set<String> knownSones = new HashSet<String>();
182 /** The post database. */
183 private final Database database;
185 /** All bookmarked posts. */
186 /* synchronize access on itself. */
187 private final Set<String> bookmarkedPosts = new HashSet<String>();
189 /** Trusted identities, sorted by own identities. */
190 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
192 /** All temporary images. */
193 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
195 /** Ticker for threads that mark own elements as known. */
196 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
198 /** The time the configuration was last touched. */
199 private volatile long lastConfigurationUpdate;
202 * Creates a new core.
204 * @param configuration
205 * The configuration of the core
206 * @param freenetInterface
207 * The freenet interface
208 * @param identityManager
209 * The identity manager
210 * @param webOfTrustUpdater
211 * The WebOfTrust updater
218 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
220 this.configuration = configuration;
221 this.freenetInterface = freenetInterface;
222 this.identityManager = identityManager;
223 this.soneDownloader = new SoneDownloader(this, freenetInterface);
224 this.imageInserter = new ImageInserter(freenetInterface);
225 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
226 this.webOfTrustUpdater = webOfTrustUpdater;
227 this.eventBus = eventBus;
228 this.database = database;
236 * Returns the time Sone was started.
238 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
240 public long getStartupTime() {
245 * Sets the configuration to use. This will automatically save the current
246 * configuration to the given configuration.
248 * @param configuration
249 * The new configuration to use
251 public void setConfiguration(Configuration configuration) {
252 this.configuration = configuration;
253 touchConfiguration();
257 * Returns the options used by the core.
259 * @return The options of the core
261 public Preferences getPreferences() {
266 * Returns the identity manager used by the core.
268 * @return The identity manager
270 public IdentityManager getIdentityManager() {
271 return identityManager;
275 * Returns the update checker.
277 * @return The update checker
279 public UpdateChecker getUpdateChecker() {
280 return updateChecker;
284 * Sets the FCP interface to use.
286 * @param fcpInterface
287 * The FCP interface to use
289 public void setFcpInterface(FcpInterface fcpInterface) {
290 this.fcpInterface = fcpInterface;
294 * Returns the Sone rescuer for the given local Sone.
297 * The local Sone to get the rescuer for
298 * @return The Sone rescuer for the given Sone
300 public SoneRescuer getSoneRescuer(Sone sone) {
301 checkNotNull(sone, "sone must not be null");
302 checkArgument(sone.isLocal(), "sone must be local");
303 synchronized (sones) {
304 SoneRescuer soneRescuer = soneRescuers.get(sone);
305 if (soneRescuer == null) {
306 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
307 soneRescuers.put(sone, soneRescuer);
315 * Returns whether the given Sone is currently locked.
319 * @return {@code true} if the Sone is locked, {@code false} if it is not
321 public boolean isLocked(Sone sone) {
322 synchronized (lockedSones) {
323 return lockedSones.contains(sone);
327 /** {@inheritDocs} */
329 public Collection<Sone> getSones() {
330 synchronized (sones) {
331 return ImmutableSet.copyOf(sones.values());
336 * Returns the Sone with the given ID, regardless whether it’s local or
340 * The ID of the Sone to get
341 * @return The Sone with the given ID, or {@code null} if there is no such
345 public Optional<Sone> getSone(String id) {
346 synchronized (sones) {
347 return Optional.fromNullable(sones.get(id));
351 /** {@inheritDocs} */
353 public Collection<Sone> getLocalSones() {
354 synchronized (sones) {
355 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
358 public boolean apply(Sone sone) {
359 return sone.isLocal();
366 * Returns the local Sone with the given ID, optionally creating a new Sone.
371 * {@code true} to create a new Sone if none exists, {@code false} to return
372 * null if none exists
373 * @return The Sone with the given ID, or {@code null}
375 public Sone getLocalSone(String id, boolean create) {
376 synchronized (sones) {
377 Sone sone = sones.get(id);
378 if ((sone == null) && create) {
379 sone = new SoneImpl(id, true);
382 if ((sone != null) && !sone.isLocal()) {
383 sone = new SoneImpl(id, true);
390 /** {@inheritDocs} */
392 public Collection<Sone> getRemoteSones() {
393 synchronized (sones) {
394 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
397 public boolean apply(Sone sone) {
398 return !sone.isLocal();
405 * Returns the remote Sone with the given ID.
408 * The ID of the remote Sone to get
410 * {@code true} to always create a Sone, {@code false} to return {@code null}
411 * if no Sone with the given ID exists
412 * @return The Sone with the given ID
414 public Sone getRemoteSone(String id, boolean create) {
415 synchronized (sones) {
416 Sone sone = sones.get(id);
417 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
418 sone = new SoneImpl(id, false);
426 * Returns whether the given Sone has been modified.
429 * The Sone to check for modifications
430 * @return {@code true} if a modification has been detected in the Sone, {@code
433 public boolean isModifiedSone(Sone sone) {
434 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
438 * Returns the time when the given was first followed by any local Sone.
441 * The Sone to get the time for
442 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
443 * followed, or {@link Long#MAX_VALUE}
445 public long getSoneFollowingTime(Sone sone) {
446 synchronized (soneFollowingTimes) {
447 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
452 * Returns whether the target Sone is trusted by the origin Sone.
458 * @return {@code true} if the target Sone is trusted by the origin Sone
460 public boolean isSoneTrusted(Sone origin, Sone target) {
461 checkNotNull(origin, "origin must not be null");
462 checkNotNull(target, "target must not be null");
463 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
464 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
468 * Returns a post builder.
470 * @return A new post builder
472 public PostBuilder postBuilder() {
473 return database.newPostBuilder();
478 public Optional<Post> getPost(String postId) {
479 return database.getPost(postId);
482 /** {@inheritDocs} */
484 public Collection<Post> getPosts(String soneId) {
485 return database.getPosts(soneId);
490 public Collection<Post> getDirectedPosts(final String recipientId) {
491 checkNotNull(recipientId, "recipient must not be null");
492 return database.getDirectedPosts(recipientId);
496 * Returns a post reply builder.
498 * @return A new post reply builder
500 public PostReplyBuilder postReplyBuilder() {
501 return database.newPostReplyBuilder();
506 public Optional<PostReply> getPostReply(String replyId) {
507 return database.getPostReply(replyId);
512 public List<PostReply> getReplies(final String postId) {
513 return database.getReplies(postId);
517 * Returns all Sones that have liked the given post.
520 * The post to get the liking Sones for
521 * @return The Sones that like the given post
523 public Set<Sone> getLikes(Post post) {
524 Set<Sone> sones = new HashSet<Sone>();
525 for (Sone sone : getSones()) {
526 if (sone.getLikedPostIds().contains(post.getId())) {
534 * Returns all Sones that have liked the given reply.
537 * The reply to get the liking Sones for
538 * @return The Sones that like the given reply
540 public Set<Sone> getLikes(PostReply reply) {
541 Set<Sone> sones = new HashSet<Sone>();
542 for (Sone sone : getSones()) {
543 if (sone.getLikedReplyIds().contains(reply.getId())) {
551 * Returns whether the given post is bookmarked.
555 * @return {@code true} if the given post is bookmarked, {@code false}
558 public boolean isBookmarked(Post post) {
559 return isPostBookmarked(post.getId());
563 * Returns whether the post with the given ID is bookmarked.
566 * The ID of the post to check
567 * @return {@code true} if the post with the given ID is bookmarked, {@code
570 public boolean isPostBookmarked(String id) {
571 synchronized (bookmarkedPosts) {
572 return bookmarkedPosts.contains(id);
577 * Returns all currently known bookmarked posts.
579 * @return All bookmarked posts
581 public Set<Post> getBookmarkedPosts() {
582 Set<Post> posts = new HashSet<Post>();
583 synchronized (bookmarkedPosts) {
584 for (String bookmarkedPostId : bookmarkedPosts) {
585 Optional<Post> post = getPost(bookmarkedPostId);
586 if (post.isPresent()) {
587 posts.add(post.get());
594 public Optional<Album> getAlbum(String albumId) {
595 return database.getAlbum(albumId);
598 public Optional<Image> getImage(String imageId) {
599 return database.getImage(imageId);
603 * Returns the temporary image with the given ID.
606 * The ID of the temporary image
607 * @return The temporary image, or {@code null} if there is no temporary image
610 public TemporaryImage getTemporaryImage(String imageId) {
611 synchronized (temporaryImages) {
612 return temporaryImages.get(imageId);
621 * Locks the given Sone. A locked Sone will not be inserted by {@link
622 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
627 public void lockSone(Sone sone) {
628 synchronized (lockedSones) {
629 if (lockedSones.add(sone)) {
630 eventBus.post(new SoneLockedEvent(sone));
636 * Unlocks the given Sone.
640 * @see #lockSone(Sone)
642 public void unlockSone(Sone sone) {
643 synchronized (lockedSones) {
644 if (lockedSones.remove(sone)) {
645 eventBus.post(new SoneUnlockedEvent(sone));
651 * Adds a local Sone from the given own identity.
654 * The own identity to create a Sone from
655 * @return The added (or already existing) Sone
657 public Sone addLocalSone(OwnIdentity ownIdentity) {
658 if (ownIdentity == null) {
659 logger.log(Level.WARNING, "Given OwnIdentity is null!");
662 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
663 synchronized (sones) {
666 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
667 } catch (MalformedURLException mue1) {
668 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
671 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
672 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
674 /* TODO - load posts ’n stuff */
675 sones.put(ownIdentity.getId(), sone);
676 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
677 soneInserters.put(sone, soneInserter);
678 sone.setStatus(SoneStatus.idle);
680 soneInserter.start();
686 * Creates a new Sone for the given own identity.
689 * The own identity to create a Sone for
690 * @return The created Sone
692 public Sone createSone(OwnIdentity ownIdentity) {
693 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
694 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
697 Sone sone = addLocalSone(ownIdentity);
698 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
699 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
700 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
701 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
702 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
703 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
705 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
706 touchConfiguration();
711 * Adds the Sone of the given identity.
714 * The identity whose Sone to add
715 * @return The added or already existing Sone
717 public Sone addRemoteSone(Identity identity) {
718 if (identity == null) {
719 logger.log(Level.WARNING, "Given Identity is null!");
722 synchronized (sones) {
723 final Sone sone = getRemoteSone(identity.getId(), true);
724 if (sone.isLocal()) {
727 sone.setIdentity(identity);
728 boolean newSone = sone.getRequestUri() == null;
729 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
730 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
732 synchronized (knownSones) {
733 newSone = !knownSones.contains(sone.getId());
735 sone.setKnown(!newSone);
737 eventBus.post(new NewSoneFoundEvent(sone));
738 for (Sone localSone : getLocalSones()) {
739 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
740 followSone(localSone, sone.getId());
745 soneDownloader.addSone(sone);
746 soneDownloaders.execute(new Runnable() {
749 @SuppressWarnings("synthetic-access")
751 soneDownloader.fetchSone(sone, sone.getRequestUri());
760 * Lets the given local Sone follow the Sone with the given ID.
763 * The local Sone that should follow another Sone
765 * The ID of the Sone to follow
767 public void followSone(Sone sone, String soneId) {
768 checkNotNull(sone, "sone must not be null");
769 checkNotNull(soneId, "soneId must not be null");
770 sone.addFriend(soneId);
771 synchronized (soneFollowingTimes) {
772 if (!soneFollowingTimes.containsKey(soneId)) {
773 long now = System.currentTimeMillis();
774 soneFollowingTimes.put(soneId, now);
775 Optional<Sone> followedSone = getSone(soneId);
776 if (!followedSone.isPresent()) {
779 for (Post post : followedSone.get().getPosts()) {
780 if (post.getTime() < now) {
784 for (PostReply reply : followedSone.get().getReplies()) {
785 if (reply.getTime() < now) {
786 markReplyKnown(reply);
791 touchConfiguration();
795 * Lets the given local Sone unfollow the Sone with the given ID.
798 * The local Sone that should unfollow another Sone
800 * The ID of the Sone being unfollowed
802 public void unfollowSone(Sone sone, String soneId) {
803 checkNotNull(sone, "sone must not be null");
804 checkNotNull(soneId, "soneId must not be null");
805 sone.removeFriend(soneId);
806 boolean unfollowedSoneStillFollowed = false;
807 for (Sone localSone : getLocalSones()) {
808 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
810 if (!unfollowedSoneStillFollowed) {
811 synchronized (soneFollowingTimes) {
812 soneFollowingTimes.remove(soneId);
815 touchConfiguration();
819 * Sets the trust value of the given origin Sone for the target Sone.
826 * The trust value (from {@code -100} to {@code 100})
828 public void setTrust(Sone origin, Sone target, int trustValue) {
829 checkNotNull(origin, "origin must not be null");
830 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
831 checkNotNull(target, "target must not be null");
832 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
833 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
837 * Removes any trust assignment for the given target Sone.
844 public void removeTrust(Sone origin, Sone target) {
845 checkNotNull(origin, "origin must not be null");
846 checkNotNull(target, "target must not be null");
847 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
848 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
852 * Assigns the configured positive trust value for the given target.
859 public void trustSone(Sone origin, Sone target) {
860 setTrust(origin, target, preferences.getPositiveTrust());
864 * Assigns the configured negative trust value for the given target.
871 public void distrustSone(Sone origin, Sone target) {
872 setTrust(origin, target, preferences.getNegativeTrust());
876 * Removes the trust assignment for the given target.
883 public void untrustSone(Sone origin, Sone target) {
884 removeTrust(origin, target);
888 * Updates the stored Sone with the given Sone.
893 public void updateSone(Sone sone) {
894 updateSone(sone, false);
898 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
899 * {@code true}, an older Sone than the current Sone can be given to restore an
904 * @param soneRescueMode
905 * {@code true} if the stored Sone should be updated regardless of the age of
908 public void updateSone(Sone sone, boolean soneRescueMode) {
909 Optional<Sone> storedSone = getSone(sone.getId());
910 if (storedSone.isPresent()) {
911 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
912 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
915 /* find removed posts. */
916 Collection<Post> existingPosts = database.getPosts(sone.getId());
917 for (Post oldPost : existingPosts) {
918 if (!sone.getPosts().contains(oldPost)) {
919 eventBus.post(new PostRemovedEvent(oldPost));
922 /* find new posts. */
923 for (Post newPost : sone.getPosts()) {
924 if (existingPosts.contains(newPost)) {
927 if (newPost.getTime() < getSoneFollowingTime(sone)) {
928 newPost.setKnown(true);
929 } else if (!newPost.isKnown()) {
930 eventBus.post(new NewPostFoundEvent(newPost));
934 database.storePosts(sone, sone.getPosts());
935 if (!soneRescueMode) {
936 for (PostReply reply : storedSone.get().getReplies()) {
937 if (!sone.getReplies().contains(reply)) {
938 eventBus.post(new PostReplyRemovedEvent(reply));
942 Set<PostReply> storedReplies = storedSone.get().getReplies();
943 for (PostReply reply : sone.getReplies()) {
944 if (storedReplies.contains(reply)) {
947 if (reply.getTime() < getSoneFollowingTime(sone)) {
948 reply.setKnown(true);
949 } else if (!reply.isKnown()) {
950 eventBus.post(new NewPostReplyFoundEvent(reply));
953 database.storePostReplies(sone, sone.getReplies());
954 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
955 database.removeAlbum(album);
956 for (Image image : album.getImages()) {
957 database.removeImage(image);
960 for (Album album : sone.getRootAlbum().getAlbums()) {
961 database.storeAlbum(album);
962 for (Image image : album.getImages()) {
963 database.storeImage(image);
966 synchronized (sones) {
967 sone.setOptions(storedSone.get().getOptions());
968 sone.setKnown(storedSone.get().isKnown());
969 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
970 if (sone.isLocal()) {
971 soneInserters.get(storedSone.get()).setSone(sone);
972 touchConfiguration();
974 sones.put(sone.getId(), sone);
980 * Deletes the given Sone. This will remove the Sone from the {@link
981 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
982 * context from its identity.
987 public void deleteSone(Sone sone) {
988 if (!(sone.getIdentity() instanceof OwnIdentity)) {
989 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
992 synchronized (sones) {
993 if (!getLocalSones().contains(sone)) {
994 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
997 sones.remove(sone.getId());
998 SoneInserter soneInserter = soneInserters.remove(sone);
1001 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1002 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1004 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1005 } catch (ConfigurationException ce1) {
1006 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1011 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1012 * known} before, a {@link MarkSoneKnownEvent} is fired.
1015 * The Sone to mark as known
1017 public void markSoneKnown(Sone sone) {
1018 if (!sone.isKnown()) {
1019 sone.setKnown(true);
1020 synchronized (knownSones) {
1021 knownSones.add(sone.getId());
1023 eventBus.post(new MarkSoneKnownEvent(sone));
1024 touchConfiguration();
1029 * Loads and updates the given Sone from the configuration. If any error is
1030 * encountered, loading is aborted and the given Sone is not changed.
1033 * The Sone to load and update
1035 public void loadSone(Sone sone) {
1036 if (!sone.isLocal()) {
1037 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1040 logger.info(String.format("Loading local Sone: %s", sone));
1042 /* initialize options. */
1043 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1044 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1045 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1046 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1047 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1048 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1051 String sonePrefix = "Sone/" + sone.getId();
1052 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1053 if (soneTime == null) {
1054 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1057 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1060 Profile profile = new Profile(sone);
1061 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1062 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1063 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1064 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1065 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1066 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1068 /* load profile fields. */
1070 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1071 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1072 if (fieldName == null) {
1075 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1076 profile.addField(fieldName).setValue(fieldValue);
1080 Set<Post> posts = new HashSet<Post>();
1082 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1083 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1084 if (postId == null) {
1087 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1088 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1089 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1090 if ((postTime == 0) || (postText == null)) {
1091 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1094 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1095 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1096 postBuilder.to(postRecipientId);
1098 posts.add(postBuilder.build());
1102 Set<PostReply> replies = new HashSet<PostReply>();
1104 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1105 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1106 if (replyId == null) {
1109 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1110 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1111 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1112 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1113 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1116 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1117 replies.add(postReplyBuilder.build());
1120 /* load post likes. */
1121 Set<String> likedPostIds = new HashSet<String>();
1123 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1124 if (likedPostId == null) {
1127 likedPostIds.add(likedPostId);
1130 /* load reply likes. */
1131 Set<String> likedReplyIds = new HashSet<String>();
1133 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1134 if (likedReplyId == null) {
1137 likedReplyIds.add(likedReplyId);
1141 Set<String> friends = new HashSet<String>();
1143 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1144 if (friendId == null) {
1147 friends.add(friendId);
1151 Map<String, Album> albums = Maps.newHashMap();
1152 int albumCounter = 0;
1154 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1155 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1156 if (albumId == null) {
1159 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1160 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1161 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1162 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1163 if ((albumTitle == null) || (albumDescription == null)) {
1164 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1167 Album parentAlbum = sone.getRootAlbum();
1168 if (albumParentId != null) {
1169 parentAlbum = albums.get(albumParentId);
1171 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1172 albums.put(album.getId(), album);
1176 int imageCounter = 0;
1178 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1179 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1180 if (imageId == null) {
1183 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1184 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1185 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1186 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1187 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1188 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1189 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1190 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1191 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1194 Album album = albums.get(albumId);
1195 if (album == null) {
1196 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1199 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1203 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1204 if (avatarId != null) {
1205 profile.setAvatar(getImage(avatarId).orNull());
1209 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1210 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1211 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1212 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1213 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1214 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1216 /* if we’re still here, Sone was loaded successfully. */
1217 synchronized (sone) {
1218 sone.setTime(soneTime);
1219 sone.setProfile(profile);
1220 sone.setPosts(posts);
1221 sone.setReplies(replies);
1222 sone.setLikePostIds(likedPostIds);
1223 sone.setLikeReplyIds(likedReplyIds);
1224 for (String friendId : friends) {
1225 followSone(sone, friendId);
1227 for (Album album : sone.getRootAlbum().getAlbums()) {
1230 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1232 synchronized (knownSones) {
1233 for (String friend : friends) {
1234 knownSones.add(friend);
1237 database.storePosts(sone, posts);
1238 for (Post post : posts) {
1239 post.setKnown(true);
1241 database.storePostReplies(sone, replies);
1242 for (PostReply reply : replies) {
1243 reply.setKnown(true);
1246 logger.info(String.format("Sone loaded successfully: %s", sone));
1250 * Creates a new post.
1253 * The Sone that creates the post
1255 * The text of the post
1256 * @return The created post
1258 public Post createPost(Sone sone, String text) {
1259 return createPost(sone, System.currentTimeMillis(), text);
1263 * Creates a new post.
1266 * The Sone that creates the post
1268 * The time of the post
1270 * The text of the post
1271 * @return The created post
1273 public Post createPost(Sone sone, long time, String text) {
1274 return createPost(sone, null, time, text);
1278 * Creates a new post.
1281 * The Sone that creates the post
1283 * The recipient Sone, or {@code null} if this post does not have a
1286 * The text of the post
1287 * @return The created post
1289 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1290 return createPost(sone, recipient, System.currentTimeMillis(), text);
1294 * Creates a new post.
1297 * The Sone that creates the post
1299 * The recipient Sone, or {@code null} if this post does not have a
1302 * The time of the post
1304 * The text of the post
1305 * @return The created post
1307 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1308 checkNotNull(text, "text must not be null");
1309 checkArgument(text.trim().length() > 0, "text must not be empty");
1310 if (!sone.isLocal()) {
1311 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1314 PostBuilder postBuilder = database.newPostBuilder();
1315 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1316 if (recipient.isPresent()) {
1317 postBuilder.to(recipient.get().getId());
1319 final Post post = postBuilder.build();
1320 database.storePost(post);
1321 eventBus.post(new NewPostFoundEvent(post));
1323 touchConfiguration();
1324 localElementTicker.schedule(new Runnable() {
1331 markPostKnown(post);
1333 }, 10, TimeUnit.SECONDS);
1338 * Deletes the given post.
1341 * The post to delete
1343 public void deletePost(Post post) {
1344 if (!post.getSone().isLocal()) {
1345 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1348 database.removePost(post);
1349 eventBus.post(new PostRemovedEvent(post));
1350 markPostKnown(post);
1351 touchConfiguration();
1355 * Marks the given post as known, if it is currently not a known post
1356 * (according to {@link Post#isKnown()}).
1359 * The post to mark as known
1361 public void markPostKnown(Post post) {
1362 post.setKnown(true);
1363 eventBus.post(new MarkPostKnownEvent(post));
1364 touchConfiguration();
1365 for (PostReply reply : getReplies(post.getId())) {
1366 markReplyKnown(reply);
1371 * Bookmarks the given post.
1374 * The post to bookmark
1376 public void bookmark(Post post) {
1377 bookmarkPost(post.getId());
1381 * Bookmarks the post with the given ID.
1384 * The ID of the post to bookmark
1386 public void bookmarkPost(String id) {
1387 synchronized (bookmarkedPosts) {
1388 bookmarkedPosts.add(id);
1393 * Removes the given post from the bookmarks.
1396 * The post to unbookmark
1398 public void unbookmark(Post post) {
1399 unbookmarkPost(post.getId());
1403 * Removes the post with the given ID from the bookmarks.
1406 * The ID of the post to unbookmark
1408 public void unbookmarkPost(String id) {
1409 synchronized (bookmarkedPosts) {
1410 bookmarkedPosts.remove(id);
1415 * Creates a new reply.
1418 * The Sone that creates the reply
1420 * The post that this reply refers to
1422 * The text of the reply
1423 * @return The created reply
1425 public PostReply createReply(Sone sone, Post post, String text) {
1426 checkNotNull(text, "text must not be null");
1427 checkArgument(text.trim().length() > 0, "text must not be empty");
1428 if (!sone.isLocal()) {
1429 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1432 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1433 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1434 final PostReply reply = postReplyBuilder.build();
1435 database.storePostReply(reply);
1436 eventBus.post(new NewPostReplyFoundEvent(reply));
1437 sone.addReply(reply);
1438 touchConfiguration();
1439 localElementTicker.schedule(new Runnable() {
1446 markReplyKnown(reply);
1448 }, 10, TimeUnit.SECONDS);
1453 * Deletes the given reply.
1456 * The reply to delete
1458 public void deleteReply(PostReply reply) {
1459 Sone sone = reply.getSone();
1460 if (!sone.isLocal()) {
1461 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1464 database.removePostReply(reply);
1465 markReplyKnown(reply);
1466 sone.removeReply(reply);
1467 touchConfiguration();
1471 * Marks the given reply as known, if it is currently not a known reply
1472 * (according to {@link Reply#isKnown()}).
1475 * The reply to mark as known
1477 public void markReplyKnown(PostReply reply) {
1478 boolean previouslyKnown = reply.isKnown();
1479 reply.setKnown(true);
1480 eventBus.post(new MarkPostReplyKnownEvent(reply));
1481 if (!previouslyKnown) {
1482 touchConfiguration();
1487 * Creates a new image.
1490 * The Sone creating the image
1492 * The album the image will be inserted into
1493 * @param temporaryImage
1494 * The temporary image to create the image from
1495 * @return The newly created image
1497 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1498 checkNotNull(sone, "sone must not be null");
1499 checkNotNull(album, "album must not be null");
1500 checkNotNull(temporaryImage, "temporaryImage must not be null");
1501 checkArgument(sone.isLocal(), "sone must be a local Sone");
1502 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1503 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1504 imageInserter.insertImage(temporaryImage, image);
1509 * Deletes the given image. This method will also delete a matching temporary
1513 * The image to delete
1514 * @see #deleteTemporaryImage(TemporaryImage)
1516 public void deleteImage(Image image) {
1517 checkNotNull(image, "image must not be null");
1518 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1519 deleteTemporaryImage(image.getId());
1521 touchConfiguration();
1525 * Creates a new temporary image.
1528 * The MIME type of the temporary image
1530 * The encoded data of the image
1531 * @return The temporary image
1533 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1534 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1535 synchronized (temporaryImages) {
1536 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1538 return temporaryImage;
1542 * Deletes the given temporary image.
1544 * @param temporaryImage
1545 * The temporary image to delete
1547 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1548 checkNotNull(temporaryImage, "temporaryImage must not be null");
1549 deleteTemporaryImage(temporaryImage.getId());
1553 * Deletes the temporary image with the given ID.
1556 * The ID of the temporary image to delete
1558 public void deleteTemporaryImage(String imageId) {
1559 checkNotNull(imageId, "imageId must not be null");
1560 synchronized (temporaryImages) {
1561 temporaryImages.remove(imageId);
1563 Optional<Image> image = getImage(imageId);
1564 if (image.isPresent()) {
1565 imageInserter.cancelImageInsert(image.get());
1570 * Notifies the core that the configuration, either of the core or of a single
1571 * local Sone, has changed, and that the configuration should be saved.
1573 public void touchConfiguration() {
1574 lastConfigurationUpdate = System.currentTimeMillis();
1581 /** Starts the core. */
1583 public void serviceStart() {
1584 loadConfiguration();
1585 updateChecker.start();
1586 identityManager.start();
1587 webOfTrustUpdater.init();
1588 webOfTrustUpdater.start();
1592 /** {@inheritDoc} */
1594 public void serviceRun() {
1595 long lastSaved = System.currentTimeMillis();
1596 while (!shouldStop()) {
1598 long now = System.currentTimeMillis();
1599 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1600 for (Sone localSone : getLocalSones()) {
1601 saveSone(localSone);
1603 saveConfiguration();
1609 /** Stops the core. */
1611 public void serviceStop() {
1612 localElementTicker.shutdownNow();
1613 synchronized (sones) {
1614 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1615 soneInserter.getValue().stop();
1616 saveSone(soneInserter.getKey());
1619 saveConfiguration();
1621 webOfTrustUpdater.stop();
1622 updateChecker.stop();
1623 soneDownloader.stop();
1624 soneDownloaders.shutdown();
1625 identityManager.stop();
1633 * Saves the given Sone. This will persist all local settings for the given
1634 * Sone, such as the friends list and similar, private options.
1639 private synchronized void saveSone(Sone sone) {
1640 if (!sone.isLocal()) {
1641 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1644 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1645 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1649 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1651 /* save Sone into configuration. */
1652 String sonePrefix = "Sone/" + sone.getId();
1653 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1654 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1657 Profile profile = sone.getProfile();
1658 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1659 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1660 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1661 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1662 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1663 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1664 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1666 /* save profile fields. */
1667 int fieldCounter = 0;
1668 for (Field profileField : profile.getFields()) {
1669 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1670 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1671 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1673 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1676 int postCounter = 0;
1677 for (Post post : sone.getPosts()) {
1678 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1679 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1680 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1681 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1682 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1684 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1687 int replyCounter = 0;
1688 for (PostReply reply : sone.getReplies()) {
1689 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1690 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1691 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1692 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1693 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1695 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1697 /* save post likes. */
1698 int postLikeCounter = 0;
1699 for (String postId : sone.getLikedPostIds()) {
1700 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1702 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1704 /* save reply likes. */
1705 int replyLikeCounter = 0;
1706 for (String replyId : sone.getLikedReplyIds()) {
1707 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1709 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1712 int friendCounter = 0;
1713 for (String friendId : sone.getFriends()) {
1714 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1716 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1718 /* save albums. first, collect in a flat structure, top-level first. */
1719 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1721 int albumCounter = 0;
1722 for (Album album : albums) {
1723 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1724 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1725 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1726 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1727 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1728 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1730 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1733 int imageCounter = 0;
1734 for (Album album : albums) {
1735 for (Image image : album.getImages()) {
1736 if (!image.isInserted()) {
1739 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1740 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1741 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1742 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1743 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1744 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1745 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1746 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1747 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1750 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1753 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1754 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1755 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1756 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1757 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1758 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1760 configuration.save();
1762 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1764 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1765 } catch (ConfigurationException ce1) {
1766 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1770 /** Saves the current options. */
1771 private void saveConfiguration() {
1772 synchronized (configuration) {
1773 if (storingConfiguration) {
1774 logger.log(Level.FINE, "Already storing configuration…");
1777 storingConfiguration = true;
1780 /* store the options first. */
1782 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1783 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1784 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1785 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1786 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1787 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1788 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1789 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1790 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1791 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1792 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1793 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1795 /* save known Sones. */
1796 int soneCounter = 0;
1797 synchronized (knownSones) {
1798 for (String knownSoneId : knownSones) {
1799 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1801 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1804 /* save Sone following times. */
1806 synchronized (soneFollowingTimes) {
1807 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1808 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1809 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1812 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1815 /* save known posts. */
1818 /* save bookmarked posts. */
1819 int bookmarkedPostCounter = 0;
1820 synchronized (bookmarkedPosts) {
1821 for (String bookmarkedPostId : bookmarkedPosts) {
1822 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1825 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1828 configuration.save();
1830 } catch (ConfigurationException ce1) {
1831 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1832 } catch (DatabaseException de1) {
1833 logger.log(Level.SEVERE, "Could not save database!", de1);
1835 synchronized (configuration) {
1836 storingConfiguration = false;
1841 /** Loads the configuration. */
1842 private void loadConfiguration() {
1843 /* create options. */
1844 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1847 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1848 SoneInserter.setInsertionDelay(newValue);
1852 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1853 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1854 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1855 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1856 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1857 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1858 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1859 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1860 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1863 @SuppressWarnings("synthetic-access")
1864 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1865 fcpInterface.setActive(newValue);
1868 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1871 @SuppressWarnings("synthetic-access")
1872 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1873 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1878 loadConfigurationValue("InsertionDelay");
1879 loadConfigurationValue("PostsPerPage");
1880 loadConfigurationValue("ImagesPerPage");
1881 loadConfigurationValue("CharactersPerPost");
1882 loadConfigurationValue("PostCutOffLength");
1883 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1884 loadConfigurationValue("PositiveTrust");
1885 loadConfigurationValue("NegativeTrust");
1886 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1887 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1888 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1890 /* load known Sones. */
1891 int soneCounter = 0;
1893 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1894 if (knownSoneId == null) {
1897 synchronized (knownSones) {
1898 knownSones.add(knownSoneId);
1902 /* load Sone following times. */
1905 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1906 if (soneId == null) {
1909 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1910 synchronized (soneFollowingTimes) {
1911 soneFollowingTimes.put(soneId, time);
1916 /* load bookmarked posts. */
1917 int bookmarkedPostCounter = 0;
1919 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1920 if (bookmarkedPostId == null) {
1923 synchronized (bookmarkedPosts) {
1924 bookmarkedPosts.add(bookmarkedPostId);
1931 * Loads an {@link Integer} configuration value for the option with the given
1932 * name, logging validation failures.
1935 * The name of the option to load
1937 private void loadConfigurationValue(String optionName) {
1939 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1940 } catch (IllegalArgumentException iae1) {
1941 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1946 * Notifies the core that a new {@link OwnIdentity} was added.
1948 * @param ownIdentityAddedEvent
1952 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1953 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1954 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1955 if (ownIdentity.hasContext("Sone")) {
1956 addLocalSone(ownIdentity);
1961 * Notifies the core that an {@link OwnIdentity} was removed.
1963 * @param ownIdentityRemovedEvent
1967 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1968 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1969 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1970 trustedIdentities.removeAll(ownIdentity);
1974 * Notifies the core that a new {@link Identity} was added.
1976 * @param identityAddedEvent
1980 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1981 Identity identity = identityAddedEvent.identity();
1982 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1983 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1984 addRemoteSone(identity);
1988 * Notifies the core that an {@link Identity} was updated.
1990 * @param identityUpdatedEvent
1994 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1995 final Identity identity = identityUpdatedEvent.identity();
1996 soneDownloaders.execute(new Runnable() {
1999 @SuppressWarnings("synthetic-access")
2001 Sone sone = getRemoteSone(identity.getId(), false);
2002 if (sone.isLocal()) {
2005 sone.setIdentity(identity);
2006 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2007 soneDownloader.addSone(sone);
2008 soneDownloader.fetchSone(sone);
2014 * Notifies the core that an {@link Identity} was removed.
2016 * @param identityRemovedEvent
2020 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2021 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2022 Identity identity = identityRemovedEvent.identity();
2023 trustedIdentities.remove(ownIdentity, identity);
2024 boolean foundIdentity = false;
2025 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2026 if (trustedIdentity.getKey().equals(ownIdentity)) {
2029 if (trustedIdentity.getValue().contains(identity)) {
2030 foundIdentity = true;
2033 if (foundIdentity) {
2034 /* some local identity still trusts this identity, don’t remove. */
2037 Optional<Sone> sone = getSone(identity.getId());
2038 if (!sone.isPresent()) {
2039 /* TODO - we don’t have the Sone anymore. should this happen? */
2042 database.removePosts(sone.get());
2043 for (Post post : sone.get().getPosts()) {
2044 eventBus.post(new PostRemovedEvent(post));
2046 database.removePostReplies(sone.get());
2047 for (PostReply reply : sone.get().getReplies()) {
2048 eventBus.post(new PostReplyRemovedEvent(reply));
2050 synchronized (sones) {
2051 sones.remove(identity.getId());
2053 eventBus.post(new SoneRemovedEvent(sone.get()));
2057 * Deletes the temporary image.
2059 * @param imageInsertFinishedEvent
2063 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2064 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2065 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2066 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2067 touchConfiguration();