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 freenet.keys.FreenetURI;
94 import com.google.common.base.Optional;
95 import com.google.common.base.Predicate;
96 import com.google.common.base.Predicates;
97 import com.google.common.collect.FluentIterable;
98 import com.google.common.collect.HashMultimap;
99 import com.google.common.collect.ImmutableSet;
100 import com.google.common.collect.Maps;
101 import com.google.common.collect.Multimap;
102 import com.google.common.collect.Multimaps;
103 import com.google.common.eventbus.EventBus;
104 import com.google.common.eventbus.Subscribe;
105 import com.google.inject.Inject;
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);
326 /** {@inheritDocs} */
328 public Collection<Sone> getSones() {
329 synchronized (sones) {
330 return ImmutableSet.copyOf(sones.values());
335 * Returns the Sone with the given ID, regardless whether it’s local or
339 * The ID of the Sone to get
340 * @return The Sone with the given ID, or {@code null} if there is no such
344 public Optional<Sone> getSone(String id) {
345 synchronized (sones) {
346 return Optional.fromNullable(sones.get(id));
350 /** {@inheritDocs} */
352 public Collection<Sone> getLocalSones() {
353 synchronized (sones) {
354 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
357 public boolean apply(Sone sone) {
358 return sone.isLocal();
365 * Returns the local Sone with the given ID, optionally creating a new Sone.
370 * {@code true} to create a new Sone if none exists, {@code false} to return
371 * null if none exists
372 * @return The Sone with the given ID, or {@code null}
374 public Sone getLocalSone(String id, boolean create) {
375 synchronized (sones) {
376 Sone sone = sones.get(id);
377 if ((sone == null) && create) {
378 sone = new SoneImpl(id, true);
381 if ((sone != null) && !sone.isLocal()) {
382 sone = new SoneImpl(id, true);
389 /** {@inheritDocs} */
391 public Collection<Sone> getRemoteSones() {
392 synchronized (sones) {
393 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
396 public boolean apply(Sone sone) {
397 return !sone.isLocal();
404 * Returns the remote Sone with the given ID.
407 * The ID of the remote Sone to get
409 * {@code true} to always create a Sone, {@code false} to return {@code null}
410 * if no Sone with the given ID exists
411 * @return The Sone with the given ID
413 public Sone getRemoteSone(String id, boolean create) {
414 synchronized (sones) {
415 Sone sone = sones.get(id);
416 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
417 sone = new SoneImpl(id, false);
425 * Returns whether the given Sone has been modified.
428 * The Sone to check for modifications
429 * @return {@code true} if a modification has been detected in the Sone, {@code
432 public boolean isModifiedSone(Sone sone) {
433 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
437 * Returns the time when the given was first followed by any local Sone.
440 * The Sone to get the time for
441 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
442 * followed, or {@link Long#MAX_VALUE}
444 public long getSoneFollowingTime(Sone sone) {
445 synchronized (soneFollowingTimes) {
446 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
451 * Returns whether the target Sone is trusted by the origin Sone.
457 * @return {@code true} if the target Sone is trusted by the origin Sone
459 public boolean isSoneTrusted(Sone origin, Sone target) {
460 checkNotNull(origin, "origin must not be null");
461 checkNotNull(target, "target must not be null");
462 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
463 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
467 * Returns a post builder.
469 * @return A new post builder
471 public PostBuilder postBuilder() {
472 return database.newPostBuilder();
477 public Optional<Post> getPost(String postId) {
478 return database.getPost(postId);
481 /** {@inheritDocs} */
483 public Collection<Post> getPosts(String soneId) {
484 return database.getPosts(soneId);
489 public Collection<Post> getDirectedPosts(final String recipientId) {
490 checkNotNull(recipientId, "recipient must not be null");
491 return database.getDirectedPosts(recipientId);
495 * Returns a post reply builder.
497 * @return A new post reply builder
499 public PostReplyBuilder postReplyBuilder() {
500 return database.newPostReplyBuilder();
505 public Optional<PostReply> getPostReply(String replyId) {
506 return database.getPostReply(replyId);
511 public List<PostReply> getReplies(final String postId) {
512 return database.getReplies(postId);
516 * Returns all Sones that have liked the given post.
519 * The post to get the liking Sones for
520 * @return The Sones that like the given post
522 public Set<Sone> getLikes(Post post) {
523 Set<Sone> sones = new HashSet<Sone>();
524 for (Sone sone : getSones()) {
525 if (sone.getLikedPostIds().contains(post.getId())) {
533 * Returns all Sones that have liked the given reply.
536 * The reply to get the liking Sones for
537 * @return The Sones that like the given reply
539 public Set<Sone> getLikes(PostReply reply) {
540 Set<Sone> sones = new HashSet<Sone>();
541 for (Sone sone : getSones()) {
542 if (sone.getLikedReplyIds().contains(reply.getId())) {
550 * Returns whether the given post is bookmarked.
554 * @return {@code true} if the given post is bookmarked, {@code false}
557 public boolean isBookmarked(Post post) {
558 return isPostBookmarked(post.getId());
562 * Returns whether the post with the given ID is bookmarked.
565 * The ID of the post to check
566 * @return {@code true} if the post with the given ID is bookmarked, {@code
569 public boolean isPostBookmarked(String id) {
570 synchronized (bookmarkedPosts) {
571 return bookmarkedPosts.contains(id);
576 * Returns all currently known bookmarked posts.
578 * @return All bookmarked posts
580 public Set<Post> getBookmarkedPosts() {
581 Set<Post> posts = new HashSet<Post>();
582 synchronized (bookmarkedPosts) {
583 for (String bookmarkedPostId : bookmarkedPosts) {
584 Optional<Post> post = getPost(bookmarkedPostId);
585 if (post.isPresent()) {
586 posts.add(post.get());
593 public Optional<Album> getAlbum(String albumId) {
594 return database.getAlbum(albumId);
597 public Optional<Image> getImage(String imageId) {
598 return database.getImage(imageId);
602 * Returns the temporary image with the given ID.
605 * The ID of the temporary image
606 * @return The temporary image, or {@code null} if there is no temporary image
609 public TemporaryImage getTemporaryImage(String imageId) {
610 synchronized (temporaryImages) {
611 return temporaryImages.get(imageId);
620 * Locks the given Sone. A locked Sone will not be inserted by {@link
621 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
626 public void lockSone(Sone sone) {
627 synchronized (lockedSones) {
628 if (lockedSones.add(sone)) {
629 eventBus.post(new SoneLockedEvent(sone));
635 * Unlocks the given Sone.
639 * @see #lockSone(Sone)
641 public void unlockSone(Sone sone) {
642 synchronized (lockedSones) {
643 if (lockedSones.remove(sone)) {
644 eventBus.post(new SoneUnlockedEvent(sone));
650 * Adds a local Sone from the given own identity.
653 * The own identity to create a Sone from
654 * @return The added (or already existing) Sone
656 public Sone addLocalSone(OwnIdentity ownIdentity) {
657 if (ownIdentity == null) {
658 logger.log(Level.WARNING, "Given OwnIdentity is null!");
661 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
662 synchronized (sones) {
665 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
666 } catch (MalformedURLException mue1) {
667 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
670 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
671 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
673 /* TODO - load posts ’n stuff */
674 sones.put(ownIdentity.getId(), sone);
675 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
676 soneInserters.put(sone, soneInserter);
677 sone.setStatus(SoneStatus.idle);
679 soneInserter.start();
685 * Creates a new Sone for the given own identity.
688 * The own identity to create a Sone for
689 * @return The created Sone
691 public Sone createSone(OwnIdentity ownIdentity) {
692 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
693 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
696 Sone sone = addLocalSone(ownIdentity);
697 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
698 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
699 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
700 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
701 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
702 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
704 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
705 touchConfiguration();
710 * Adds the Sone of the given identity.
713 * The identity whose Sone to add
714 * @return The added or already existing Sone
716 public Sone addRemoteSone(Identity identity) {
717 if (identity == null) {
718 logger.log(Level.WARNING, "Given Identity is null!");
721 synchronized (sones) {
722 final Sone sone = getRemoteSone(identity.getId(), true);
723 if (sone.isLocal()) {
726 sone.setIdentity(identity);
727 boolean newSone = sone.getRequestUri() == null;
728 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
729 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
731 synchronized (knownSones) {
732 newSone = !knownSones.contains(sone.getId());
734 sone.setKnown(!newSone);
736 eventBus.post(new NewSoneFoundEvent(sone));
737 for (Sone localSone : getLocalSones()) {
738 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
739 followSone(localSone, sone.getId());
744 soneDownloader.addSone(sone);
745 soneDownloaders.execute(new Runnable() {
748 @SuppressWarnings("synthetic-access")
750 soneDownloader.fetchSone(sone, sone.getRequestUri());
759 * Lets the given local Sone follow the Sone with the given ID.
762 * The local Sone that should follow another Sone
764 * The ID of the Sone to follow
766 public void followSone(Sone sone, String soneId) {
767 checkNotNull(sone, "sone must not be null");
768 checkNotNull(soneId, "soneId must not be null");
769 sone.addFriend(soneId);
770 synchronized (soneFollowingTimes) {
771 if (!soneFollowingTimes.containsKey(soneId)) {
772 long now = System.currentTimeMillis();
773 soneFollowingTimes.put(soneId, now);
774 Optional<Sone> followedSone = getSone(soneId);
775 if (!followedSone.isPresent()) {
778 for (Post post : followedSone.get().getPosts()) {
779 if (post.getTime() < now) {
783 for (PostReply reply : followedSone.get().getReplies()) {
784 if (reply.getTime() < now) {
785 markReplyKnown(reply);
790 touchConfiguration();
794 * Lets the given local Sone unfollow the Sone with the given ID.
797 * The local Sone that should unfollow another Sone
799 * The ID of the Sone being unfollowed
801 public void unfollowSone(Sone sone, String soneId) {
802 checkNotNull(sone, "sone must not be null");
803 checkNotNull(soneId, "soneId must not be null");
804 sone.removeFriend(soneId);
805 boolean unfollowedSoneStillFollowed = false;
806 for (Sone localSone : getLocalSones()) {
807 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
809 if (!unfollowedSoneStillFollowed) {
810 synchronized (soneFollowingTimes) {
811 soneFollowingTimes.remove(soneId);
814 touchConfiguration();
818 * Sets the trust value of the given origin Sone for the target Sone.
825 * The trust value (from {@code -100} to {@code 100})
827 public void setTrust(Sone origin, Sone target, int trustValue) {
828 checkNotNull(origin, "origin must not be null");
829 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
830 checkNotNull(target, "target must not be null");
831 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
832 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
836 * Removes any trust assignment for the given target Sone.
843 public void removeTrust(Sone origin, Sone target) {
844 checkNotNull(origin, "origin must not be null");
845 checkNotNull(target, "target must not be null");
846 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
847 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
851 * Assigns the configured positive trust value for the given target.
858 public void trustSone(Sone origin, Sone target) {
859 setTrust(origin, target, preferences.getPositiveTrust());
863 * Assigns the configured negative trust value for the given target.
870 public void distrustSone(Sone origin, Sone target) {
871 setTrust(origin, target, preferences.getNegativeTrust());
875 * Removes the trust assignment for the given target.
882 public void untrustSone(Sone origin, Sone target) {
883 removeTrust(origin, target);
887 * Updates the stored Sone with the given Sone.
892 public void updateSone(Sone sone) {
893 updateSone(sone, false);
897 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
898 * {@code true}, an older Sone than the current Sone can be given to restore an
903 * @param soneRescueMode
904 * {@code true} if the stored Sone should be updated regardless of the age of
907 public void updateSone(Sone sone, boolean soneRescueMode) {
908 Optional<Sone> storedSone = getSone(sone.getId());
909 if (storedSone.isPresent()) {
910 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
911 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
914 /* find removed posts. */
915 Collection<Post> existingPosts = database.getPosts(sone.getId());
916 for (Post oldPost : existingPosts) {
917 if (!sone.getPosts().contains(oldPost)) {
918 eventBus.post(new PostRemovedEvent(oldPost));
921 /* find new posts. */
922 for (Post newPost : sone.getPosts()) {
923 if (existingPosts.contains(newPost)) {
926 if (newPost.getTime() < getSoneFollowingTime(sone)) {
927 newPost.setKnown(true);
928 } else if (!newPost.isKnown()) {
929 eventBus.post(new NewPostFoundEvent(newPost));
933 database.storePosts(sone, sone.getPosts());
934 if (!soneRescueMode) {
935 for (PostReply reply : storedSone.get().getReplies()) {
936 if (!sone.getReplies().contains(reply)) {
937 eventBus.post(new PostReplyRemovedEvent(reply));
941 Set<PostReply> storedReplies = storedSone.get().getReplies();
942 for (PostReply reply : sone.getReplies()) {
943 if (storedReplies.contains(reply)) {
946 if (reply.getTime() < getSoneFollowingTime(sone)) {
947 reply.setKnown(true);
948 } else if (!reply.isKnown()) {
949 eventBus.post(new NewPostReplyFoundEvent(reply));
952 database.storePostReplies(sone, sone.getReplies());
953 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
954 database.removeAlbum(album);
955 for (Image image : album.getImages()) {
956 database.removeImage(image);
959 for (Album album : sone.getRootAlbum().getAlbums()) {
960 database.storeAlbum(album);
961 for (Image image : album.getImages()) {
962 database.storeImage(image);
965 synchronized (sones) {
966 sone.setOptions(storedSone.get().getOptions());
967 sone.setKnown(storedSone.get().isKnown());
968 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
969 if (sone.isLocal()) {
970 soneInserters.get(storedSone.get()).setSone(sone);
971 touchConfiguration();
973 sones.put(sone.getId(), sone);
979 * Deletes the given Sone. This will remove the Sone from the {@link
980 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
981 * context from its identity.
986 public void deleteSone(Sone sone) {
987 if (!(sone.getIdentity() instanceof OwnIdentity)) {
988 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
991 synchronized (sones) {
992 if (!getLocalSones().contains(sone)) {
993 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
996 sones.remove(sone.getId());
997 SoneInserter soneInserter = soneInserters.remove(sone);
1000 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1001 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1003 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1004 } catch (ConfigurationException ce1) {
1005 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1010 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1011 * known} before, a {@link MarkSoneKnownEvent} is fired.
1014 * The Sone to mark as known
1016 public void markSoneKnown(Sone sone) {
1017 if (!sone.isKnown()) {
1018 sone.setKnown(true);
1019 synchronized (knownSones) {
1020 knownSones.add(sone.getId());
1022 eventBus.post(new MarkSoneKnownEvent(sone));
1023 touchConfiguration();
1028 * Loads and updates the given Sone from the configuration. If any error is
1029 * encountered, loading is aborted and the given Sone is not changed.
1032 * The Sone to load and update
1034 public void loadSone(Sone sone) {
1035 if (!sone.isLocal()) {
1036 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1039 logger.info(String.format("Loading local Sone: %s", sone));
1041 /* initialize options. */
1042 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1043 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1044 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1045 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1046 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1047 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1050 String sonePrefix = "Sone/" + sone.getId();
1051 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1052 if (soneTime == null) {
1053 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1056 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1059 Profile profile = new Profile(sone);
1060 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1061 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1062 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1063 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1064 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1065 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1067 /* load profile fields. */
1069 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1070 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1071 if (fieldName == null) {
1074 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1075 profile.addField(fieldName).setValue(fieldValue);
1079 Set<Post> posts = new HashSet<Post>();
1081 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1082 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1083 if (postId == null) {
1086 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1087 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1088 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1089 if ((postTime == 0) || (postText == null)) {
1090 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1093 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1094 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1095 postBuilder.to(postRecipientId);
1097 posts.add(postBuilder.build());
1101 Set<PostReply> replies = new HashSet<PostReply>();
1103 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1104 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1105 if (replyId == null) {
1108 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1109 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1110 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1111 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1112 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1115 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1116 replies.add(postReplyBuilder.build());
1119 /* load post likes. */
1120 Set<String> likedPostIds = new HashSet<String>();
1122 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1123 if (likedPostId == null) {
1126 likedPostIds.add(likedPostId);
1129 /* load reply likes. */
1130 Set<String> likedReplyIds = new HashSet<String>();
1132 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1133 if (likedReplyId == null) {
1136 likedReplyIds.add(likedReplyId);
1140 Set<String> friends = new HashSet<String>();
1142 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1143 if (friendId == null) {
1146 friends.add(friendId);
1150 Map<String, Album> albums = Maps.newHashMap();
1151 int albumCounter = 0;
1153 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1154 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1155 if (albumId == null) {
1158 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1159 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1160 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1161 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1162 if ((albumTitle == null) || (albumDescription == null)) {
1163 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1166 Album parentAlbum = sone.getRootAlbum();
1167 if (albumParentId != null) {
1168 parentAlbum = albums.get(albumParentId);
1170 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1171 albums.put(album.getId(), album);
1175 int imageCounter = 0;
1177 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1178 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1179 if (imageId == null) {
1182 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1183 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1184 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1185 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1186 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1187 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1188 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1189 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1190 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1193 Album album = albums.get(albumId);
1194 if (album == null) {
1195 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1198 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1202 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1203 if (avatarId != null) {
1204 profile.setAvatar(getImage(avatarId).orNull());
1208 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1209 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1210 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1211 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1212 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1213 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1215 /* if we’re still here, Sone was loaded successfully. */
1216 synchronized (sone) {
1217 sone.setTime(soneTime);
1218 sone.setProfile(profile);
1219 sone.setPosts(posts);
1220 sone.setReplies(replies);
1221 sone.setLikePostIds(likedPostIds);
1222 sone.setLikeReplyIds(likedReplyIds);
1223 for (String friendId : friends) {
1224 followSone(sone, friendId);
1226 for (Album album : sone.getRootAlbum().getAlbums()) {
1227 sone.getRootAlbum().removeAlbum(album);
1229 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1231 synchronized (knownSones) {
1232 for (String friend : friends) {
1233 knownSones.add(friend);
1236 database.storePosts(sone, posts);
1237 for (Post post : posts) {
1238 post.setKnown(true);
1240 database.storePostReplies(sone, replies);
1241 for (PostReply reply : replies) {
1242 reply.setKnown(true);
1245 logger.info(String.format("Sone loaded successfully: %s", sone));
1249 * Creates a new post.
1252 * The Sone that creates the post
1254 * The text of the post
1255 * @return The created post
1257 public Post createPost(Sone sone, String text) {
1258 return createPost(sone, System.currentTimeMillis(), text);
1262 * Creates a new post.
1265 * The Sone that creates the post
1267 * The time of the post
1269 * The text of the post
1270 * @return The created post
1272 public Post createPost(Sone sone, long time, String text) {
1273 return createPost(sone, null, time, text);
1277 * Creates a new post.
1280 * The Sone that creates the post
1282 * The recipient Sone, or {@code null} if this post does not have a
1285 * The text of the post
1286 * @return The created post
1288 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1289 return createPost(sone, recipient, System.currentTimeMillis(), text);
1293 * Creates a new post.
1296 * The Sone that creates the post
1298 * The recipient Sone, or {@code null} if this post does not have a
1301 * The time of the post
1303 * The text of the post
1304 * @return The created post
1306 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1307 checkNotNull(text, "text must not be null");
1308 checkArgument(text.trim().length() > 0, "text must not be empty");
1309 if (!sone.isLocal()) {
1310 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1313 PostBuilder postBuilder = database.newPostBuilder();
1314 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1315 if (recipient.isPresent()) {
1316 postBuilder.to(recipient.get().getId());
1318 final Post post = postBuilder.build();
1319 database.storePost(post);
1320 eventBus.post(new NewPostFoundEvent(post));
1322 touchConfiguration();
1323 localElementTicker.schedule(new Runnable() {
1330 markPostKnown(post);
1332 }, 10, TimeUnit.SECONDS);
1337 * Deletes the given post.
1340 * The post to delete
1342 public void deletePost(Post post) {
1343 if (!post.getSone().isLocal()) {
1344 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1347 database.removePost(post);
1348 eventBus.post(new PostRemovedEvent(post));
1349 markPostKnown(post);
1350 touchConfiguration();
1354 * Marks the given post as known, if it is currently not a known post
1355 * (according to {@link Post#isKnown()}).
1358 * The post to mark as known
1360 public void markPostKnown(Post post) {
1361 post.setKnown(true);
1362 eventBus.post(new MarkPostKnownEvent(post));
1363 touchConfiguration();
1364 for (PostReply reply : getReplies(post.getId())) {
1365 markReplyKnown(reply);
1370 * Bookmarks the given post.
1373 * The post to bookmark
1375 public void bookmark(Post post) {
1376 bookmarkPost(post.getId());
1380 * Bookmarks the post with the given ID.
1383 * The ID of the post to bookmark
1385 public void bookmarkPost(String id) {
1386 synchronized (bookmarkedPosts) {
1387 bookmarkedPosts.add(id);
1392 * Removes the given post from the bookmarks.
1395 * The post to unbookmark
1397 public void unbookmark(Post post) {
1398 unbookmarkPost(post.getId());
1402 * Removes the post with the given ID from the bookmarks.
1405 * The ID of the post to unbookmark
1407 public void unbookmarkPost(String id) {
1408 synchronized (bookmarkedPosts) {
1409 bookmarkedPosts.remove(id);
1414 * Creates a new reply.
1417 * The Sone that creates the reply
1419 * The post that this reply refers to
1421 * The text of the reply
1422 * @return The created reply
1424 public PostReply createReply(Sone sone, Post post, String text) {
1425 checkNotNull(text, "text must not be null");
1426 checkArgument(text.trim().length() > 0, "text must not be empty");
1427 if (!sone.isLocal()) {
1428 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1431 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1432 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1433 final PostReply reply = postReplyBuilder.build();
1434 database.storePostReply(reply);
1435 eventBus.post(new NewPostReplyFoundEvent(reply));
1436 sone.addReply(reply);
1437 touchConfiguration();
1438 localElementTicker.schedule(new Runnable() {
1445 markReplyKnown(reply);
1447 }, 10, TimeUnit.SECONDS);
1452 * Deletes the given reply.
1455 * The reply to delete
1457 public void deleteReply(PostReply reply) {
1458 Sone sone = reply.getSone();
1459 if (!sone.isLocal()) {
1460 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1463 database.removePostReply(reply);
1464 markReplyKnown(reply);
1465 sone.removeReply(reply);
1466 touchConfiguration();
1470 * Marks the given reply as known, if it is currently not a known reply
1471 * (according to {@link Reply#isKnown()}).
1474 * The reply to mark as known
1476 public void markReplyKnown(PostReply reply) {
1477 boolean previouslyKnown = reply.isKnown();
1478 reply.setKnown(true);
1479 eventBus.post(new MarkPostReplyKnownEvent(reply));
1480 if (!previouslyKnown) {
1481 touchConfiguration();
1486 * Deletes the given album. The owner of the album has to be a local Sone, and
1487 * the album has to be {@link Album#isEmpty() empty} to be deleted.
1490 * The album to remove
1492 public void deleteAlbum(Album album) {
1493 checkNotNull(album, "album must not be null");
1494 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1495 if (!album.isEmpty()) {
1498 album.getParent().removeAlbum(album);
1499 database.removeAlbum(album);
1500 touchConfiguration();
1504 * Creates a new image.
1507 * The Sone creating the image
1509 * The album the image will be inserted into
1510 * @param temporaryImage
1511 * The temporary image to create the image from
1512 * @return The newly created image
1514 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1515 checkNotNull(sone, "sone must not be null");
1516 checkNotNull(album, "album must not be null");
1517 checkNotNull(temporaryImage, "temporaryImage must not be null");
1518 checkArgument(sone.isLocal(), "sone must be a local Sone");
1519 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1520 Image image = album.newImageBuilder().withId(temporaryImage.getId()).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1521 imageInserter.insertImage(temporaryImage, image);
1526 * Deletes the given image. This method will also delete a matching temporary
1530 * The image to delete
1531 * @see #deleteTemporaryImage(TemporaryImage)
1533 public void deleteImage(Image image) {
1534 checkNotNull(image, "image must not be null");
1535 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1536 deleteTemporaryImage(image.getId());
1538 touchConfiguration();
1542 * Creates a new temporary image.
1545 * The MIME type of the temporary image
1547 * The encoded data of the image
1548 * @return The temporary image
1550 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1551 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1552 synchronized (temporaryImages) {
1553 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1555 return temporaryImage;
1559 * Deletes the given temporary image.
1561 * @param temporaryImage
1562 * The temporary image to delete
1564 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1565 checkNotNull(temporaryImage, "temporaryImage must not be null");
1566 deleteTemporaryImage(temporaryImage.getId());
1570 * Deletes the temporary image with the given ID.
1573 * The ID of the temporary image to delete
1575 public void deleteTemporaryImage(String imageId) {
1576 checkNotNull(imageId, "imageId must not be null");
1577 synchronized (temporaryImages) {
1578 temporaryImages.remove(imageId);
1580 Optional<Image> image = getImage(imageId);
1581 if (image.isPresent()) {
1582 imageInserter.cancelImageInsert(image.get());
1587 * Notifies the core that the configuration, either of the core or of a single
1588 * local Sone, has changed, and that the configuration should be saved.
1590 public void touchConfiguration() {
1591 lastConfigurationUpdate = System.currentTimeMillis();
1598 /** Starts the core. */
1600 public void serviceStart() {
1601 loadConfiguration();
1602 updateChecker.start();
1603 identityManager.start();
1604 webOfTrustUpdater.init();
1605 webOfTrustUpdater.start();
1609 /** {@inheritDoc} */
1611 public void serviceRun() {
1612 long lastSaved = System.currentTimeMillis();
1613 while (!shouldStop()) {
1615 long now = System.currentTimeMillis();
1616 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1617 for (Sone localSone : getLocalSones()) {
1618 saveSone(localSone);
1620 saveConfiguration();
1626 /** Stops the core. */
1628 public void serviceStop() {
1629 localElementTicker.shutdownNow();
1630 synchronized (sones) {
1631 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1632 soneInserter.getValue().stop();
1633 saveSone(soneInserter.getKey());
1636 saveConfiguration();
1638 webOfTrustUpdater.stop();
1639 updateChecker.stop();
1640 soneDownloader.stop();
1641 soneDownloaders.shutdown();
1642 identityManager.stop();
1650 * Saves the given Sone. This will persist all local settings for the given
1651 * Sone, such as the friends list and similar, private options.
1656 private synchronized void saveSone(Sone sone) {
1657 if (!sone.isLocal()) {
1658 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1661 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1662 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1666 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1668 /* save Sone into configuration. */
1669 String sonePrefix = "Sone/" + sone.getId();
1670 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1671 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1674 Profile profile = sone.getProfile();
1675 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1676 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1677 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1678 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1679 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1680 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1681 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1683 /* save profile fields. */
1684 int fieldCounter = 0;
1685 for (Field profileField : profile.getFields()) {
1686 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1687 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1688 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1690 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1693 int postCounter = 0;
1694 for (Post post : sone.getPosts()) {
1695 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1696 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1697 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1698 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1699 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1701 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1704 int replyCounter = 0;
1705 for (PostReply reply : sone.getReplies()) {
1706 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1707 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1708 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1709 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1710 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1712 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1714 /* save post likes. */
1715 int postLikeCounter = 0;
1716 for (String postId : sone.getLikedPostIds()) {
1717 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1719 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1721 /* save reply likes. */
1722 int replyLikeCounter = 0;
1723 for (String replyId : sone.getLikedReplyIds()) {
1724 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1726 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1729 int friendCounter = 0;
1730 for (String friendId : sone.getFriends()) {
1731 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1733 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1735 /* save albums. first, collect in a flat structure, top-level first. */
1736 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1738 int albumCounter = 0;
1739 for (Album album : albums) {
1740 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1741 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1742 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1743 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1744 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1745 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1747 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1750 int imageCounter = 0;
1751 for (Album album : albums) {
1752 for (Image image : album.getImages()) {
1753 if (!image.isInserted()) {
1756 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1757 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1758 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1759 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1760 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1761 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1762 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1763 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1764 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1767 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1770 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1771 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1772 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1773 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1774 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1775 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1777 configuration.save();
1779 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1781 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1782 } catch (ConfigurationException ce1) {
1783 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1787 /** Saves the current options. */
1788 private void saveConfiguration() {
1789 synchronized (configuration) {
1790 if (storingConfiguration) {
1791 logger.log(Level.FINE, "Already storing configuration…");
1794 storingConfiguration = true;
1797 /* store the options first. */
1799 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1800 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1801 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1802 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1803 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1804 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1805 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1806 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1807 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1808 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1809 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1810 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1812 /* save known Sones. */
1813 int soneCounter = 0;
1814 synchronized (knownSones) {
1815 for (String knownSoneId : knownSones) {
1816 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1818 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1821 /* save Sone following times. */
1823 synchronized (soneFollowingTimes) {
1824 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1825 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1826 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1829 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1832 /* save known posts. */
1835 /* save bookmarked posts. */
1836 int bookmarkedPostCounter = 0;
1837 synchronized (bookmarkedPosts) {
1838 for (String bookmarkedPostId : bookmarkedPosts) {
1839 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1842 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1845 configuration.save();
1847 } catch (ConfigurationException ce1) {
1848 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1849 } catch (DatabaseException de1) {
1850 logger.log(Level.SEVERE, "Could not save database!", de1);
1852 synchronized (configuration) {
1853 storingConfiguration = false;
1858 /** Loads the configuration. */
1859 private void loadConfiguration() {
1860 /* create options. */
1861 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1864 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1865 SoneInserter.setInsertionDelay(newValue);
1869 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1870 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1871 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1872 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1873 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1874 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1875 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1876 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1877 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1880 @SuppressWarnings("synthetic-access")
1881 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1882 fcpInterface.setActive(newValue);
1885 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1888 @SuppressWarnings("synthetic-access")
1889 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1890 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1895 loadConfigurationValue("InsertionDelay");
1896 loadConfigurationValue("PostsPerPage");
1897 loadConfigurationValue("ImagesPerPage");
1898 loadConfigurationValue("CharactersPerPost");
1899 loadConfigurationValue("PostCutOffLength");
1900 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1901 loadConfigurationValue("PositiveTrust");
1902 loadConfigurationValue("NegativeTrust");
1903 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1904 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1905 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1907 /* load known Sones. */
1908 int soneCounter = 0;
1910 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1911 if (knownSoneId == null) {
1914 synchronized (knownSones) {
1915 knownSones.add(knownSoneId);
1919 /* load Sone following times. */
1922 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1923 if (soneId == null) {
1926 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1927 synchronized (soneFollowingTimes) {
1928 soneFollowingTimes.put(soneId, time);
1933 /* load bookmarked posts. */
1934 int bookmarkedPostCounter = 0;
1936 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1937 if (bookmarkedPostId == null) {
1940 synchronized (bookmarkedPosts) {
1941 bookmarkedPosts.add(bookmarkedPostId);
1948 * Loads an {@link Integer} configuration value for the option with the given
1949 * name, logging validation failures.
1952 * The name of the option to load
1954 private void loadConfigurationValue(String optionName) {
1956 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1957 } catch (IllegalArgumentException iae1) {
1958 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1963 * Notifies the core that a new {@link OwnIdentity} was added.
1965 * @param ownIdentityAddedEvent
1969 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1970 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1971 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1972 if (ownIdentity.hasContext("Sone")) {
1973 addLocalSone(ownIdentity);
1978 * Notifies the core that an {@link OwnIdentity} was removed.
1980 * @param ownIdentityRemovedEvent
1984 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1985 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1986 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1987 trustedIdentities.removeAll(ownIdentity);
1991 * Notifies the core that a new {@link Identity} was added.
1993 * @param identityAddedEvent
1997 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1998 Identity identity = identityAddedEvent.identity();
1999 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2000 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2001 addRemoteSone(identity);
2005 * Notifies the core that an {@link Identity} was updated.
2007 * @param identityUpdatedEvent
2011 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2012 final Identity identity = identityUpdatedEvent.identity();
2013 soneDownloaders.execute(new Runnable() {
2016 @SuppressWarnings("synthetic-access")
2018 Sone sone = getRemoteSone(identity.getId(), false);
2019 if (sone.isLocal()) {
2022 sone.setIdentity(identity);
2023 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2024 soneDownloader.addSone(sone);
2025 soneDownloader.fetchSone(sone);
2031 * Notifies the core that an {@link Identity} was removed.
2033 * @param identityRemovedEvent
2037 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2038 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2039 Identity identity = identityRemovedEvent.identity();
2040 trustedIdentities.remove(ownIdentity, identity);
2041 boolean foundIdentity = false;
2042 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2043 if (trustedIdentity.getKey().equals(ownIdentity)) {
2046 if (trustedIdentity.getValue().contains(identity)) {
2047 foundIdentity = true;
2050 if (foundIdentity) {
2051 /* some local identity still trusts this identity, don’t remove. */
2054 Optional<Sone> sone = getSone(identity.getId());
2055 if (!sone.isPresent()) {
2056 /* TODO - we don’t have the Sone anymore. should this happen? */
2059 database.removePosts(sone.get());
2060 for (Post post : sone.get().getPosts()) {
2061 eventBus.post(new PostRemovedEvent(post));
2063 database.removePostReplies(sone.get());
2064 for (PostReply reply : sone.get().getReplies()) {
2065 eventBus.post(new PostReplyRemovedEvent(reply));
2067 synchronized (sones) {
2068 sones.remove(identity.getId());
2070 eventBus.post(new SoneRemovedEvent(sone.get()));
2074 * Deletes the temporary image.
2076 * @param imageInsertFinishedEvent
2080 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2081 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2082 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2083 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2084 touchConfiguration();