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;
23 import java.net.MalformedURLException;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
29 import java.util.Map.Entry;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.ScheduledExecutorService;
34 import java.util.concurrent.TimeUnit;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
38 import net.pterodactylus.sone.core.Options.DefaultOption;
39 import net.pterodactylus.sone.core.Options.Option;
40 import net.pterodactylus.sone.core.Options.OptionWatcher;
41 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
42 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
45 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
46 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
47 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
48 import net.pterodactylus.sone.core.event.PostRemovedEvent;
49 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneLockedEvent;
51 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
53 import net.pterodactylus.sone.data.Album;
54 import net.pterodactylus.sone.data.Client;
55 import net.pterodactylus.sone.data.Image;
56 import net.pterodactylus.sone.data.Post;
57 import net.pterodactylus.sone.data.PostReply;
58 import net.pterodactylus.sone.data.Profile;
59 import net.pterodactylus.sone.data.Profile.Field;
60 import net.pterodactylus.sone.data.Reply;
61 import net.pterodactylus.sone.data.Sone;
62 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.SoneImpl;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.PostBuilder;
69 import net.pterodactylus.sone.database.PostProvider;
70 import net.pterodactylus.sone.database.PostReplyBuilder;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.fcp.FcpInterface;
74 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.sone.main.SonePlugin;
84 import net.pterodactylus.sone.utils.IntegerRangePredicate;
85 import net.pterodactylus.util.config.Configuration;
86 import net.pterodactylus.util.config.ConfigurationException;
87 import net.pterodactylus.util.logging.Logging;
88 import net.pterodactylus.util.number.Numbers;
89 import net.pterodactylus.util.service.AbstractService;
90 import net.pterodactylus.util.thread.NamedThreadFactory;
92 import com.google.common.base.Optional;
93 import com.google.common.base.Predicate;
94 import com.google.common.base.Predicates;
95 import com.google.common.collect.FluentIterable;
96 import com.google.common.collect.HashMultimap;
97 import com.google.common.collect.ImmutableSet;
98 import com.google.common.collect.Maps;
99 import com.google.common.collect.Multimap;
100 import com.google.common.collect.Multimaps;
101 import com.google.common.eventbus.EventBus;
102 import com.google.common.eventbus.Subscribe;
103 import com.google.inject.Inject;
105 import freenet.keys.FreenetURI;
110 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
112 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
115 private static final Logger logger = Logging.getLogger(Core.class);
117 /** The start time. */
118 private final long startupTime = System.currentTimeMillis();
121 private final Options options = new Options();
123 /** The preferences. */
124 private final Preferences preferences = new Preferences(options);
126 /** The event bus. */
127 private final EventBus eventBus;
129 /** The configuration. */
130 private Configuration configuration;
132 /** Whether we’re currently saving the configuration. */
133 private boolean storingConfiguration = false;
135 /** The identity manager. */
136 private final IdentityManager identityManager;
138 /** Interface to freenet. */
139 private final FreenetInterface freenetInterface;
141 /** The Sone downloader. */
142 private final SoneDownloader soneDownloader;
144 /** The image inserter. */
145 private final ImageInserter imageInserter;
147 /** Sone downloader thread-pool. */
148 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
150 /** The update checker. */
151 private final UpdateChecker updateChecker;
153 /** The trust updater. */
154 private final WebOfTrustUpdater webOfTrustUpdater;
156 /** The FCP interface. */
157 private volatile FcpInterface fcpInterface;
159 /** The times Sones were followed. */
160 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
162 /** Locked local Sones. */
163 /* synchronize on itself. */
164 private final Set<Sone> lockedSones = new HashSet<Sone>();
166 /** Sone inserters. */
167 /* synchronize access on this on sones. */
168 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
170 /** Sone rescuers. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /* synchronize access on this on itself. */
176 private final Map<String, Sone> sones = new HashMap<String, Sone>();
178 /** All known Sones. */
179 private final Set<String> knownSones = new HashSet<String>();
181 /** The post database. */
182 private final Database database;
184 /** All bookmarked posts. */
185 /* synchronize access on itself. */
186 private final Set<String> bookmarkedPosts = new HashSet<String>();
188 /** Trusted identities, sorted by own identities. */
189 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
191 /** All temporary images. */
192 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
194 /** Ticker for threads that mark own elements as known. */
195 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
197 /** The time the configuration was last touched. */
198 private volatile long lastConfigurationUpdate;
201 * Creates a new core.
203 * @param configuration
204 * The configuration of the core
205 * @param freenetInterface
206 * The freenet interface
207 * @param identityManager
208 * The identity manager
209 * @param webOfTrustUpdater
210 * The WebOfTrust updater
217 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
219 this.configuration = configuration;
220 this.freenetInterface = freenetInterface;
221 this.identityManager = identityManager;
222 this.soneDownloader = new SoneDownloader(this, freenetInterface);
223 this.imageInserter = new ImageInserter(freenetInterface);
224 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
225 this.webOfTrustUpdater = webOfTrustUpdater;
226 this.eventBus = eventBus;
227 this.database = database;
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 checkNotNull(sone, "sone must not be null");
301 checkArgument(sone.isLocal(), "sone must be local");
302 synchronized (sones) {
303 SoneRescuer soneRescuer = soneRescuers.get(sone);
304 if (soneRescuer == null) {
305 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
306 soneRescuers.put(sone, soneRescuer);
314 * Returns whether the given Sone is currently locked.
318 * @return {@code true} if the Sone is locked, {@code false} if it is not
320 public boolean isLocked(Sone sone) {
321 synchronized (lockedSones) {
322 return lockedSones.contains(sone);
330 public Collection<Sone> getSones() {
331 synchronized (sones) {
332 return ImmutableSet.copyOf(sones.values());
337 * Returns the Sone with the given ID, regardless whether it’s local or
341 * The ID of the Sone to get
342 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Optional<Sone> getSone(String id) {
347 synchronized (sones) {
348 return Optional.fromNullable(sones.get(id));
356 public Collection<Sone> getLocalSones() {
357 synchronized (sones) {
358 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
361 public boolean apply(Sone sone) {
362 return sone.isLocal();
369 * Returns the local Sone with the given ID, optionally creating a new Sone.
374 * {@code true} to create a new Sone if none exists,
375 * {@code false} to return null if none exists
376 * @return The Sone with the given ID, or {@code null}
378 public Sone getLocalSone(String id, boolean create) {
379 synchronized (sones) {
380 Sone sone = sones.get(id);
381 if ((sone == null) && create) {
382 sone = new SoneImpl(id, true);
385 if ((sone != null) && !sone.isLocal()) {
386 sone = new SoneImpl(id, true);
397 public Collection<Sone> getRemoteSones() {
398 synchronized (sones) {
399 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
402 public boolean apply(Sone sone) {
403 return !sone.isLocal();
410 * Returns the remote Sone with the given ID.
413 * The ID of the remote Sone to get
415 * {@code true} to always create a Sone, {@code false} to return
416 * {@code null} if no Sone with the given ID exists
417 * @return The Sone with the given ID
419 public Sone getRemoteSone(String id, boolean create) {
420 synchronized (sones) {
421 Sone sone = sones.get(id);
422 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
423 sone = new SoneImpl(id, false);
431 * Returns whether the given Sone has been modified.
434 * The Sone to check for modifications
435 * @return {@code true} if a modification has been detected in the Sone,
436 * {@code false} otherwise
438 public boolean isModifiedSone(Sone sone) {
439 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
443 * Returns the time when the given was first followed by any local Sone.
446 * The Sone to get the time for
447 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
448 * been followed, or {@link Long#MAX_VALUE}
450 public long getSoneFollowingTime(Sone sone) {
451 synchronized (soneFollowingTimes) {
452 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
457 * Returns whether the target Sone is trusted by the origin Sone.
463 * @return {@code true} if the target Sone is trusted by the origin Sone
465 public boolean isSoneTrusted(Sone origin, Sone target) {
466 checkNotNull(origin, "origin must not be null");
467 checkNotNull(target, "target must not be null");
468 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
469 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
473 * Returns a post builder.
475 * @return A new post builder
477 public PostBuilder postBuilder() {
478 return database.newPostBuilder();
485 public Optional<Post> getPost(String postId) {
486 return database.getPost(postId);
493 public Collection<Post> getPosts(String soneId) {
494 return database.getPosts(soneId);
501 public Collection<Post> getDirectedPosts(final String recipientId) {
502 checkNotNull(recipientId, "recipient must not be null");
503 return database.getDirectedPosts(recipientId);
507 * Returns a post reply builder.
509 * @return A new post reply builder
511 public PostReplyBuilder postReplyBuilder() {
512 return database.newPostReplyBuilder();
519 public Optional<PostReply> getPostReply(String replyId) {
520 return database.getPostReply(replyId);
527 public List<PostReply> getReplies(final String postId) {
528 return database.getReplies(postId);
532 * Returns all Sones that have liked the given post.
535 * The post to get the liking Sones for
536 * @return The Sones that like the given post
538 public Set<Sone> getLikes(Post post) {
539 Set<Sone> sones = new HashSet<Sone>();
540 for (Sone sone : getSones()) {
541 if (sone.getLikedPostIds().contains(post.getId())) {
549 * Returns all Sones that have liked the given reply.
552 * The reply to get the liking Sones for
553 * @return The Sones that like the given reply
555 public Set<Sone> getLikes(PostReply reply) {
556 Set<Sone> sones = new HashSet<Sone>();
557 for (Sone sone : getSones()) {
558 if (sone.getLikedReplyIds().contains(reply.getId())) {
566 * Returns whether the given post is bookmarked.
570 * @return {@code true} if the given post is bookmarked, {@code false}
573 public boolean isBookmarked(Post post) {
574 return isPostBookmarked(post.getId());
578 * Returns whether the post with the given ID is bookmarked.
581 * The ID of the post to check
582 * @return {@code true} if the post with the given ID is bookmarked,
583 * {@code false} otherwise
585 public boolean isPostBookmarked(String id) {
586 synchronized (bookmarkedPosts) {
587 return bookmarkedPosts.contains(id);
592 * Returns all currently known bookmarked posts.
594 * @return All bookmarked posts
596 public Set<Post> getBookmarkedPosts() {
597 Set<Post> posts = new HashSet<Post>();
598 synchronized (bookmarkedPosts) {
599 for (String bookmarkedPostId : bookmarkedPosts) {
600 Optional<Post> post = getPost(bookmarkedPostId);
601 if (post.isPresent()) {
602 posts.add(post.get());
609 public Optional<Album> getAlbum(String albumId) {
610 return database.getAlbum(albumId);
613 public Optional<Image> getImage(String imageId) {
614 return database.getImage(imageId);
618 * Returns the temporary image with the given ID.
621 * The ID of the temporary image
622 * @return The temporary image, or {@code null} if there is no temporary
623 * image with the given ID
625 public TemporaryImage getTemporaryImage(String imageId) {
626 synchronized (temporaryImages) {
627 return temporaryImages.get(imageId);
636 * Locks the given Sone. A locked Sone will not be inserted by
637 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
643 public void lockSone(Sone sone) {
644 synchronized (lockedSones) {
645 if (lockedSones.add(sone)) {
646 eventBus.post(new SoneLockedEvent(sone));
652 * Unlocks the given Sone.
654 * @see #lockSone(Sone)
658 public void unlockSone(Sone sone) {
659 synchronized (lockedSones) {
660 if (lockedSones.remove(sone)) {
661 eventBus.post(new SoneUnlockedEvent(sone));
667 * Adds a local Sone from the given own identity.
670 * The own identity to create a Sone from
671 * @return The added (or already existing) Sone
673 public Sone addLocalSone(OwnIdentity ownIdentity) {
674 if (ownIdentity == null) {
675 logger.log(Level.WARNING, "Given OwnIdentity is null!");
678 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
679 synchronized (sones) {
682 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
683 } catch (MalformedURLException mue1) {
684 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
687 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
688 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
690 /* TODO - load posts ’n stuff */
691 sones.put(ownIdentity.getId(), sone);
692 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
693 soneInserters.put(sone, soneInserter);
694 sone.setStatus(SoneStatus.idle);
696 soneInserter.start();
702 * Creates a new Sone for the given own identity.
705 * The own identity to create a Sone for
706 * @return The created Sone
708 public Sone createSone(OwnIdentity ownIdentity) {
709 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
710 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
713 Sone sone = addLocalSone(ownIdentity);
714 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
715 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
716 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
717 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
718 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
719 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
721 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
722 touchConfiguration();
727 * Adds the Sone of the given identity.
730 * The identity whose Sone to add
731 * @return The added or already existing Sone
733 public Sone addRemoteSone(Identity identity) {
734 if (identity == null) {
735 logger.log(Level.WARNING, "Given Identity is null!");
738 synchronized (sones) {
739 final Sone sone = getRemoteSone(identity.getId(), true);
740 if (sone.isLocal()) {
743 sone.setIdentity(identity);
744 boolean newSone = sone.getRequestUri() == null;
745 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
746 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
748 synchronized (knownSones) {
749 newSone = !knownSones.contains(sone.getId());
751 sone.setKnown(!newSone);
753 eventBus.post(new NewSoneFoundEvent(sone));
754 for (Sone localSone : getLocalSones()) {
755 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
756 followSone(localSone, sone.getId());
761 soneDownloader.addSone(sone);
762 soneDownloaders.execute(new Runnable() {
765 @SuppressWarnings("synthetic-access")
767 soneDownloader.fetchSone(sone, sone.getRequestUri());
776 * Lets the given local Sone follow the Sone with the given ID.
779 * The local Sone that should follow another Sone
781 * The ID of the Sone to follow
783 public void followSone(Sone sone, String soneId) {
784 checkNotNull(sone, "sone must not be null");
785 checkNotNull(soneId, "soneId must not be null");
786 sone.addFriend(soneId);
787 synchronized (soneFollowingTimes) {
788 if (!soneFollowingTimes.containsKey(soneId)) {
789 long now = System.currentTimeMillis();
790 soneFollowingTimes.put(soneId, now);
791 Optional<Sone> followedSone = getSone(soneId);
792 if (!followedSone.isPresent()) {
795 for (Post post : followedSone.get().getPosts()) {
796 if (post.getTime() < now) {
800 for (PostReply reply : followedSone.get().getReplies()) {
801 if (reply.getTime() < now) {
802 markReplyKnown(reply);
807 touchConfiguration();
811 * Lets the given local Sone unfollow the Sone with the given ID.
814 * The local Sone that should unfollow another Sone
816 * The ID of the Sone being unfollowed
818 public void unfollowSone(Sone sone, String soneId) {
819 checkNotNull(sone, "sone must not be null");
820 checkNotNull(soneId, "soneId must not be null");
821 sone.removeFriend(soneId);
822 boolean unfollowedSoneStillFollowed = false;
823 for (Sone localSone : getLocalSones()) {
824 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
826 if (!unfollowedSoneStillFollowed) {
827 synchronized (soneFollowingTimes) {
828 soneFollowingTimes.remove(soneId);
831 touchConfiguration();
835 * Sets the trust value of the given origin Sone for the target Sone.
842 * The trust value (from {@code -100} to {@code 100})
844 public void setTrust(Sone origin, Sone target, int trustValue) {
845 checkNotNull(origin, "origin must not be null");
846 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
847 checkNotNull(target, "target must not be null");
848 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
849 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
853 * Removes any trust assignment for the given target Sone.
860 public void removeTrust(Sone origin, Sone target) {
861 checkNotNull(origin, "origin must not be null");
862 checkNotNull(target, "target must not be null");
863 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
864 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
868 * Assigns the configured positive trust value for the given target.
875 public void trustSone(Sone origin, Sone target) {
876 setTrust(origin, target, preferences.getPositiveTrust());
880 * Assigns the configured negative trust value for the given target.
887 public void distrustSone(Sone origin, Sone target) {
888 setTrust(origin, target, preferences.getNegativeTrust());
892 * Removes the trust assignment for the given target.
899 public void untrustSone(Sone origin, Sone target) {
900 removeTrust(origin, target);
904 * Updates the stored Sone with the given Sone.
909 public void updateSone(Sone sone) {
910 updateSone(sone, false);
914 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
915 * {@code true}, an older Sone than the current Sone can be given to restore
920 * @param soneRescueMode
921 * {@code true} if the stored Sone should be updated regardless
922 * of the age of the given Sone
924 public void updateSone(Sone sone, boolean soneRescueMode) {
925 Optional<Sone> storedSone = getSone(sone.getId());
926 if (storedSone.isPresent()) {
927 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
928 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
931 /* find removed posts. */
932 Collection<Post> existingPosts = database.getPosts(sone.getId());
933 for (Post oldPost : existingPosts) {
934 if (!sone.getPosts().contains(oldPost)) {
935 eventBus.post(new PostRemovedEvent(oldPost));
938 /* find new posts. */
939 for (Post newPost : sone.getPosts()) {
940 if (existingPosts.contains(newPost)) {
943 if (newPost.getTime() < getSoneFollowingTime(sone)) {
944 newPost.setKnown(true);
945 } else if (!newPost.isKnown()) {
946 eventBus.post(new NewPostFoundEvent(newPost));
950 database.storePosts(sone, sone.getPosts());
951 if (!soneRescueMode) {
952 for (PostReply reply : storedSone.get().getReplies()) {
953 if (!sone.getReplies().contains(reply)) {
954 eventBus.post(new PostReplyRemovedEvent(reply));
958 Set<PostReply> storedReplies = storedSone.get().getReplies();
959 for (PostReply reply : sone.getReplies()) {
960 if (storedReplies.contains(reply)) {
963 if (reply.getTime() < getSoneFollowingTime(sone)) {
964 reply.setKnown(true);
965 } else if (!reply.isKnown()) {
966 eventBus.post(new NewPostReplyFoundEvent(reply));
969 database.storePostReplies(sone, sone.getReplies());
970 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
971 database.removeAlbum(album);
972 for (Image image : album.getImages()) {
973 database.removeImage(image);
976 for (Album album : sone.getRootAlbum().getAlbums()) {
977 database.storeAlbum(album);
978 for (Image image : album.getImages()) {
979 database.storeImage(image);
982 synchronized (sones) {
983 sone.setOptions(storedSone.get().getOptions());
984 sone.setKnown(storedSone.get().isKnown());
985 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
986 if (sone.isLocal()) {
987 soneInserters.get(storedSone.get()).setSone(sone);
988 touchConfiguration();
990 sones.put(sone.getId(), sone);
996 * Deletes the given Sone. This will remove the Sone from the
997 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
998 * remove the context from its identity.
1001 * The Sone to delete
1003 public void deleteSone(Sone sone) {
1004 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1005 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1008 synchronized (sones) {
1009 if (!getLocalSones().contains(sone)) {
1010 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1013 sones.remove(sone.getId());
1014 SoneInserter soneInserter = soneInserters.remove(sone);
1015 soneInserter.stop();
1017 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1018 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1020 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1021 } catch (ConfigurationException ce1) {
1022 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1027 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1028 * known} before, a {@link MarkSoneKnownEvent} is fired.
1031 * The Sone to mark as known
1033 public void markSoneKnown(Sone sone) {
1034 if (!sone.isKnown()) {
1035 sone.setKnown(true);
1036 synchronized (knownSones) {
1037 knownSones.add(sone.getId());
1039 eventBus.post(new MarkSoneKnownEvent(sone));
1040 touchConfiguration();
1045 * Loads and updates the given Sone from the configuration. If any error is
1046 * encountered, loading is aborted and the given Sone is not changed.
1049 * The Sone to load and update
1051 public void loadSone(Sone sone) {
1052 if (!sone.isLocal()) {
1053 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1056 logger.info(String.format("Loading local Sone: %s", sone));
1058 /* initialize options. */
1059 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1060 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1061 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1062 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1063 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1064 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1067 String sonePrefix = "Sone/" + sone.getId();
1068 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1069 if (soneTime == null) {
1070 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1073 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1076 Profile profile = new Profile(sone);
1077 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1078 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1079 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1080 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1081 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1082 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1084 /* load profile fields. */
1086 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1087 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1088 if (fieldName == null) {
1091 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1092 profile.addField(fieldName).setValue(fieldValue);
1096 Set<Post> posts = new HashSet<Post>();
1098 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1099 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1100 if (postId == null) {
1103 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1104 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1105 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1106 if ((postTime == 0) || (postText == null)) {
1107 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1110 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1111 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1112 postBuilder.to(postRecipientId);
1114 posts.add(postBuilder.build());
1118 Set<PostReply> replies = new HashSet<PostReply>();
1120 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1121 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1122 if (replyId == null) {
1125 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1126 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1127 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1128 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1129 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1132 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1133 replies.add(postReplyBuilder.build());
1136 /* load post likes. */
1137 Set<String> likedPostIds = new HashSet<String>();
1139 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1140 if (likedPostId == null) {
1143 likedPostIds.add(likedPostId);
1146 /* load reply likes. */
1147 Set<String> likedReplyIds = new HashSet<String>();
1149 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1150 if (likedReplyId == null) {
1153 likedReplyIds.add(likedReplyId);
1157 Set<String> friends = new HashSet<String>();
1159 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1160 if (friendId == null) {
1163 friends.add(friendId);
1167 Map<String, Album> albums = Maps.newHashMap();
1168 int albumCounter = 0;
1170 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1171 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1172 if (albumId == null) {
1175 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1176 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1177 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1178 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1179 if ((albumTitle == null) || (albumDescription == null)) {
1180 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1183 Album parentAlbum = sone.getRootAlbum();
1184 if (albumParentId != null) {
1185 parentAlbum = albums.get(albumParentId);
1187 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1188 albums.put(album.getId(), album);
1192 int imageCounter = 0;
1194 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1195 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1196 if (imageId == null) {
1199 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1200 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1201 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1202 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1203 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1204 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1205 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1206 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1207 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1210 Album album = albums.get(albumId);
1211 if (album == null) {
1212 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1215 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1219 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1220 if (avatarId != null) {
1221 profile.setAvatar(getImage(avatarId).orNull());
1225 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1226 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1227 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1228 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1229 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1230 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1232 /* if we’re still here, Sone was loaded successfully. */
1233 synchronized (sone) {
1234 sone.setTime(soneTime);
1235 sone.setProfile(profile);
1236 sone.setPosts(posts);
1237 sone.setReplies(replies);
1238 sone.setLikePostIds(likedPostIds);
1239 sone.setLikeReplyIds(likedReplyIds);
1240 for (String friendId : friends) {
1241 followSone(sone, friendId);
1243 for (Album album : sone.getRootAlbum().getAlbums()) {
1244 sone.getRootAlbum().removeAlbum(album);
1246 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1248 synchronized (knownSones) {
1249 for (String friend : friends) {
1250 knownSones.add(friend);
1253 database.storePosts(sone, posts);
1254 for (Post post : posts) {
1255 post.setKnown(true);
1257 database.storePostReplies(sone, replies);
1258 for (PostReply reply : replies) {
1259 reply.setKnown(true);
1262 logger.info(String.format("Sone loaded successfully: %s", sone));
1266 * Creates a new post.
1269 * The Sone that creates the post
1271 * The text of the post
1272 * @return The created post
1274 public Post createPost(Sone sone, String text) {
1275 return createPost(sone, System.currentTimeMillis(), text);
1279 * Creates a new post.
1282 * The Sone that creates the post
1284 * The time of the post
1286 * The text of the post
1287 * @return The created post
1289 public Post createPost(Sone sone, long time, String text) {
1290 return createPost(sone, null, time, 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
1302 * The text of the post
1303 * @return The created post
1305 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1306 return createPost(sone, recipient, System.currentTimeMillis(), text);
1310 * Creates a new post.
1313 * The Sone that creates the post
1315 * The recipient Sone, or {@code null} if this post does not have
1318 * The time of the post
1320 * The text of the post
1321 * @return The created post
1323 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1324 checkNotNull(text, "text must not be null");
1325 checkArgument(text.trim().length() > 0, "text must not be empty");
1326 if (!sone.isLocal()) {
1327 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1330 PostBuilder postBuilder = database.newPostBuilder();
1331 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1332 if (recipient.isPresent()) {
1333 postBuilder.to(recipient.get().getId());
1335 final Post post = postBuilder.build();
1336 database.storePost(post);
1337 eventBus.post(new NewPostFoundEvent(post));
1339 touchConfiguration();
1340 localElementTicker.schedule(new Runnable() {
1347 markPostKnown(post);
1349 }, 10, TimeUnit.SECONDS);
1354 * Deletes the given post.
1357 * The post to delete
1359 public void deletePost(Post post) {
1360 if (!post.getSone().isLocal()) {
1361 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1364 database.removePost(post);
1365 eventBus.post(new PostRemovedEvent(post));
1366 markPostKnown(post);
1367 touchConfiguration();
1371 * Marks the given post as known, if it is currently not a known post
1372 * (according to {@link Post#isKnown()}).
1375 * The post to mark as known
1377 public void markPostKnown(Post post) {
1378 post.setKnown(true);
1379 eventBus.post(new MarkPostKnownEvent(post));
1380 touchConfiguration();
1381 for (PostReply reply : getReplies(post.getId())) {
1382 markReplyKnown(reply);
1387 * Bookmarks the given post.
1390 * The post to bookmark
1392 public void bookmark(Post post) {
1393 bookmarkPost(post.getId());
1397 * Bookmarks the post with the given ID.
1400 * The ID of the post to bookmark
1402 public void bookmarkPost(String id) {
1403 synchronized (bookmarkedPosts) {
1404 bookmarkedPosts.add(id);
1409 * Removes the given post from the bookmarks.
1412 * The post to unbookmark
1414 public void unbookmark(Post post) {
1415 unbookmarkPost(post.getId());
1419 * Removes the post with the given ID from the bookmarks.
1422 * The ID of the post to unbookmark
1424 public void unbookmarkPost(String id) {
1425 synchronized (bookmarkedPosts) {
1426 bookmarkedPosts.remove(id);
1431 * Creates a new reply.
1434 * The Sone that creates the reply
1436 * The post that this reply refers to
1438 * The text of the reply
1439 * @return The created reply
1441 public PostReply createReply(Sone sone, Post post, String text) {
1442 checkNotNull(text, "text must not be null");
1443 checkArgument(text.trim().length() > 0, "text must not be empty");
1444 if (!sone.isLocal()) {
1445 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1448 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1449 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1450 final PostReply reply = postReplyBuilder.build();
1451 database.storePostReply(reply);
1452 eventBus.post(new NewPostReplyFoundEvent(reply));
1453 sone.addReply(reply);
1454 touchConfiguration();
1455 localElementTicker.schedule(new Runnable() {
1462 markReplyKnown(reply);
1464 }, 10, TimeUnit.SECONDS);
1469 * Deletes the given reply.
1472 * The reply to delete
1474 public void deleteReply(PostReply reply) {
1475 Sone sone = reply.getSone();
1476 if (!sone.isLocal()) {
1477 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1480 database.removePostReply(reply);
1481 markReplyKnown(reply);
1482 sone.removeReply(reply);
1483 touchConfiguration();
1487 * Marks the given reply as known, if it is currently not a known reply
1488 * (according to {@link Reply#isKnown()}).
1491 * The reply to mark as known
1493 public void markReplyKnown(PostReply reply) {
1494 boolean previouslyKnown = reply.isKnown();
1495 reply.setKnown(true);
1496 eventBus.post(new MarkPostReplyKnownEvent(reply));
1497 if (!previouslyKnown) {
1498 touchConfiguration();
1503 * Deletes the given album. The owner of the album has to be a local Sone,
1504 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1507 * The album to remove
1509 public void deleteAlbum(Album album) {
1510 checkNotNull(album, "album must not be null");
1511 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1512 if (!album.isEmpty()) {
1515 album.getParent().removeAlbum(album);
1516 database.removeAlbum(album);
1517 touchConfiguration();
1521 * Creates a new image.
1524 * The Sone creating the image
1526 * The album the image will be inserted into
1527 * @param temporaryImage
1528 * The temporary image to create the image from
1529 * @return The newly created image
1531 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1532 checkNotNull(sone, "sone must not be null");
1533 checkNotNull(album, "album must not be null");
1534 checkNotNull(temporaryImage, "temporaryImage must not be null");
1535 checkArgument(sone.isLocal(), "sone must be a local Sone");
1536 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1537 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1538 database.storeImage(image);
1539 imageInserter.insertImage(temporaryImage, image);
1544 * Deletes the given image. This method will also delete a matching
1547 * @see #deleteTemporaryImage(TemporaryImage)
1549 * The image to delete
1551 public void deleteImage(Image image) {
1552 checkNotNull(image, "image must not be null");
1553 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1554 deleteTemporaryImage(image.getId());
1555 image.getAlbum().removeImage(image);
1556 database.removeImage(image);
1557 touchConfiguration();
1561 * Creates a new temporary image.
1564 * The MIME type of the temporary image
1566 * The encoded data of the image
1567 * @return The temporary image
1569 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1570 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1571 synchronized (temporaryImages) {
1572 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1574 return temporaryImage;
1578 * Deletes the given temporary image.
1580 * @param temporaryImage
1581 * The temporary image to delete
1583 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1584 checkNotNull(temporaryImage, "temporaryImage must not be null");
1585 deleteTemporaryImage(temporaryImage.getId());
1589 * Deletes the temporary image with the given ID.
1592 * The ID of the temporary image to delete
1594 public void deleteTemporaryImage(String imageId) {
1595 checkNotNull(imageId, "imageId must not be null");
1596 synchronized (temporaryImages) {
1597 temporaryImages.remove(imageId);
1599 Optional<Image> image = getImage(imageId);
1600 if (image.isPresent()) {
1601 imageInserter.cancelImageInsert(image.get());
1606 * Notifies the core that the configuration, either of the core or of a
1607 * single local Sone, has changed, and that the configuration should be
1610 public void touchConfiguration() {
1611 lastConfigurationUpdate = System.currentTimeMillis();
1622 public void serviceStart() {
1623 loadConfiguration();
1624 updateChecker.start();
1625 identityManager.start();
1626 webOfTrustUpdater.init();
1627 webOfTrustUpdater.start();
1635 public void serviceRun() {
1636 long lastSaved = System.currentTimeMillis();
1637 while (!shouldStop()) {
1639 long now = System.currentTimeMillis();
1640 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1641 for (Sone localSone : getLocalSones()) {
1642 saveSone(localSone);
1644 saveConfiguration();
1654 public void serviceStop() {
1655 localElementTicker.shutdownNow();
1656 synchronized (sones) {
1657 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1658 soneInserter.getValue().stop();
1659 saveSone(soneInserter.getKey());
1662 saveConfiguration();
1664 webOfTrustUpdater.stop();
1665 updateChecker.stop();
1666 soneDownloader.stop();
1667 soneDownloaders.shutdown();
1668 identityManager.stop();
1676 * Saves the given Sone. This will persist all local settings for the given
1677 * Sone, such as the friends list and similar, private options.
1682 private synchronized void saveSone(Sone sone) {
1683 if (!sone.isLocal()) {
1684 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1687 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1688 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1692 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1694 /* save Sone into configuration. */
1695 String sonePrefix = "Sone/" + sone.getId();
1696 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1697 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1700 Profile profile = sone.getProfile();
1701 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1702 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1703 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1704 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1705 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1706 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1707 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1709 /* save profile fields. */
1710 int fieldCounter = 0;
1711 for (Field profileField : profile.getFields()) {
1712 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1713 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1714 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1716 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1719 int postCounter = 0;
1720 for (Post post : sone.getPosts()) {
1721 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1722 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1723 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1724 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1725 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1727 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1730 int replyCounter = 0;
1731 for (PostReply reply : sone.getReplies()) {
1732 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1733 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1734 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1735 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1736 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1738 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1740 /* save post likes. */
1741 int postLikeCounter = 0;
1742 for (String postId : sone.getLikedPostIds()) {
1743 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1745 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1747 /* save reply likes. */
1748 int replyLikeCounter = 0;
1749 for (String replyId : sone.getLikedReplyIds()) {
1750 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1752 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1755 int friendCounter = 0;
1756 for (String friendId : sone.getFriends()) {
1757 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1759 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1761 /* save albums. first, collect in a flat structure, top-level first. */
1762 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1764 int albumCounter = 0;
1765 for (Album album : albums) {
1766 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1767 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1768 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1769 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1770 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1771 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1773 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1776 int imageCounter = 0;
1777 for (Album album : albums) {
1778 for (Image image : album.getImages()) {
1779 if (!image.isInserted()) {
1782 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1783 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1784 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1785 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1786 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1787 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1788 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1789 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1790 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1793 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1796 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1797 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1798 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1799 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1800 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1801 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1803 configuration.save();
1805 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1807 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1808 } catch (ConfigurationException ce1) {
1809 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1814 * Saves the current options.
1816 private void saveConfiguration() {
1817 synchronized (configuration) {
1818 if (storingConfiguration) {
1819 logger.log(Level.FINE, "Already storing configuration…");
1822 storingConfiguration = true;
1825 /* store the options first. */
1827 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1828 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1829 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1830 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1831 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1832 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1833 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1834 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1835 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1836 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1837 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1838 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1840 /* save known Sones. */
1841 int soneCounter = 0;
1842 synchronized (knownSones) {
1843 for (String knownSoneId : knownSones) {
1844 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1846 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1849 /* save Sone following times. */
1851 synchronized (soneFollowingTimes) {
1852 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1853 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1854 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1857 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1860 /* save known posts. */
1863 /* save bookmarked posts. */
1864 int bookmarkedPostCounter = 0;
1865 synchronized (bookmarkedPosts) {
1866 for (String bookmarkedPostId : bookmarkedPosts) {
1867 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1870 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1873 configuration.save();
1875 } catch (ConfigurationException ce1) {
1876 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1877 } catch (DatabaseException de1) {
1878 logger.log(Level.SEVERE, "Could not save database!", de1);
1880 synchronized (configuration) {
1881 storingConfiguration = false;
1887 * Loads the configuration.
1889 private void loadConfiguration() {
1890 /* create options. */
1891 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1894 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1895 SoneInserter.setInsertionDelay(newValue);
1899 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1900 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1901 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1902 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1903 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1904 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1905 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1906 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1907 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1910 @SuppressWarnings("synthetic-access")
1911 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1912 fcpInterface.setActive(newValue);
1915 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1918 @SuppressWarnings("synthetic-access")
1919 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1920 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1925 loadConfigurationValue("InsertionDelay");
1926 loadConfigurationValue("PostsPerPage");
1927 loadConfigurationValue("ImagesPerPage");
1928 loadConfigurationValue("CharactersPerPost");
1929 loadConfigurationValue("PostCutOffLength");
1930 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1931 loadConfigurationValue("PositiveTrust");
1932 loadConfigurationValue("NegativeTrust");
1933 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1934 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1935 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1937 /* load known Sones. */
1938 int soneCounter = 0;
1940 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1941 if (knownSoneId == null) {
1944 synchronized (knownSones) {
1945 knownSones.add(knownSoneId);
1949 /* load Sone following times. */
1952 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1953 if (soneId == null) {
1956 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1957 synchronized (soneFollowingTimes) {
1958 soneFollowingTimes.put(soneId, time);
1963 /* load bookmarked posts. */
1964 int bookmarkedPostCounter = 0;
1966 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1967 if (bookmarkedPostId == null) {
1970 synchronized (bookmarkedPosts) {
1971 bookmarkedPosts.add(bookmarkedPostId);
1978 * Loads an {@link Integer} configuration value for the option with the
1979 * given name, logging validation failures.
1982 * The name of the option to load
1984 private void loadConfigurationValue(String optionName) {
1986 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1987 } catch (IllegalArgumentException iae1) {
1988 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1993 * Notifies the core that a new {@link OwnIdentity} was added.
1995 * @param ownIdentityAddedEvent
1999 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2000 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2001 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2002 if (ownIdentity.hasContext("Sone")) {
2003 addLocalSone(ownIdentity);
2008 * Notifies the core that an {@link OwnIdentity} was removed.
2010 * @param ownIdentityRemovedEvent
2014 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2015 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2016 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2017 trustedIdentities.removeAll(ownIdentity);
2021 * Notifies the core that a new {@link Identity} was added.
2023 * @param identityAddedEvent
2027 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2028 Identity identity = identityAddedEvent.identity();
2029 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2030 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2031 addRemoteSone(identity);
2035 * Notifies the core that an {@link Identity} was updated.
2037 * @param identityUpdatedEvent
2041 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2042 final Identity identity = identityUpdatedEvent.identity();
2043 soneDownloaders.execute(new Runnable() {
2046 @SuppressWarnings("synthetic-access")
2048 Sone sone = getRemoteSone(identity.getId(), false);
2049 if (sone.isLocal()) {
2052 sone.setIdentity(identity);
2053 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2054 soneDownloader.addSone(sone);
2055 soneDownloader.fetchSone(sone);
2061 * Notifies the core that an {@link Identity} was removed.
2063 * @param identityRemovedEvent
2067 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2068 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2069 Identity identity = identityRemovedEvent.identity();
2070 trustedIdentities.remove(ownIdentity, identity);
2071 boolean foundIdentity = false;
2072 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2073 if (trustedIdentity.getKey().equals(ownIdentity)) {
2076 if (trustedIdentity.getValue().contains(identity)) {
2077 foundIdentity = true;
2080 if (foundIdentity) {
2081 /* some local identity still trusts this identity, don’t remove. */
2084 Optional<Sone> sone = getSone(identity.getId());
2085 if (!sone.isPresent()) {
2086 /* TODO - we don’t have the Sone anymore. should this happen? */
2089 database.removePosts(sone.get());
2090 for (Post post : sone.get().getPosts()) {
2091 eventBus.post(new PostRemovedEvent(post));
2093 database.removePostReplies(sone.get());
2094 for (PostReply reply : sone.get().getReplies()) {
2095 eventBus.post(new PostReplyRemovedEvent(reply));
2097 synchronized (sones) {
2098 sones.remove(identity.getId());
2100 eventBus.post(new SoneRemovedEvent(sone.get()));
2104 * Deletes the temporary image.
2106 * @param imageInsertFinishedEvent
2110 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2111 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2112 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2113 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2114 touchConfiguration();