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.ImageBuilder.ImageCreated;
73 import net.pterodactylus.sone.database.PostBuilder;
74 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
75 import net.pterodactylus.sone.database.PostReplyBuilder;
76 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
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 {
119 private static final Logger logger = Logging.getLogger(Core.class);
122 private final Options options = new Options();
124 /** The preferences. */
125 private final Preferences preferences = new Preferences(options);
127 /** The event bus. */
128 private final EventBus eventBus;
130 /** The configuration. */
131 private Configuration configuration;
133 /** Whether we’re currently saving the configuration. */
134 private boolean storingConfiguration = false;
136 /** The identity manager. */
137 private final IdentityManager identityManager;
139 /** Interface to freenet. */
140 private final FreenetInterface freenetInterface;
142 /** The Sone downloader. */
143 private final SoneDownloader soneDownloader;
145 /** The image inserter. */
146 private final ImageInserter imageInserter;
148 /** Sone downloader thread-pool. */
149 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151 /** The update checker. */
152 private final UpdateChecker updateChecker;
154 /** The trust updater. */
155 private final WebOfTrustUpdater webOfTrustUpdater;
157 /** The FCP interface. */
158 private volatile FcpInterface fcpInterface;
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
176 /* synchronize access on this on itself. */
177 private final Map<String, Sone> sones = new HashMap<String, Sone>();
179 /** All known Sones. */
180 private final Set<String> knownSones = new HashSet<String>();
182 /** The post database. */
183 private final Database database;
185 /** All bookmarked posts. */
186 /* synchronize access on itself. */
187 private final Set<String> bookmarkedPosts = new HashSet<String>();
189 /** Trusted identities, sorted by own identities. */
190 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
192 /** All temporary images. */
193 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
195 /** Ticker for threads that mark own elements as known. */
196 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
198 /** The time the configuration was last touched. */
199 private volatile long lastConfigurationUpdate;
202 * Creates a new core.
204 * @param configuration
205 * The configuration of the core
206 * @param freenetInterface
207 * The freenet interface
208 * @param identityManager
209 * The identity manager
210 * @param webOfTrustUpdater
211 * The WebOfTrust updater
218 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
220 this.configuration = configuration;
221 this.freenetInterface = freenetInterface;
222 this.identityManager = identityManager;
223 this.soneDownloader = new SoneDownloader(this, freenetInterface);
224 this.imageInserter = new ImageInserter(freenetInterface);
225 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
226 this.webOfTrustUpdater = webOfTrustUpdater;
227 this.eventBus = eventBus;
228 this.database = database;
236 * Sets the configuration to use. This will automatically save the current
237 * configuration to the given configuration.
239 * @param configuration
240 * The new configuration to use
242 public void setConfiguration(Configuration configuration) {
243 this.configuration = configuration;
244 touchConfiguration();
248 * Returns the options used by the core.
250 * @return The options of the core
252 public Preferences getPreferences() {
257 * Returns the identity manager used by the core.
259 * @return The identity manager
261 public IdentityManager getIdentityManager() {
262 return identityManager;
266 * Returns the update checker.
268 * @return The update checker
270 public UpdateChecker getUpdateChecker() {
271 return updateChecker;
275 * Sets the FCP interface to use.
277 * @param fcpInterface
278 * The FCP interface to use
280 public void setFcpInterface(FcpInterface fcpInterface) {
281 this.fcpInterface = fcpInterface;
284 public Database getDatabase() {
289 * Returns the Sone rescuer for the given local Sone.
292 * The local Sone to get the rescuer for
293 * @return The Sone rescuer for the given Sone
295 public SoneRescuer getSoneRescuer(Sone sone) {
296 checkNotNull(sone, "sone must not be null");
297 checkArgument(sone.isLocal(), "sone must be local");
298 synchronized (sones) {
299 SoneRescuer soneRescuer = soneRescuers.get(sone);
300 if (soneRescuer == null) {
301 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
302 soneRescuers.put(sone, soneRescuer);
310 * Returns whether the given Sone is currently locked.
314 * @return {@code true} if the Sone is locked, {@code false} if it is not
316 public boolean isLocked(Sone sone) {
317 synchronized (lockedSones) {
318 return lockedSones.contains(sone);
323 public Collection<Sone> getSones() {
324 synchronized (sones) {
325 return ImmutableSet.copyOf(sones.values());
330 public Optional<Sone> getSone(String id) {
331 synchronized (sones) {
332 return Optional.fromNullable(sones.get(id));
337 public Collection<Sone> getLocalSones() {
338 synchronized (sones) {
339 return from(sones.values()).filter(new Predicate<Sone>() {
342 public boolean apply(Sone sone) {
343 return sone.isLocal();
350 * Returns the local Sone with the given ID, optionally creating a new Sone.
354 * @return The Sone with the given ID, or {@code null}
356 public Optional<Sone> getLocalSone(String id) {
357 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
361 public Collection<Sone> getRemoteSones() {
362 synchronized (sones) {
363 return from(sones.values()).filter(new Predicate<Sone>() {
366 public boolean apply(Sone sone) {
367 return !sone.isLocal();
374 * Returns the remote Sone with the given ID.
377 * The ID of the remote Sone to get
378 * @return The Sone with the given ID
380 public Optional<Sone> getRemoteSone(String id) {
381 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
385 * Returns whether the given Sone has been modified.
388 * The Sone to check for modifications
389 * @return {@code true} if a modification has been detected in the Sone, {@code
392 public boolean isModifiedSone(Sone sone) {
393 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
397 * Returns the time when the given was first followed by any local Sone.
400 * The Sone to get the time for
401 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
402 * followed, or {@link Long#MAX_VALUE}
404 public long getSoneFollowingTime(Sone sone) {
405 synchronized (soneFollowingTimes) {
406 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
410 public Optional<PostReply> getPostReply(String replyId) {
411 return database.getPostReply(replyId);
414 public List<PostReply> getReplies(final String postId) {
415 return database.getReplies(postId);
419 * Returns all Sones that have liked the given post.
422 * The post to get the liking Sones for
423 * @return The Sones that like the given post
425 public Set<Sone> getLikes(Post post) {
426 Set<Sone> sones = new HashSet<Sone>();
427 for (Sone sone : getSones()) {
428 if (sone.getLikedPostIds().contains(post.getId())) {
436 * Returns all Sones that have liked the given reply.
439 * The reply to get the liking Sones for
440 * @return The Sones that like the given reply
442 public Set<Sone> getLikes(PostReply reply) {
443 Set<Sone> sones = new HashSet<Sone>();
444 for (Sone sone : getSones()) {
445 if (sone.getLikedReplyIds().contains(reply.getId())) {
453 * Returns whether the given post is bookmarked.
457 * @return {@code true} if the given post is bookmarked, {@code false}
460 public boolean isBookmarked(Post post) {
461 return isPostBookmarked(post.getId());
465 * Returns whether the post with the given ID is bookmarked.
468 * The ID of the post to check
469 * @return {@code true} if the post with the given ID is bookmarked, {@code
472 public boolean isPostBookmarked(String id) {
473 synchronized (bookmarkedPosts) {
474 return bookmarkedPosts.contains(id);
479 * Returns all currently known bookmarked posts.
481 * @return All bookmarked posts
483 public Set<Post> getBookmarkedPosts() {
484 Set<Post> posts = new HashSet<Post>();
485 synchronized (bookmarkedPosts) {
486 for (String bookmarkedPostId : bookmarkedPosts) {
487 Optional<Post> post = database.getPost(bookmarkedPostId);
488 if (post.isPresent()) {
489 posts.add(post.get());
496 public Optional<Album> getAlbum(String albumId) {
497 return database.getAlbum(albumId);
500 public Optional<Image> getImage(String imageId) {
501 return database.getImage(imageId);
505 * Returns the temporary image with the given ID.
508 * The ID of the temporary image
509 * @return The temporary image, or {@code null} if there is no temporary image
512 public TemporaryImage getTemporaryImage(String imageId) {
513 synchronized (temporaryImages) {
514 return temporaryImages.get(imageId);
523 * Locks the given Sone. A locked Sone will not be inserted by {@link
524 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
529 public void lockSone(Sone sone) {
530 synchronized (lockedSones) {
531 if (lockedSones.add(sone)) {
532 eventBus.post(new SoneLockedEvent(sone));
538 * Unlocks the given Sone.
542 * @see #lockSone(Sone)
544 public void unlockSone(Sone sone) {
545 synchronized (lockedSones) {
546 if (lockedSones.remove(sone)) {
547 eventBus.post(new SoneUnlockedEvent(sone));
553 * Adds a local Sone from the given own identity.
556 * The own identity to create a Sone from
557 * @return The added (or already existing) Sone
559 public Sone addLocalSone(OwnIdentity ownIdentity) {
560 if (ownIdentity == null) {
561 logger.log(Level.WARNING, "Given OwnIdentity is null!");
564 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
565 synchronized (sones) {
568 sone = database.newSoneBuilder().by(ownIdentity).local().build().setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
569 } catch (MalformedURLException mue1) {
570 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
573 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
574 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
576 /* TODO - load posts ’n stuff */
577 sones.put(ownIdentity.getId(), sone);
578 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
579 soneInserters.put(sone, soneInserter);
580 sone.setStatus(SoneStatus.idle);
582 soneInserter.start();
588 * Creates a new Sone for the given own identity.
591 * The own identity to create a Sone for
592 * @return The created Sone
594 public Sone createSone(OwnIdentity ownIdentity) {
595 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
596 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
599 Sone sone = addLocalSone(ownIdentity);
600 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
601 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
602 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
603 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
604 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
605 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
607 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
608 touchConfiguration();
613 * Adds the Sone of the given identity.
616 * The identity whose Sone to add
617 * @return The added or already existing Sone
619 public Sone addRemoteSone(Identity identity) {
620 if (identity == null) {
621 logger.log(Level.WARNING, "Given Identity is null!");
624 synchronized (sones) {
625 final Sone sone = database.newSoneBuilder().by(identity).build();
626 if (sone.isLocal()) {
629 sone.setIdentity(identity);
630 boolean newSone = sone.getRequestUri() == null;
631 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
632 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
634 synchronized (knownSones) {
635 newSone = !knownSones.contains(sone.getId());
637 sone.setKnown(!newSone);
639 eventBus.post(new NewSoneFoundEvent(sone));
640 for (Sone localSone : getLocalSones()) {
641 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
642 followSone(localSone, sone.getId());
647 soneDownloader.addSone(sone);
648 soneDownloaders.execute(new Runnable() {
651 @SuppressWarnings("synthetic-access")
653 soneDownloader.fetchSone(sone, sone.getRequestUri());
662 * Lets the given local Sone follow the Sone with the given ID.
665 * The local Sone that should follow another Sone
667 * The ID of the Sone to follow
669 public void followSone(Sone sone, String soneId) {
670 checkNotNull(sone, "sone must not be null");
671 checkNotNull(soneId, "soneId must not be null");
672 sone.addFriend(soneId);
673 synchronized (soneFollowingTimes) {
674 if (!soneFollowingTimes.containsKey(soneId)) {
675 long now = System.currentTimeMillis();
676 soneFollowingTimes.put(soneId, now);
677 Optional<Sone> followedSone = getSone(soneId);
678 if (!followedSone.isPresent()) {
681 for (Post post : followedSone.get().getPosts()) {
682 if (post.getTime() < now) {
686 for (PostReply reply : followedSone.get().getReplies()) {
687 if (reply.getTime() < now) {
688 markReplyKnown(reply);
693 touchConfiguration();
697 * Lets the given local Sone unfollow the Sone with the given ID.
700 * The local Sone that should unfollow another Sone
702 * The ID of the Sone being unfollowed
704 public void unfollowSone(Sone sone, String soneId) {
705 checkNotNull(sone, "sone must not be null");
706 checkNotNull(soneId, "soneId must not be null");
707 sone.removeFriend(soneId);
708 boolean unfollowedSoneStillFollowed = false;
709 for (Sone localSone : getLocalSones()) {
710 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
712 if (!unfollowedSoneStillFollowed) {
713 synchronized (soneFollowingTimes) {
714 soneFollowingTimes.remove(soneId);
717 touchConfiguration();
721 * Sets the trust value of the given origin Sone for the target Sone.
728 * The trust value (from {@code -100} to {@code 100})
730 public void setTrust(Sone origin, Sone target, int trustValue) {
731 checkNotNull(origin, "origin must not be null");
732 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
733 checkNotNull(target, "target must not be null");
734 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
735 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
739 * Removes any trust assignment for the given target Sone.
746 public void removeTrust(Sone origin, Sone target) {
747 checkNotNull(origin, "origin must not be null");
748 checkNotNull(target, "target must not be null");
749 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
750 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
754 * Assigns the configured positive trust value for the given target.
761 public void trustSone(Sone origin, Sone target) {
762 setTrust(origin, target, preferences.getPositiveTrust());
766 * Assigns the configured negative trust value for the given target.
773 public void distrustSone(Sone origin, Sone target) {
774 setTrust(origin, target, preferences.getNegativeTrust());
778 * Removes the trust assignment for the given target.
785 public void untrustSone(Sone origin, Sone target) {
786 removeTrust(origin, target);
790 * Updates the stored Sone with the given Sone.
795 public void updateSone(Sone sone) {
796 updateSone(sone, false);
800 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
801 * {@code true}, an older Sone than the current Sone can be given to restore an
806 * @param soneRescueMode
807 * {@code true} if the stored Sone should be updated regardless of the age of
810 public void updateSone(Sone sone, boolean soneRescueMode) {
811 Optional<Sone> storedSone = getSone(sone.getId());
812 if (storedSone.isPresent()) {
813 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
814 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
817 /* find removed posts. */
818 Collection<Post> existingPosts = database.getPosts(sone.getId());
819 for (Post oldPost : existingPosts) {
820 if (!sone.getPosts().contains(oldPost)) {
821 eventBus.post(new PostRemovedEvent(oldPost));
824 /* find new posts. */
825 for (Post newPost : sone.getPosts()) {
826 if (existingPosts.contains(newPost)) {
829 if (newPost.getTime() < getSoneFollowingTime(sone)) {
830 newPost.setKnown(true);
831 } else if (!newPost.isKnown()) {
832 eventBus.post(new NewPostFoundEvent(newPost));
836 database.storePosts(sone, sone.getPosts());
837 if (!soneRescueMode) {
838 for (PostReply reply : storedSone.get().getReplies()) {
839 if (!sone.getReplies().contains(reply)) {
840 eventBus.post(new PostReplyRemovedEvent(reply));
844 Set<PostReply> storedReplies = storedSone.get().getReplies();
845 for (PostReply reply : sone.getReplies()) {
846 if (storedReplies.contains(reply)) {
849 if (reply.getTime() < getSoneFollowingTime(sone)) {
850 reply.setKnown(true);
851 } else if (!reply.isKnown()) {
852 eventBus.post(new NewPostReplyFoundEvent(reply));
855 database.storePostReplies(sone, sone.getReplies());
856 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
857 database.removeAlbum(album);
858 for (Image image : album.getImages()) {
859 database.removeImage(image);
862 for (Album album : sone.getRootAlbum().getAlbums()) {
863 database.storeAlbum(album);
864 for (Image image : album.getImages()) {
865 database.storeImage(image);
868 synchronized (sones) {
869 sone.setOptions(storedSone.get().getOptions());
870 sone.setKnown(storedSone.get().isKnown());
871 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
872 if (sone.isLocal()) {
873 soneInserters.get(storedSone.get()).setSone(sone);
874 touchConfiguration();
876 sones.put(sone.getId(), sone);
882 * Deletes the given Sone. This will remove the Sone from the {@link
883 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
884 * context from its identity.
889 public void deleteSone(Sone sone) {
890 if (!(sone.getIdentity() instanceof OwnIdentity)) {
891 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
894 synchronized (sones) {
895 if (!getLocalSones().contains(sone)) {
896 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
899 sones.remove(sone.getId());
900 SoneInserter soneInserter = soneInserters.remove(sone);
903 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
904 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
906 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
907 } catch (ConfigurationException ce1) {
908 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
913 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
914 * known} before, a {@link MarkSoneKnownEvent} is fired.
917 * The Sone to mark as known
919 public void markSoneKnown(Sone sone) {
920 if (!sone.isKnown()) {
922 synchronized (knownSones) {
923 knownSones.add(sone.getId());
925 eventBus.post(new MarkSoneKnownEvent(sone));
926 touchConfiguration();
931 * Loads and updates the given Sone from the configuration. If any error is
932 * encountered, loading is aborted and the given Sone is not changed.
935 * The Sone to load and update
937 public void loadSone(Sone sone) {
938 if (!sone.isLocal()) {
939 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
942 logger.info(String.format("Loading local Sone: %s", sone));
944 /* initialize options. */
945 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
946 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
947 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
948 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
949 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
950 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
953 String sonePrefix = "Sone/" + sone.getId();
954 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
955 if (soneTime == null) {
956 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
959 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
962 Profile profile = new Profile(sone);
963 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
964 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
965 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
966 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
967 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
968 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
970 /* load profile fields. */
972 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
973 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
974 if (fieldName == null) {
977 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
978 profile.addField(fieldName).setValue(fieldValue);
982 Set<Post> posts = new HashSet<Post>();
984 String postPrefix = sonePrefix + "/Posts/" + posts.size();
985 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
986 if (postId == null) {
989 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
990 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
991 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
992 if ((postTime == 0) || (postText == null)) {
993 logger.log(Level.WARNING, "Invalid post found, aborting load!");
996 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
997 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
998 postBuilder.to(of(postRecipientId));
1000 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1004 Set<PostReply> replies = new HashSet<PostReply>();
1006 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1007 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1008 if (replyId == null) {
1011 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1012 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1013 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1014 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1015 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1018 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1019 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1022 /* load post likes. */
1023 Set<String> likedPostIds = new HashSet<String>();
1025 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1026 if (likedPostId == null) {
1029 likedPostIds.add(likedPostId);
1032 /* load reply likes. */
1033 Set<String> likedReplyIds = new HashSet<String>();
1035 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1036 if (likedReplyId == null) {
1039 likedReplyIds.add(likedReplyId);
1043 Set<String> friends = new HashSet<String>();
1045 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1046 if (friendId == null) {
1049 friends.add(friendId);
1053 Map<String, Album> albums = Maps.newHashMap();
1054 int albumCounter = 0;
1056 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1057 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1058 if (albumId == null) {
1061 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1062 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1063 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1064 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1065 if ((albumTitle == null) || (albumDescription == null)) {
1066 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1069 Album parentAlbum = sone.getRootAlbum();
1070 if (albumParentId != null) {
1071 parentAlbum = albums.get(albumParentId);
1073 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1074 albums.put(album.getId(), album);
1078 int imageCounter = 0;
1080 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1081 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1082 if (imageId == null) {
1085 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1086 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1087 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1088 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1089 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1090 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1091 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1092 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1093 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1096 Album album = albums.get(albumId);
1097 if (album == null) {
1098 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1101 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1105 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1106 if (avatarId != null) {
1107 profile.setAvatar(getImage(avatarId).orNull());
1111 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1112 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1113 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1114 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1115 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1116 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1118 /* if we’re still here, Sone was loaded successfully. */
1119 synchronized (sone) {
1120 sone.setTime(soneTime);
1121 sone.setProfile(profile);
1122 sone.setPosts(posts);
1123 sone.setReplies(replies);
1124 sone.setLikePostIds(likedPostIds);
1125 sone.setLikeReplyIds(likedReplyIds);
1126 for (String friendId : friends) {
1127 followSone(sone, friendId);
1129 for (Album album : sone.getRootAlbum().getAlbums()) {
1132 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1134 synchronized (knownSones) {
1135 for (String friend : friends) {
1136 knownSones.add(friend);
1139 database.storePosts(sone, posts);
1140 for (Post post : posts) {
1141 post.setKnown(true);
1143 database.storePostReplies(sone, replies);
1144 for (PostReply reply : replies) {
1145 reply.setKnown(true);
1148 logger.info(String.format("Sone loaded successfully: %s", sone));
1152 * Deletes the given post.
1155 * The post to delete
1157 public void deletePost(Post post) {
1158 if (!post.getSone().isLocal()) {
1159 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1162 database.removePost(post);
1163 eventBus.post(new PostRemovedEvent(post));
1164 markPostKnown(post);
1165 touchConfiguration();
1169 * Marks the given post as known, if it is currently not a known post
1170 * (according to {@link Post#isKnown()}).
1173 * The post to mark as known
1175 public void markPostKnown(Post post) {
1176 post.setKnown(true);
1177 eventBus.post(new MarkPostKnownEvent(post));
1178 touchConfiguration();
1179 for (PostReply reply : getReplies(post.getId())) {
1180 markReplyKnown(reply);
1185 * Bookmarks the post with the given ID.
1188 * The ID of the post to bookmark
1190 public void bookmarkPost(String id) {
1191 synchronized (bookmarkedPosts) {
1192 bookmarkedPosts.add(id);
1197 * Removes the given post from the bookmarks.
1200 * The post to unbookmark
1202 public void unbookmark(Post post) {
1203 unbookmarkPost(post.getId());
1207 * Removes the post with the given ID from the bookmarks.
1210 * The ID of the post to unbookmark
1212 public void unbookmarkPost(String id) {
1213 synchronized (bookmarkedPosts) {
1214 bookmarkedPosts.remove(id);
1219 * Deletes the given reply.
1222 * The reply to delete
1224 public void deleteReply(PostReply reply) {
1225 Sone sone = reply.getSone();
1226 if (!sone.isLocal()) {
1227 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1230 database.removePostReply(reply);
1231 markReplyKnown(reply);
1232 sone.removeReply(reply);
1233 touchConfiguration();
1237 * Marks the given reply as known, if it is currently not a known reply
1238 * (according to {@link Reply#isKnown()}).
1241 * The reply to mark as known
1243 public void markReplyKnown(PostReply reply) {
1244 boolean previouslyKnown = reply.isKnown();
1245 reply.setKnown(true);
1246 eventBus.post(new MarkPostReplyKnownEvent(reply));
1247 if (!previouslyKnown) {
1248 touchConfiguration();
1253 * Creates a new image.
1256 * The Sone creating the image
1258 * The album the image will be inserted into
1259 * @param temporaryImage
1260 * The temporary image to create the image from
1261 * @return The newly created image
1263 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1264 checkNotNull(sone, "sone must not be null");
1265 checkNotNull(album, "album must not be null");
1266 checkNotNull(temporaryImage, "temporaryImage must not be null");
1267 checkArgument(sone.isLocal(), "sone must be a local Sone");
1268 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1269 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1270 imageInserter.insertImage(temporaryImage, image);
1275 * Deletes the given image. This method will also delete a matching temporary
1279 * The image to delete
1280 * @see #deleteTemporaryImage(String)
1282 public void deleteImage(Image image) {
1283 checkNotNull(image, "image must not be null");
1284 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1285 deleteTemporaryImage(image.getId());
1287 touchConfiguration();
1291 * Creates a new temporary image.
1294 * The MIME type of the temporary image
1296 * The encoded data of the image
1297 * @return The temporary image
1299 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1300 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1301 synchronized (temporaryImages) {
1302 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1304 return temporaryImage;
1308 * Deletes the temporary image with the given ID.
1311 * The ID of the temporary image to delete
1313 public void deleteTemporaryImage(String imageId) {
1314 checkNotNull(imageId, "imageId must not be null");
1315 synchronized (temporaryImages) {
1316 temporaryImages.remove(imageId);
1318 Optional<Image> image = getImage(imageId);
1319 if (image.isPresent()) {
1320 imageInserter.cancelImageInsert(image.get());
1325 * Notifies the core that the configuration, either of the core or of a single
1326 * local Sone, has changed, and that the configuration should be saved.
1328 public void touchConfiguration() {
1329 lastConfigurationUpdate = System.currentTimeMillis();
1337 public void serviceStart() {
1338 loadConfiguration();
1339 updateChecker.start();
1340 identityManager.start();
1341 webOfTrustUpdater.init();
1342 webOfTrustUpdater.start();
1347 public void serviceRun() {
1348 long lastSaved = System.currentTimeMillis();
1349 while (!shouldStop()) {
1351 long now = System.currentTimeMillis();
1352 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1353 for (Sone localSone : getLocalSones()) {
1354 saveSone(localSone);
1356 saveConfiguration();
1363 public void serviceStop() {
1364 localElementTicker.shutdownNow();
1365 synchronized (sones) {
1366 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1367 soneInserter.getValue().stop();
1368 saveSone(soneInserter.getKey());
1371 saveConfiguration();
1373 webOfTrustUpdater.stop();
1374 updateChecker.stop();
1375 soneDownloader.stop();
1376 soneDownloaders.shutdown();
1377 identityManager.stop();
1385 * Saves the given Sone. This will persist all local settings for the given
1386 * Sone, such as the friends list and similar, private options.
1391 private synchronized void saveSone(Sone sone) {
1392 if (!sone.isLocal()) {
1393 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1396 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1397 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1401 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1403 /* save Sone into configuration. */
1404 String sonePrefix = "Sone/" + sone.getId();
1405 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1406 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1409 Profile profile = sone.getProfile();
1410 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1411 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1412 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1413 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1414 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1415 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1416 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1418 /* save profile fields. */
1419 int fieldCounter = 0;
1420 for (Field profileField : profile.getFields()) {
1421 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1422 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1423 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1425 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1428 int postCounter = 0;
1429 for (Post post : sone.getPosts()) {
1430 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1431 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1432 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1433 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1434 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1436 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1439 int replyCounter = 0;
1440 for (PostReply reply : sone.getReplies()) {
1441 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1442 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1443 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1444 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1445 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1447 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1449 /* save post likes. */
1450 int postLikeCounter = 0;
1451 for (String postId : sone.getLikedPostIds()) {
1452 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1454 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1456 /* save reply likes. */
1457 int replyLikeCounter = 0;
1458 for (String replyId : sone.getLikedReplyIds()) {
1459 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1461 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1464 int friendCounter = 0;
1465 for (String friendId : sone.getFriends()) {
1466 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1468 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1470 /* save albums. first, collect in a flat structure, top-level first. */
1471 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1473 int albumCounter = 0;
1474 for (Album album : albums) {
1475 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1476 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1477 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1478 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1479 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1480 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1482 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1485 int imageCounter = 0;
1486 for (Album album : albums) {
1487 for (Image image : album.getImages()) {
1488 if (!image.isInserted()) {
1491 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1492 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1493 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1494 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1495 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1496 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1497 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1498 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1499 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1502 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1505 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1506 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1507 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1508 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1509 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1510 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1512 configuration.save();
1514 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1516 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1517 } catch (ConfigurationException ce1) {
1518 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1522 /** Saves the current options. */
1523 private void saveConfiguration() {
1524 synchronized (configuration) {
1525 if (storingConfiguration) {
1526 logger.log(Level.FINE, "Already storing configuration…");
1529 storingConfiguration = true;
1532 /* store the options first. */
1534 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1535 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1536 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1537 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1538 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1539 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1540 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1541 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1542 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1543 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1544 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1545 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1547 /* save known Sones. */
1548 int soneCounter = 0;
1549 synchronized (knownSones) {
1550 for (String knownSoneId : knownSones) {
1551 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1553 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1556 /* save Sone following times. */
1558 synchronized (soneFollowingTimes) {
1559 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1560 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1561 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1564 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1567 /* save known posts. */
1570 /* save bookmarked posts. */
1571 int bookmarkedPostCounter = 0;
1572 synchronized (bookmarkedPosts) {
1573 for (String bookmarkedPostId : bookmarkedPosts) {
1574 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1577 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1580 configuration.save();
1582 } catch (ConfigurationException ce1) {
1583 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1584 } catch (DatabaseException de1) {
1585 logger.log(Level.SEVERE, "Could not save database!", de1);
1587 synchronized (configuration) {
1588 storingConfiguration = false;
1593 /** Loads the configuration. */
1594 private void loadConfiguration() {
1595 /* create options. */
1596 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1599 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1600 SoneInserter.setInsertionDelay(newValue);
1604 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1605 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1606 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1607 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1608 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1609 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1610 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1611 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1612 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1615 @SuppressWarnings("synthetic-access")
1616 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1617 fcpInterface.setActive(newValue);
1620 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1623 @SuppressWarnings("synthetic-access")
1624 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1625 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1630 loadConfigurationValue("InsertionDelay");
1631 loadConfigurationValue("PostsPerPage");
1632 loadConfigurationValue("ImagesPerPage");
1633 loadConfigurationValue("CharactersPerPost");
1634 loadConfigurationValue("PostCutOffLength");
1635 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1636 loadConfigurationValue("PositiveTrust");
1637 loadConfigurationValue("NegativeTrust");
1638 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1639 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1640 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1642 /* load known Sones. */
1643 int soneCounter = 0;
1645 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1646 if (knownSoneId == null) {
1649 synchronized (knownSones) {
1650 knownSones.add(knownSoneId);
1654 /* load Sone following times. */
1657 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1658 if (soneId == null) {
1661 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1662 synchronized (soneFollowingTimes) {
1663 soneFollowingTimes.put(soneId, time);
1668 /* load bookmarked posts. */
1669 int bookmarkedPostCounter = 0;
1671 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1672 if (bookmarkedPostId == null) {
1675 synchronized (bookmarkedPosts) {
1676 bookmarkedPosts.add(bookmarkedPostId);
1683 * Loads an {@link Integer} configuration value for the option with the given
1684 * name, logging validation failures.
1687 * The name of the option to load
1689 private void loadConfigurationValue(String optionName) {
1691 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1692 } catch (IllegalArgumentException iae1) {
1693 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1698 * Notifies the core that a new {@link OwnIdentity} was added.
1700 * @param ownIdentityAddedEvent
1704 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1705 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1706 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1707 if (ownIdentity.hasContext("Sone")) {
1708 addLocalSone(ownIdentity);
1713 * Notifies the core that an {@link OwnIdentity} was removed.
1715 * @param ownIdentityRemovedEvent
1719 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1720 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1721 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1722 trustedIdentities.removeAll(ownIdentity);
1726 * Notifies the core that a new {@link Identity} was added.
1728 * @param identityAddedEvent
1732 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1733 Identity identity = identityAddedEvent.identity();
1734 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1735 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1736 addRemoteSone(identity);
1740 * Notifies the core that an {@link Identity} was updated.
1742 * @param identityUpdatedEvent
1746 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1747 final Identity identity = identityUpdatedEvent.identity();
1748 soneDownloaders.execute(new Runnable() {
1751 @SuppressWarnings("synthetic-access")
1753 Optional<Sone> sone = getRemoteSone(identity.getId());
1754 sone.get().setIdentity(identity);
1755 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1756 soneDownloader.addSone(sone.get());
1757 soneDownloader.fetchSone(sone.get());
1763 * Notifies the core that an {@link Identity} was removed.
1765 * @param identityRemovedEvent
1769 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1770 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1771 Identity identity = identityRemovedEvent.identity();
1772 trustedIdentities.remove(ownIdentity, identity);
1773 boolean foundIdentity = false;
1774 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1775 if (trustedIdentity.getKey().equals(ownIdentity)) {
1778 if (trustedIdentity.getValue().contains(identity)) {
1779 foundIdentity = true;
1782 if (foundIdentity) {
1783 /* some local identity still trusts this identity, don’t remove. */
1786 Optional<Sone> sone = getSone(identity.getId());
1787 if (!sone.isPresent()) {
1788 /* TODO - we don’t have the Sone anymore. should this happen? */
1791 database.removePosts(sone.get());
1792 for (Post post : sone.get().getPosts()) {
1793 eventBus.post(new PostRemovedEvent(post));
1795 database.removePostReplies(sone.get());
1796 for (PostReply reply : sone.get().getReplies()) {
1797 eventBus.post(new PostReplyRemovedEvent(reply));
1799 synchronized (sones) {
1800 sones.remove(identity.getId());
1802 eventBus.post(new SoneRemovedEvent(sone.get()));
1806 * Deletes the temporary image.
1808 * @param imageInsertFinishedEvent
1812 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1813 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1814 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1815 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1816 touchConfiguration();
1819 public Optional<PostCreated> postCreated() {
1820 return Optional.<PostCreated>of(new PostCreated() {
1822 public void postCreated(final Post post) {
1823 if (post.isKnown()) {
1826 eventBus.post(new NewPostFoundEvent(post));
1827 if (post.getSone().isLocal()) {
1828 localElementTicker.schedule(new Runnable() {
1831 markPostKnown(post);
1833 }, 10, TimeUnit.SECONDS);
1839 public Optional<PostReplyCreated> postReplyCreated() {
1840 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1842 public void postReplyCreated(final PostReply postReply) {
1843 if (postReply.isKnown()) {
1846 eventBus.post(new NewPostReplyFoundEvent(postReply));
1847 if (postReply.getSone().isLocal()) {
1848 localElementTicker.schedule(new Runnable() {
1855 markReplyKnown(postReply);
1857 }, 10, TimeUnit.SECONDS);
1863 public Optional<ImageCreated> imageCreated() {
1864 return Optional.<ImageCreated>of(new ImageCreated() {
1866 public void imageCreated(Image image) {
1867 /* nothing happens here yet. */