2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.of;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.collect.FluentIterable.from;
25 import static net.pterodactylus.sone.data.Identified.GET_ID;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import java.net.MalformedURLException;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.sone.core.Options.DefaultOption;
44 import net.pterodactylus.sone.core.Options.Option;
45 import net.pterodactylus.sone.core.Options.OptionWatcher;
46 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
47 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
49 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
50 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
51 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
52 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
53 import net.pterodactylus.sone.core.event.PostRemovedEvent;
54 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneLockedEvent;
56 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
58 import net.pterodactylus.sone.data.Album;
59 import net.pterodactylus.sone.data.Client;
60 import net.pterodactylus.sone.data.Image;
61 import net.pterodactylus.sone.data.Post;
62 import net.pterodactylus.sone.data.PostReply;
63 import net.pterodactylus.sone.data.Profile;
64 import net.pterodactylus.sone.data.Profile.Field;
65 import net.pterodactylus.sone.data.Reply;
66 import net.pterodactylus.sone.data.Sone;
67 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
68 import net.pterodactylus.sone.data.Sone.SoneStatus;
69 import net.pterodactylus.sone.data.TemporaryImage;
70 import net.pterodactylus.sone.database.Database;
71 import net.pterodactylus.sone.database.DatabaseException;
72 import net.pterodactylus.sone.database.PostBuilder;
73 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
74 import net.pterodactylus.sone.database.PostProvider;
75 import net.pterodactylus.sone.database.PostReplyBuilder;
76 import net.pterodactylus.sone.database.PostReplyProvider;
77 import net.pterodactylus.sone.database.SoneProvider;
78 import net.pterodactylus.sone.fcp.FcpInterface;
79 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
80 import net.pterodactylus.sone.freenet.wot.Identity;
81 import net.pterodactylus.sone.freenet.wot.IdentityManager;
82 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
88 import net.pterodactylus.sone.main.SonePlugin;
89 import net.pterodactylus.sone.utils.IntegerRangePredicate;
90 import net.pterodactylus.util.config.Configuration;
91 import net.pterodactylus.util.config.ConfigurationException;
92 import net.pterodactylus.util.logging.Logging;
93 import net.pterodactylus.util.number.Numbers;
94 import net.pterodactylus.util.service.AbstractService;
95 import net.pterodactylus.util.thread.NamedThreadFactory;
97 import freenet.keys.FreenetURI;
99 import com.google.common.base.Optional;
100 import com.google.common.base.Predicate;
101 import com.google.common.base.Predicates;
102 import com.google.common.collect.HashMultimap;
103 import com.google.common.collect.ImmutableSet;
104 import com.google.common.collect.Maps;
105 import com.google.common.collect.Multimap;
106 import com.google.common.collect.Multimaps;
107 import com.google.common.eventbus.EventBus;
108 import com.google.common.eventbus.Subscribe;
109 import com.google.inject.Inject;
114 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
116 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
119 private static final Logger logger = Logging.getLogger(Core.class);
121 /** The start time. */
122 private final long startupTime = System.currentTimeMillis();
125 private final Options options = new Options();
127 /** The preferences. */
128 private final Preferences preferences = new Preferences(options);
130 /** The event bus. */
131 private final EventBus eventBus;
133 /** The configuration. */
134 private Configuration configuration;
136 /** Whether we’re currently saving the configuration. */
137 private boolean storingConfiguration = false;
139 /** The identity manager. */
140 private final IdentityManager identityManager;
142 /** Interface to freenet. */
143 private final FreenetInterface freenetInterface;
145 /** The Sone downloader. */
146 private final SoneDownloader soneDownloader;
148 /** The image inserter. */
149 private final ImageInserter imageInserter;
151 /** Sone downloader thread-pool. */
152 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154 /** The update checker. */
155 private final UpdateChecker updateChecker;
157 /** The trust updater. */
158 private final WebOfTrustUpdater webOfTrustUpdater;
160 /** The FCP interface. */
161 private volatile FcpInterface fcpInterface;
163 /** The times Sones were followed. */
164 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
166 /** Locked local Sones. */
167 /* synchronize on itself. */
168 private final Set<Sone> lockedSones = new HashSet<Sone>();
170 /** Sone inserters. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
174 /** Sone rescuers. */
175 /* synchronize access on this on sones. */
176 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
179 /* synchronize access on this on itself. */
180 private final Map<String, Sone> sones = new HashMap<String, Sone>();
182 /** All known Sones. */
183 private final Set<String> knownSones = new HashSet<String>();
185 /** The post database. */
186 private final Database database;
188 /** All bookmarked posts. */
189 /* synchronize access on itself. */
190 private final Set<String> bookmarkedPosts = new HashSet<String>();
192 /** Trusted identities, sorted by own identities. */
193 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
195 /** All temporary images. */
196 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
198 /** Ticker for threads that mark own elements as known. */
199 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
201 /** The time the configuration was last touched. */
202 private volatile long lastConfigurationUpdate;
205 * Creates a new core.
207 * @param configuration
208 * The configuration of the core
209 * @param freenetInterface
210 * The freenet interface
211 * @param identityManager
212 * The identity manager
213 * @param webOfTrustUpdater
214 * The WebOfTrust updater
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloader(this, freenetInterface);
227 this.imageInserter = new ImageInserter(freenetInterface);
228 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
231 this.database = database;
239 * Returns the time Sone was started.
241 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
243 public long getStartupTime() {
248 * Sets the configuration to use. This will automatically save the current
249 * configuration to the given configuration.
251 * @param configuration
252 * The new configuration to use
254 public void setConfiguration(Configuration configuration) {
255 this.configuration = configuration;
256 touchConfiguration();
260 * Returns the options used by the core.
262 * @return The options of the core
264 public Preferences getPreferences() {
269 * Returns the identity manager used by the core.
271 * @return The identity manager
273 public IdentityManager getIdentityManager() {
274 return identityManager;
278 * Returns the update checker.
280 * @return The update checker
282 public UpdateChecker getUpdateChecker() {
283 return updateChecker;
287 * Sets the FCP interface to use.
289 * @param fcpInterface
290 * The FCP interface to use
292 public void setFcpInterface(FcpInterface fcpInterface) {
293 this.fcpInterface = fcpInterface;
296 public Database getDatabase() {
301 * Returns the Sone rescuer for the given local Sone.
304 * The local Sone to get the rescuer for
305 * @return The Sone rescuer for the given Sone
307 public SoneRescuer getSoneRescuer(Sone sone) {
308 checkNotNull(sone, "sone must not be null");
309 checkArgument(sone.isLocal(), "sone must be local");
310 synchronized (sones) {
311 SoneRescuer soneRescuer = soneRescuers.get(sone);
312 if (soneRescuer == null) {
313 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
314 soneRescuers.put(sone, soneRescuer);
322 * Returns whether the given Sone is currently locked.
326 * @return {@code true} if the Sone is locked, {@code false} if it is not
328 public boolean isLocked(Sone sone) {
329 synchronized (lockedSones) {
330 return lockedSones.contains(sone);
334 /** {@inheritDocs} */
336 public Collection<Sone> getSones() {
337 synchronized (sones) {
338 return ImmutableSet.copyOf(sones.values());
343 * Returns the Sone with the given ID, regardless whether it’s local or
347 * The ID of the Sone to get
348 * @return The Sone with the given ID, or {@code null} if there is no such
352 public Optional<Sone> getSone(String id) {
353 synchronized (sones) {
354 return Optional.fromNullable(sones.get(id));
358 /** {@inheritDocs} */
360 public Collection<Sone> getLocalSones() {
361 synchronized (sones) {
362 return from(sones.values()).filter(new Predicate<Sone>() {
365 public boolean apply(Sone sone) {
366 return sone.isLocal();
373 * Returns the local Sone with the given ID, optionally creating a new Sone.
377 * @return The Sone with the given ID, or {@code null}
379 public Optional<Sone> getLocalSone(String id) {
380 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
383 /** {@inheritDocs} */
385 public Collection<Sone> getRemoteSones() {
386 synchronized (sones) {
387 return from(sones.values()).filter(new Predicate<Sone>() {
390 public boolean apply(Sone sone) {
391 return !sone.isLocal();
398 * Returns the remote Sone with the given ID.
401 * The ID of the remote Sone to get
402 * @return The Sone with the given ID
404 public Optional<Sone> getRemoteSone(String id) {
405 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
409 * Returns whether the given Sone has been modified.
412 * The Sone to check for modifications
413 * @return {@code true} if a modification has been detected in the Sone, {@code
416 public boolean isModifiedSone(Sone sone) {
417 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
421 * Returns the time when the given was first followed by any local Sone.
424 * The Sone to get the time for
425 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
426 * followed, or {@link Long#MAX_VALUE}
428 public long getSoneFollowingTime(Sone sone) {
429 synchronized (soneFollowingTimes) {
430 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
435 * Returns whether the target Sone is trusted by the origin Sone.
441 * @return {@code true} if the target Sone is trusted by the origin Sone
443 public boolean isSoneTrusted(Sone origin, Sone target) {
444 checkNotNull(origin, "origin must not be null");
445 checkNotNull(target, "target must not be null");
446 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
447 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
452 public Optional<Post> getPost(String postId) {
453 return database.getPost(postId);
456 /** {@inheritDocs} */
458 public Collection<Post> getPosts(String soneId) {
459 return database.getPosts(soneId);
464 public Collection<Post> getDirectedPosts(final String recipientId) {
465 checkNotNull(recipientId, "recipient must not be null");
466 return database.getDirectedPosts(recipientId);
470 * Returns a post reply builder.
472 * @return A new post reply builder
474 public PostReplyBuilder postReplyBuilder() {
475 return database.newPostReplyBuilder();
480 public Optional<PostReply> getPostReply(String replyId) {
481 return database.getPostReply(replyId);
486 public List<PostReply> getReplies(final String postId) {
487 return database.getReplies(postId);
491 * Returns all Sones that have liked the given post.
494 * The post to get the liking Sones for
495 * @return The Sones that like the given post
497 public Set<Sone> getLikes(Post post) {
498 Set<Sone> sones = new HashSet<Sone>();
499 for (Sone sone : getSones()) {
500 if (sone.getLikedPostIds().contains(post.getId())) {
508 * Returns all Sones that have liked the given reply.
511 * The reply to get the liking Sones for
512 * @return The Sones that like the given reply
514 public Set<Sone> getLikes(PostReply reply) {
515 Set<Sone> sones = new HashSet<Sone>();
516 for (Sone sone : getSones()) {
517 if (sone.getLikedReplyIds().contains(reply.getId())) {
525 * Returns whether the given post is bookmarked.
529 * @return {@code true} if the given post is bookmarked, {@code false}
532 public boolean isBookmarked(Post post) {
533 return isPostBookmarked(post.getId());
537 * Returns whether the post with the given ID is bookmarked.
540 * The ID of the post to check
541 * @return {@code true} if the post with the given ID is bookmarked, {@code
544 public boolean isPostBookmarked(String id) {
545 synchronized (bookmarkedPosts) {
546 return bookmarkedPosts.contains(id);
551 * Returns all currently known bookmarked posts.
553 * @return All bookmarked posts
555 public Set<Post> getBookmarkedPosts() {
556 Set<Post> posts = new HashSet<Post>();
557 synchronized (bookmarkedPosts) {
558 for (String bookmarkedPostId : bookmarkedPosts) {
559 Optional<Post> post = getPost(bookmarkedPostId);
560 if (post.isPresent()) {
561 posts.add(post.get());
568 public Optional<Album> getAlbum(String albumId) {
569 return database.getAlbum(albumId);
572 public Optional<Image> getImage(String imageId) {
573 return database.getImage(imageId);
577 * Returns the temporary image with the given ID.
580 * The ID of the temporary image
581 * @return The temporary image, or {@code null} if there is no temporary image
584 public TemporaryImage getTemporaryImage(String imageId) {
585 synchronized (temporaryImages) {
586 return temporaryImages.get(imageId);
595 * Locks the given Sone. A locked Sone will not be inserted by {@link
596 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
601 public void lockSone(Sone sone) {
602 synchronized (lockedSones) {
603 if (lockedSones.add(sone)) {
604 eventBus.post(new SoneLockedEvent(sone));
610 * Unlocks the given Sone.
614 * @see #lockSone(Sone)
616 public void unlockSone(Sone sone) {
617 synchronized (lockedSones) {
618 if (lockedSones.remove(sone)) {
619 eventBus.post(new SoneUnlockedEvent(sone));
625 * Adds a local Sone from the given own identity.
628 * The own identity to create a Sone from
629 * @return The added (or already existing) Sone
631 public Sone addLocalSone(OwnIdentity ownIdentity) {
632 if (ownIdentity == null) {
633 logger.log(Level.WARNING, "Given OwnIdentity is null!");
636 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
637 synchronized (sones) {
640 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
641 } catch (MalformedURLException mue1) {
642 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
645 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
646 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
648 /* TODO - load posts ’n stuff */
649 sones.put(ownIdentity.getId(), sone);
650 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
651 soneInserters.put(sone, soneInserter);
652 sone.setStatus(SoneStatus.idle);
654 soneInserter.start();
660 * Creates a new Sone for the given own identity.
663 * The own identity to create a Sone for
664 * @return The created Sone
666 public Sone createSone(OwnIdentity ownIdentity) {
667 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
668 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
671 Sone sone = addLocalSone(ownIdentity);
672 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
673 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
674 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
675 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
676 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
677 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
679 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
680 touchConfiguration();
685 * Adds the Sone of the given identity.
688 * The identity whose Sone to add
689 * @return The added or already existing Sone
691 public Sone addRemoteSone(Identity identity) {
692 if (identity == null) {
693 logger.log(Level.WARNING, "Given Identity is null!");
696 synchronized (sones) {
697 final Sone sone = database.newSoneBuilder().by(identity).build();
698 if (sone.isLocal()) {
701 sone.setIdentity(identity);
702 boolean newSone = sone.getRequestUri() == null;
703 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
704 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
706 synchronized (knownSones) {
707 newSone = !knownSones.contains(sone.getId());
709 sone.setKnown(!newSone);
711 eventBus.post(new NewSoneFoundEvent(sone));
712 for (Sone localSone : getLocalSones()) {
713 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
714 followSone(localSone, sone.getId());
719 soneDownloader.addSone(sone);
720 soneDownloaders.execute(new Runnable() {
723 @SuppressWarnings("synthetic-access")
725 soneDownloader.fetchSone(sone, sone.getRequestUri());
734 * Lets the given local Sone follow the Sone with the given ID.
737 * The local Sone that should follow another Sone
739 * The ID of the Sone to follow
741 public void followSone(Sone sone, String soneId) {
742 checkNotNull(sone, "sone must not be null");
743 checkNotNull(soneId, "soneId must not be null");
744 sone.addFriend(soneId);
745 synchronized (soneFollowingTimes) {
746 if (!soneFollowingTimes.containsKey(soneId)) {
747 long now = System.currentTimeMillis();
748 soneFollowingTimes.put(soneId, now);
749 Optional<Sone> followedSone = getSone(soneId);
750 if (!followedSone.isPresent()) {
753 for (Post post : followedSone.get().getPosts()) {
754 if (post.getTime() < now) {
758 for (PostReply reply : followedSone.get().getReplies()) {
759 if (reply.getTime() < now) {
760 markReplyKnown(reply);
765 touchConfiguration();
769 * Lets the given local Sone unfollow the Sone with the given ID.
772 * The local Sone that should unfollow another Sone
774 * The ID of the Sone being unfollowed
776 public void unfollowSone(Sone sone, String soneId) {
777 checkNotNull(sone, "sone must not be null");
778 checkNotNull(soneId, "soneId must not be null");
779 sone.removeFriend(soneId);
780 boolean unfollowedSoneStillFollowed = false;
781 for (Sone localSone : getLocalSones()) {
782 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
784 if (!unfollowedSoneStillFollowed) {
785 synchronized (soneFollowingTimes) {
786 soneFollowingTimes.remove(soneId);
789 touchConfiguration();
793 * Sets the trust value of the given origin Sone for the target Sone.
800 * The trust value (from {@code -100} to {@code 100})
802 public void setTrust(Sone origin, Sone target, int trustValue) {
803 checkNotNull(origin, "origin must not be null");
804 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
805 checkNotNull(target, "target must not be null");
806 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
807 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
811 * Removes any trust assignment for the given target Sone.
818 public void removeTrust(Sone origin, Sone target) {
819 checkNotNull(origin, "origin must not be null");
820 checkNotNull(target, "target must not be null");
821 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
822 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
826 * Assigns the configured positive trust value for the given target.
833 public void trustSone(Sone origin, Sone target) {
834 setTrust(origin, target, preferences.getPositiveTrust());
838 * Assigns the configured negative trust value for the given target.
845 public void distrustSone(Sone origin, Sone target) {
846 setTrust(origin, target, preferences.getNegativeTrust());
850 * Removes the trust assignment for the given target.
857 public void untrustSone(Sone origin, Sone target) {
858 removeTrust(origin, target);
862 * Updates the stored Sone with the given Sone.
867 public void updateSone(Sone sone) {
868 updateSone(sone, false);
872 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
873 * {@code true}, an older Sone than the current Sone can be given to restore an
878 * @param soneRescueMode
879 * {@code true} if the stored Sone should be updated regardless of the age of
882 public void updateSone(Sone sone, boolean soneRescueMode) {
883 Optional<Sone> storedSone = getSone(sone.getId());
884 if (storedSone.isPresent()) {
885 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
886 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
889 /* find removed posts. */
890 Collection<Post> existingPosts = database.getPosts(sone.getId());
891 for (Post oldPost : existingPosts) {
892 if (!sone.getPosts().contains(oldPost)) {
893 eventBus.post(new PostRemovedEvent(oldPost));
896 /* find new posts. */
897 for (Post newPost : sone.getPosts()) {
898 if (existingPosts.contains(newPost)) {
901 if (newPost.getTime() < getSoneFollowingTime(sone)) {
902 newPost.setKnown(true);
903 } else if (!newPost.isKnown()) {
904 eventBus.post(new NewPostFoundEvent(newPost));
908 database.storePosts(sone, sone.getPosts());
909 if (!soneRescueMode) {
910 for (PostReply reply : storedSone.get().getReplies()) {
911 if (!sone.getReplies().contains(reply)) {
912 eventBus.post(new PostReplyRemovedEvent(reply));
916 Set<PostReply> storedReplies = storedSone.get().getReplies();
917 for (PostReply reply : sone.getReplies()) {
918 if (storedReplies.contains(reply)) {
921 if (reply.getTime() < getSoneFollowingTime(sone)) {
922 reply.setKnown(true);
923 } else if (!reply.isKnown()) {
924 eventBus.post(new NewPostReplyFoundEvent(reply));
927 database.storePostReplies(sone, sone.getReplies());
928 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
929 database.removeAlbum(album);
930 for (Image image : album.getImages()) {
931 database.removeImage(image);
934 for (Album album : sone.getRootAlbum().getAlbums()) {
935 database.storeAlbum(album);
936 for (Image image : album.getImages()) {
937 database.storeImage(image);
940 synchronized (sones) {
941 sone.setOptions(storedSone.get().getOptions());
942 sone.setKnown(storedSone.get().isKnown());
943 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
944 if (sone.isLocal()) {
945 soneInserters.get(storedSone.get()).setSone(sone);
946 touchConfiguration();
948 sones.put(sone.getId(), sone);
954 * Deletes the given Sone. This will remove the Sone from the {@link
955 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
956 * context from its identity.
961 public void deleteSone(Sone sone) {
962 if (!(sone.getIdentity() instanceof OwnIdentity)) {
963 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
966 synchronized (sones) {
967 if (!getLocalSones().contains(sone)) {
968 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
971 sones.remove(sone.getId());
972 SoneInserter soneInserter = soneInserters.remove(sone);
975 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
976 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
978 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
979 } catch (ConfigurationException ce1) {
980 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
985 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
986 * known} before, a {@link MarkSoneKnownEvent} is fired.
989 * The Sone to mark as known
991 public void markSoneKnown(Sone sone) {
992 if (!sone.isKnown()) {
994 synchronized (knownSones) {
995 knownSones.add(sone.getId());
997 eventBus.post(new MarkSoneKnownEvent(sone));
998 touchConfiguration();
1003 * Loads and updates the given Sone from the configuration. If any error is
1004 * encountered, loading is aborted and the given Sone is not changed.
1007 * The Sone to load and update
1009 public void loadSone(Sone sone) {
1010 if (!sone.isLocal()) {
1011 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1014 logger.info(String.format("Loading local Sone: %s", sone));
1016 /* initialize options. */
1017 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1018 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1019 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1020 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1021 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1022 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1025 String sonePrefix = "Sone/" + sone.getId();
1026 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1027 if (soneTime == null) {
1028 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1031 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1034 Profile profile = new Profile(sone);
1035 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1036 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1037 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1038 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1039 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1040 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1042 /* load profile fields. */
1044 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1045 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1046 if (fieldName == null) {
1049 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1050 profile.addField(fieldName).setValue(fieldValue);
1054 Set<Post> posts = new HashSet<Post>();
1056 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1057 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1058 if (postId == null) {
1061 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1062 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1063 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1064 if ((postTime == 0) || (postText == null)) {
1065 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1068 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
1069 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1070 postBuilder.to(of(postRecipientId));
1072 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1076 Set<PostReply> replies = new HashSet<PostReply>();
1078 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1079 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1080 if (replyId == null) {
1083 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1084 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1085 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1086 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1087 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1090 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1091 replies.add(postReplyBuilder.build());
1094 /* load post likes. */
1095 Set<String> likedPostIds = new HashSet<String>();
1097 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1098 if (likedPostId == null) {
1101 likedPostIds.add(likedPostId);
1104 /* load reply likes. */
1105 Set<String> likedReplyIds = new HashSet<String>();
1107 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1108 if (likedReplyId == null) {
1111 likedReplyIds.add(likedReplyId);
1115 Set<String> friends = new HashSet<String>();
1117 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1118 if (friendId == null) {
1121 friends.add(friendId);
1125 Map<String, Album> albums = Maps.newHashMap();
1126 int albumCounter = 0;
1128 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1129 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1130 if (albumId == null) {
1133 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1134 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1135 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1136 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1137 if ((albumTitle == null) || (albumDescription == null)) {
1138 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1141 Album parentAlbum = sone.getRootAlbum();
1142 if (albumParentId != null) {
1143 parentAlbum = albums.get(albumParentId);
1145 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1146 albums.put(album.getId(), album);
1150 int imageCounter = 0;
1152 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1153 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1154 if (imageId == null) {
1157 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1158 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1159 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1160 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1161 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1162 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1163 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1164 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1165 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1168 Album album = albums.get(albumId);
1169 if (album == null) {
1170 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1173 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1177 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1178 if (avatarId != null) {
1179 profile.setAvatar(getImage(avatarId).orNull());
1183 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1184 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1185 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1186 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1187 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1188 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1190 /* if we’re still here, Sone was loaded successfully. */
1191 synchronized (sone) {
1192 sone.setTime(soneTime);
1193 sone.setProfile(profile);
1194 sone.setPosts(posts);
1195 sone.setReplies(replies);
1196 sone.setLikePostIds(likedPostIds);
1197 sone.setLikeReplyIds(likedReplyIds);
1198 for (String friendId : friends) {
1199 followSone(sone, friendId);
1201 for (Album album : sone.getRootAlbum().getAlbums()) {
1204 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1206 synchronized (knownSones) {
1207 for (String friend : friends) {
1208 knownSones.add(friend);
1211 database.storePosts(sone, posts);
1212 for (Post post : posts) {
1213 post.setKnown(true);
1215 database.storePostReplies(sone, replies);
1216 for (PostReply reply : replies) {
1217 reply.setKnown(true);
1220 logger.info(String.format("Sone loaded successfully: %s", sone));
1224 * Deletes the given post.
1227 * The post to delete
1229 public void deletePost(Post post) {
1230 if (!post.getSone().isLocal()) {
1231 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1234 database.removePost(post);
1235 eventBus.post(new PostRemovedEvent(post));
1236 markPostKnown(post);
1237 touchConfiguration();
1241 * Marks the given post as known, if it is currently not a known post
1242 * (according to {@link Post#isKnown()}).
1245 * The post to mark as known
1247 public void markPostKnown(Post post) {
1248 post.setKnown(true);
1249 eventBus.post(new MarkPostKnownEvent(post));
1250 touchConfiguration();
1251 for (PostReply reply : getReplies(post.getId())) {
1252 markReplyKnown(reply);
1257 * Bookmarks the given post.
1260 * The post to bookmark
1262 public void bookmark(Post post) {
1263 bookmarkPost(post.getId());
1267 * Bookmarks the post with the given ID.
1270 * The ID of the post to bookmark
1272 public void bookmarkPost(String id) {
1273 synchronized (bookmarkedPosts) {
1274 bookmarkedPosts.add(id);
1279 * Removes the given post from the bookmarks.
1282 * The post to unbookmark
1284 public void unbookmark(Post post) {
1285 unbookmarkPost(post.getId());
1289 * Removes the post with the given ID from the bookmarks.
1292 * The ID of the post to unbookmark
1294 public void unbookmarkPost(String id) {
1295 synchronized (bookmarkedPosts) {
1296 bookmarkedPosts.remove(id);
1301 * Creates a new reply.
1304 * The Sone that creates the reply
1306 * The post that this reply refers to
1308 * The text of the reply
1309 * @return The created reply
1311 public PostReply createReply(Sone sone, Post post, String text) {
1312 checkNotNull(text, "text must not be null");
1313 checkArgument(text.trim().length() > 0, "text must not be empty");
1314 if (!sone.isLocal()) {
1315 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1318 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1319 postReplyBuilder.from(sone.getId()).to(post.getId()).withText(text.trim());
1320 final PostReply reply = postReplyBuilder.build();
1321 database.storePostReply(reply);
1322 eventBus.post(new NewPostReplyFoundEvent(reply));
1323 sone.addReply(reply);
1324 touchConfiguration();
1325 localElementTicker.schedule(new Runnable() {
1332 markReplyKnown(reply);
1334 }, 10, TimeUnit.SECONDS);
1339 * Deletes the given reply.
1342 * The reply to delete
1344 public void deleteReply(PostReply reply) {
1345 Sone sone = reply.getSone();
1346 if (!sone.isLocal()) {
1347 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1350 database.removePostReply(reply);
1351 markReplyKnown(reply);
1352 sone.removeReply(reply);
1353 touchConfiguration();
1357 * Marks the given reply as known, if it is currently not a known reply
1358 * (according to {@link Reply#isKnown()}).
1361 * The reply to mark as known
1363 public void markReplyKnown(PostReply reply) {
1364 boolean previouslyKnown = reply.isKnown();
1365 reply.setKnown(true);
1366 eventBus.post(new MarkPostReplyKnownEvent(reply));
1367 if (!previouslyKnown) {
1368 touchConfiguration();
1373 * Creates a new image.
1376 * The Sone creating the image
1378 * The album the image will be inserted into
1379 * @param temporaryImage
1380 * The temporary image to create the image from
1381 * @return The newly created image
1383 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1384 checkNotNull(sone, "sone must not be null");
1385 checkNotNull(album, "album must not be null");
1386 checkNotNull(temporaryImage, "temporaryImage must not be null");
1387 checkArgument(sone.isLocal(), "sone must be a local Sone");
1388 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1389 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1390 imageInserter.insertImage(temporaryImage, image);
1395 * Deletes the given image. This method will also delete a matching temporary
1399 * The image to delete
1400 * @see #deleteTemporaryImage(TemporaryImage)
1402 public void deleteImage(Image image) {
1403 checkNotNull(image, "image must not be null");
1404 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1405 deleteTemporaryImage(image.getId());
1407 touchConfiguration();
1411 * Creates a new temporary image.
1414 * The MIME type of the temporary image
1416 * The encoded data of the image
1417 * @return The temporary image
1419 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1420 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1421 synchronized (temporaryImages) {
1422 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1424 return temporaryImage;
1428 * Deletes the given temporary image.
1430 * @param temporaryImage
1431 * The temporary image to delete
1433 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1434 checkNotNull(temporaryImage, "temporaryImage must not be null");
1435 deleteTemporaryImage(temporaryImage.getId());
1439 * Deletes the temporary image with the given ID.
1442 * The ID of the temporary image to delete
1444 public void deleteTemporaryImage(String imageId) {
1445 checkNotNull(imageId, "imageId must not be null");
1446 synchronized (temporaryImages) {
1447 temporaryImages.remove(imageId);
1449 Optional<Image> image = getImage(imageId);
1450 if (image.isPresent()) {
1451 imageInserter.cancelImageInsert(image.get());
1456 * Notifies the core that the configuration, either of the core or of a single
1457 * local Sone, has changed, and that the configuration should be saved.
1459 public void touchConfiguration() {
1460 lastConfigurationUpdate = System.currentTimeMillis();
1467 /** Starts the core. */
1469 public void serviceStart() {
1470 loadConfiguration();
1471 updateChecker.start();
1472 identityManager.start();
1473 webOfTrustUpdater.init();
1474 webOfTrustUpdater.start();
1478 /** {@inheritDoc} */
1480 public void serviceRun() {
1481 long lastSaved = System.currentTimeMillis();
1482 while (!shouldStop()) {
1484 long now = System.currentTimeMillis();
1485 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1486 for (Sone localSone : getLocalSones()) {
1487 saveSone(localSone);
1489 saveConfiguration();
1495 /** Stops the core. */
1497 public void serviceStop() {
1498 localElementTicker.shutdownNow();
1499 synchronized (sones) {
1500 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1501 soneInserter.getValue().stop();
1502 saveSone(soneInserter.getKey());
1505 saveConfiguration();
1507 webOfTrustUpdater.stop();
1508 updateChecker.stop();
1509 soneDownloader.stop();
1510 soneDownloaders.shutdown();
1511 identityManager.stop();
1519 * Saves the given Sone. This will persist all local settings for the given
1520 * Sone, such as the friends list and similar, private options.
1525 private synchronized void saveSone(Sone sone) {
1526 if (!sone.isLocal()) {
1527 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1530 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1531 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1535 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1537 /* save Sone into configuration. */
1538 String sonePrefix = "Sone/" + sone.getId();
1539 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1540 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1543 Profile profile = sone.getProfile();
1544 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1545 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1546 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1547 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1548 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1549 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1550 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1552 /* save profile fields. */
1553 int fieldCounter = 0;
1554 for (Field profileField : profile.getFields()) {
1555 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1556 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1557 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1559 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1562 int postCounter = 0;
1563 for (Post post : sone.getPosts()) {
1564 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1565 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1566 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1567 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1568 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1570 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1573 int replyCounter = 0;
1574 for (PostReply reply : sone.getReplies()) {
1575 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1576 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1577 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1578 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1579 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1581 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1583 /* save post likes. */
1584 int postLikeCounter = 0;
1585 for (String postId : sone.getLikedPostIds()) {
1586 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1588 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1590 /* save reply likes. */
1591 int replyLikeCounter = 0;
1592 for (String replyId : sone.getLikedReplyIds()) {
1593 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1595 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1598 int friendCounter = 0;
1599 for (String friendId : sone.getFriends()) {
1600 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1602 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1604 /* save albums. first, collect in a flat structure, top-level first. */
1605 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1607 int albumCounter = 0;
1608 for (Album album : albums) {
1609 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1610 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1611 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1612 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1613 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1614 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1616 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1619 int imageCounter = 0;
1620 for (Album album : albums) {
1621 for (Image image : album.getImages()) {
1622 if (!image.isInserted()) {
1625 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1626 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1627 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1628 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1629 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1630 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1631 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1632 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1633 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1636 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1639 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1640 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1641 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1642 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1643 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1644 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1646 configuration.save();
1648 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1650 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1651 } catch (ConfigurationException ce1) {
1652 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1656 /** Saves the current options. */
1657 private void saveConfiguration() {
1658 synchronized (configuration) {
1659 if (storingConfiguration) {
1660 logger.log(Level.FINE, "Already storing configuration…");
1663 storingConfiguration = true;
1666 /* store the options first. */
1668 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1669 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1670 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1671 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1672 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1673 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1674 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1675 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1676 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1677 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1678 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1679 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1681 /* save known Sones. */
1682 int soneCounter = 0;
1683 synchronized (knownSones) {
1684 for (String knownSoneId : knownSones) {
1685 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1687 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1690 /* save Sone following times. */
1692 synchronized (soneFollowingTimes) {
1693 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1694 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1695 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1698 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1701 /* save known posts. */
1704 /* save bookmarked posts. */
1705 int bookmarkedPostCounter = 0;
1706 synchronized (bookmarkedPosts) {
1707 for (String bookmarkedPostId : bookmarkedPosts) {
1708 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1711 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1714 configuration.save();
1716 } catch (ConfigurationException ce1) {
1717 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1718 } catch (DatabaseException de1) {
1719 logger.log(Level.SEVERE, "Could not save database!", de1);
1721 synchronized (configuration) {
1722 storingConfiguration = false;
1727 /** Loads the configuration. */
1728 private void loadConfiguration() {
1729 /* create options. */
1730 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1733 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1734 SoneInserter.setInsertionDelay(newValue);
1738 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1739 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1740 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1741 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1742 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1743 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1744 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1745 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1746 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1749 @SuppressWarnings("synthetic-access")
1750 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1751 fcpInterface.setActive(newValue);
1754 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1757 @SuppressWarnings("synthetic-access")
1758 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1759 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1764 loadConfigurationValue("InsertionDelay");
1765 loadConfigurationValue("PostsPerPage");
1766 loadConfigurationValue("ImagesPerPage");
1767 loadConfigurationValue("CharactersPerPost");
1768 loadConfigurationValue("PostCutOffLength");
1769 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1770 loadConfigurationValue("PositiveTrust");
1771 loadConfigurationValue("NegativeTrust");
1772 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1773 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1774 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1776 /* load known Sones. */
1777 int soneCounter = 0;
1779 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1780 if (knownSoneId == null) {
1783 synchronized (knownSones) {
1784 knownSones.add(knownSoneId);
1788 /* load Sone following times. */
1791 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1792 if (soneId == null) {
1795 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1796 synchronized (soneFollowingTimes) {
1797 soneFollowingTimes.put(soneId, time);
1802 /* load bookmarked posts. */
1803 int bookmarkedPostCounter = 0;
1805 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1806 if (bookmarkedPostId == null) {
1809 synchronized (bookmarkedPosts) {
1810 bookmarkedPosts.add(bookmarkedPostId);
1817 * Loads an {@link Integer} configuration value for the option with the given
1818 * name, logging validation failures.
1821 * The name of the option to load
1823 private void loadConfigurationValue(String optionName) {
1825 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1826 } catch (IllegalArgumentException iae1) {
1827 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1832 * Notifies the core that a new {@link OwnIdentity} was added.
1834 * @param ownIdentityAddedEvent
1838 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1839 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1840 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1841 if (ownIdentity.hasContext("Sone")) {
1842 addLocalSone(ownIdentity);
1847 * Notifies the core that an {@link OwnIdentity} was removed.
1849 * @param ownIdentityRemovedEvent
1853 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1854 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1855 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1856 trustedIdentities.removeAll(ownIdentity);
1860 * Notifies the core that a new {@link Identity} was added.
1862 * @param identityAddedEvent
1866 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1867 Identity identity = identityAddedEvent.identity();
1868 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1869 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1870 addRemoteSone(identity);
1874 * Notifies the core that an {@link Identity} was updated.
1876 * @param identityUpdatedEvent
1880 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1881 final Identity identity = identityUpdatedEvent.identity();
1882 soneDownloaders.execute(new Runnable() {
1885 @SuppressWarnings("synthetic-access")
1887 Optional<Sone> sone = getRemoteSone(identity.getId());
1888 sone.get().setIdentity(identity);
1889 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1890 soneDownloader.addSone(sone.get());
1891 soneDownloader.fetchSone(sone.get());
1897 * Notifies the core that an {@link Identity} was removed.
1899 * @param identityRemovedEvent
1903 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1904 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1905 Identity identity = identityRemovedEvent.identity();
1906 trustedIdentities.remove(ownIdentity, identity);
1907 boolean foundIdentity = false;
1908 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1909 if (trustedIdentity.getKey().equals(ownIdentity)) {
1912 if (trustedIdentity.getValue().contains(identity)) {
1913 foundIdentity = true;
1916 if (foundIdentity) {
1917 /* some local identity still trusts this identity, don’t remove. */
1920 Optional<Sone> sone = getSone(identity.getId());
1921 if (!sone.isPresent()) {
1922 /* TODO - we don’t have the Sone anymore. should this happen? */
1925 database.removePosts(sone.get());
1926 for (Post post : sone.get().getPosts()) {
1927 eventBus.post(new PostRemovedEvent(post));
1929 database.removePostReplies(sone.get());
1930 for (PostReply reply : sone.get().getReplies()) {
1931 eventBus.post(new PostReplyRemovedEvent(reply));
1933 synchronized (sones) {
1934 sones.remove(identity.getId());
1936 eventBus.post(new SoneRemovedEvent(sone.get()));
1940 * Deletes the temporary image.
1942 * @param imageInsertFinishedEvent
1946 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1947 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1948 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1949 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1950 touchConfiguration();
1953 public PostCreated postCreated() {
1954 return new PostCreated() {
1956 public void postCreated(final Post post) {
1957 if (post.isKnown()) {
1960 eventBus.post(new NewPostFoundEvent(post));
1961 if (post.getSone().isLocal()) {
1962 localElementTicker.schedule(new Runnable() {
1965 markPostKnown(post);
1967 }, 10, TimeUnit.SECONDS);