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.absent;
21 import static com.google.common.base.Optional.of;
22 import static com.google.common.base.Preconditions.checkArgument;
23 import static com.google.common.base.Preconditions.checkNotNull;
24 import static com.google.common.base.Predicates.not;
25 import static com.google.common.collect.FluentIterable.from;
26 import static net.pterodactylus.sone.data.Identified.GET_ID;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
29 import java.net.MalformedURLException;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
35 import java.util.Map.Entry;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
44 import net.pterodactylus.sone.core.Options.DefaultOption;
45 import net.pterodactylus.sone.core.Options.Option;
46 import net.pterodactylus.sone.core.Options.OptionWatcher;
47 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
48 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
49 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
51 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
52 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
53 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
54 import net.pterodactylus.sone.core.event.PostRemovedEvent;
55 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneLockedEvent;
57 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
58 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
59 import net.pterodactylus.sone.data.Album;
60 import net.pterodactylus.sone.data.Client;
61 import net.pterodactylus.sone.data.Image;
62 import net.pterodactylus.sone.data.Post;
63 import net.pterodactylus.sone.data.PostReply;
64 import net.pterodactylus.sone.data.Profile;
65 import net.pterodactylus.sone.data.Profile.Field;
66 import net.pterodactylus.sone.data.Reply.Modifier.ReplyUpdated;
67 import net.pterodactylus.sone.data.Sone;
68 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
69 import net.pterodactylus.sone.data.Sone.SoneStatus;
70 import net.pterodactylus.sone.data.TemporaryImage;
71 import net.pterodactylus.sone.database.Database;
72 import net.pterodactylus.sone.database.DatabaseException;
73 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
74 import net.pterodactylus.sone.database.PostBuilder;
75 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
76 import net.pterodactylus.sone.database.PostReplyBuilder;
77 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
78 import net.pterodactylus.sone.database.SoneBuilder.SoneCreated;
79 import net.pterodactylus.sone.database.SoneProvider;
80 import net.pterodactylus.sone.fcp.FcpInterface;
81 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
82 import net.pterodactylus.sone.freenet.wot.Identity;
83 import net.pterodactylus.sone.freenet.wot.IdentityManager;
84 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
85 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
90 import net.pterodactylus.sone.main.SonePlugin;
91 import net.pterodactylus.sone.utils.IntegerRangePredicate;
92 import net.pterodactylus.util.config.Configuration;
93 import net.pterodactylus.util.config.ConfigurationException;
94 import net.pterodactylus.util.logging.Logging;
95 import net.pterodactylus.util.number.Numbers;
96 import net.pterodactylus.util.service.AbstractService;
97 import net.pterodactylus.util.thread.NamedThreadFactory;
99 import freenet.keys.FreenetURI;
101 import com.google.common.base.Optional;
102 import com.google.common.base.Predicate;
103 import com.google.common.base.Predicates;
104 import com.google.common.collect.HashMultimap;
105 import com.google.common.collect.ImmutableSet;
106 import com.google.common.collect.Maps;
107 import com.google.common.collect.Multimap;
108 import com.google.common.collect.Multimaps;
109 import com.google.common.eventbus.EventBus;
110 import com.google.common.eventbus.Subscribe;
111 import com.google.inject.Inject;
116 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
118 public class Core extends AbstractService implements SoneProvider {
121 private static final Logger logger = Logging.getLogger(Core.class);
124 private final Options options = new Options();
126 /** The preferences. */
127 private final Preferences preferences = new Preferences(options);
129 /** The event bus. */
130 private final EventBus eventBus;
132 /** The configuration. */
133 private Configuration configuration;
135 /** Whether we’re currently saving the configuration. */
136 private boolean storingConfiguration = false;
138 /** The identity manager. */
139 private final IdentityManager identityManager;
141 /** Interface to freenet. */
142 private final FreenetInterface freenetInterface;
144 /** The Sone downloader. */
145 private final SoneDownloader soneDownloader;
147 /** The image inserter. */
148 private final ImageInserter imageInserter;
150 /** Sone downloader thread-pool. */
151 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
153 /** The update checker. */
154 private final UpdateChecker updateChecker;
156 /** The trust updater. */
157 private final WebOfTrustUpdater webOfTrustUpdater;
159 /** The FCP interface. */
160 private volatile FcpInterface fcpInterface;
162 /** The times Sones were followed. */
163 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
165 /** Locked local Sones. */
166 /* synchronize on itself. */
167 private final Set<Sone> lockedSones = new HashSet<Sone>();
169 /** Sone inserters. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
173 /** Sone rescuers. */
174 /* synchronize access on this on sones. */
175 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
178 /* synchronize access on this on itself. */
179 private final Map<String, Sone> sones = new HashMap<String, Sone>();
181 /** All known Sones. */
182 private final Set<String> knownSones = new HashSet<String>();
184 /** The post database. */
185 private final Database database;
187 /** All bookmarked posts. */
188 /* synchronize access on itself. */
189 private final Set<String> bookmarkedPosts = new HashSet<String>();
191 /** Trusted identities, sorted by own identities. */
192 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
194 /** All temporary images. */
195 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
197 /** Ticker for threads that mark own elements as known. */
198 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
200 /** The time the configuration was last touched. */
201 private volatile long lastConfigurationUpdate;
204 * Creates a new core.
206 * @param configuration
207 * The configuration of the core
208 * @param freenetInterface
209 * The freenet interface
210 * @param identityManager
211 * The identity manager
212 * @param webOfTrustUpdater
213 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(freenetInterface);
227 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
230 this.database = database;
238 * Sets the configuration to use. This will automatically save the current
239 * configuration to the given configuration.
241 * @param configuration
242 * The new configuration to use
244 public void setConfiguration(Configuration configuration) {
245 this.configuration = configuration;
246 touchConfiguration();
250 * Returns the options used by the core.
252 * @return The options of the core
254 public Preferences getPreferences() {
259 * Returns the identity manager used by the core.
261 * @return The identity manager
263 public IdentityManager getIdentityManager() {
264 return identityManager;
268 * Returns the update checker.
270 * @return The update checker
272 public UpdateChecker getUpdateChecker() {
273 return updateChecker;
277 * Sets the FCP interface to use.
279 * @param fcpInterface
280 * The FCP interface to use
282 public void setFcpInterface(FcpInterface fcpInterface) {
283 this.fcpInterface = fcpInterface;
286 public Database getDatabase() {
291 * Returns the Sone rescuer for the given local Sone.
294 * The local Sone to get the rescuer for
295 * @return The Sone rescuer for the given Sone
297 public SoneRescuer getSoneRescuer(Sone sone) {
298 checkNotNull(sone, "sone must not be null");
299 checkArgument(sone.isLocal(), "sone must be local");
300 synchronized (sones) {
301 SoneRescuer soneRescuer = soneRescuers.get(sone);
302 if (soneRescuer == null) {
303 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
304 soneRescuers.put(sone, soneRescuer);
312 * Returns whether the given Sone is currently locked.
316 * @return {@code true} if the Sone is locked, {@code false} if it is not
318 public boolean isLocked(Sone sone) {
319 synchronized (lockedSones) {
320 return lockedSones.contains(sone);
325 public Collection<Sone> getSones() {
326 synchronized (sones) {
327 return ImmutableSet.copyOf(sones.values());
332 public Optional<Sone> getSone(String id) {
333 synchronized (sones) {
334 return Optional.fromNullable(sones.get(id));
339 public Collection<Sone> getLocalSones() {
340 synchronized (sones) {
341 return from(sones.values()).filter(new Predicate<Sone>() {
344 public boolean apply(Sone sone) {
345 return sone.isLocal();
352 * Returns the local Sone with the given ID, optionally creating a new Sone.
356 * @return The Sone with the given ID, or {@code null}
358 public Optional<Sone> getLocalSone(String id) {
359 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
363 public Collection<Sone> getRemoteSones() {
364 synchronized (sones) {
365 return from(sones.values()).filter(new Predicate<Sone>() {
368 public boolean apply(Sone sone) {
369 return !sone.isLocal();
376 * Returns the remote Sone with the given ID.
379 * The ID of the remote Sone to get
380 * @return The Sone with the given ID
382 public Optional<Sone> getRemoteSone(String id) {
383 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
387 * Returns whether the given Sone has been modified.
390 * The Sone to check for modifications
391 * @return {@code true} if a modification has been detected in the Sone, {@code
394 public boolean isModifiedSone(Sone sone) {
395 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
399 * Returns the time when the given was first followed by any local Sone.
402 * The Sone to get the time for
403 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
404 * followed, or {@link Long#MAX_VALUE}
406 public long getSoneFollowingTime(Sone sone) {
407 synchronized (soneFollowingTimes) {
408 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
413 * Returns all Sones that have liked the given post.
416 * The post to get the liking Sones for
417 * @return The Sones that like the given post
419 public Set<Sone> getLikes(Post post) {
420 Set<Sone> sones = new HashSet<Sone>();
421 for (Sone sone : getSones()) {
422 if (sone.getLikedPostIds().contains(post.getId())) {
430 * Returns all Sones that have liked the given reply.
433 * The reply to get the liking Sones for
434 * @return The Sones that like the given reply
436 public Set<Sone> getLikes(PostReply reply) {
437 Set<Sone> sones = new HashSet<Sone>();
438 for (Sone sone : getSones()) {
439 if (sone.getLikedReplyIds().contains(reply.getId())) {
447 * Returns whether the given post is bookmarked.
451 * @return {@code true} if the given post is bookmarked, {@code false}
454 public boolean isBookmarked(Post post) {
455 return isPostBookmarked(post.getId());
459 * Returns whether the post with the given ID is bookmarked.
462 * The ID of the post to check
463 * @return {@code true} if the post with the given ID is bookmarked, {@code
466 public boolean isPostBookmarked(String id) {
467 synchronized (bookmarkedPosts) {
468 return bookmarkedPosts.contains(id);
473 * Returns all currently known bookmarked posts.
475 * @return All bookmarked posts
477 public Set<Post> getBookmarkedPosts() {
478 Set<Post> posts = new HashSet<Post>();
479 synchronized (bookmarkedPosts) {
480 for (String bookmarkedPostId : bookmarkedPosts) {
481 Optional<Post> post = database.getPost(bookmarkedPostId);
482 if (post.isPresent()) {
483 posts.add(post.get());
490 public Optional<Album> getAlbum(String albumId) {
491 return database.getAlbum(albumId);
494 public Optional<Image> getImage(String imageId) {
495 return database.getImage(imageId);
499 * Returns the temporary image with the given ID.
502 * The ID of the temporary image
503 * @return The temporary image, or {@code null} if there is no temporary image
506 public TemporaryImage getTemporaryImage(String imageId) {
507 synchronized (temporaryImages) {
508 return temporaryImages.get(imageId);
517 * Locks the given Sone. A locked Sone will not be inserted by {@link
518 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
523 public void lockSone(Sone sone) {
524 synchronized (lockedSones) {
525 if (lockedSones.add(sone)) {
526 eventBus.post(new SoneLockedEvent(sone));
532 * Unlocks the given Sone.
536 * @see #lockSone(Sone)
538 public void unlockSone(Sone sone) {
539 synchronized (lockedSones) {
540 if (lockedSones.remove(sone)) {
541 eventBus.post(new SoneUnlockedEvent(sone));
547 * Adds a local Sone from the given own identity.
550 * The own identity to create a Sone from
551 * @return The added (or already existing) Sone
553 public Sone addLocalSone(OwnIdentity ownIdentity) {
554 if (ownIdentity == null) {
555 logger.log(Level.WARNING, "Given OwnIdentity is null!");
558 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
559 synchronized (sones) {
562 sone = database.newSoneBuilder().by(ownIdentity.getId()).local().build(Optional.<SoneCreated>absent()).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
563 } catch (MalformedURLException mue1) {
564 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
567 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
568 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
570 /* TODO - load posts ’n stuff */
571 sones.put(ownIdentity.getId(), sone);
572 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
573 soneInserters.put(sone, soneInserter);
574 sone.setStatus(SoneStatus.idle);
576 soneInserter.start();
582 * Creates a new Sone for the given own identity.
585 * The own identity to create a Sone for
586 * @return The created Sone
588 public Sone createSone(OwnIdentity ownIdentity) {
589 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
590 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
593 Sone sone = addLocalSone(ownIdentity);
594 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
595 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
596 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
597 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
598 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
599 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
601 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
602 touchConfiguration();
607 * Adds the Sone of the given identity.
610 * The identity whose Sone to add
611 * @return The added or already existing Sone
613 public Sone addRemoteSone(Identity identity) {
614 if (identity == null) {
615 logger.log(Level.WARNING, "Given Identity is null!");
618 synchronized (sones) {
619 final Sone sone = database.newSoneBuilder().by(identity.getId()).build(Optional.<SoneCreated>absent());
620 if (sone.isLocal()) {
623 boolean newSone = sone.getRequestUri() == null;
624 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
625 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
627 synchronized (knownSones) {
628 newSone = !knownSones.contains(sone.getId());
630 sone.setKnown(!newSone);
632 eventBus.post(new NewSoneFoundEvent(sone));
633 for (Sone localSone : getLocalSones()) {
634 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
635 followSone(localSone, sone.getId());
640 soneDownloader.addSone(sone);
641 soneDownloaders.execute(new Runnable() {
644 @SuppressWarnings("synthetic-access")
646 soneDownloader.fetchSone(sone, sone.getRequestUri());
655 * Lets the given local Sone follow the Sone with the given ID.
658 * The local Sone that should follow another Sone
660 * The ID of the Sone to follow
662 public void followSone(Sone sone, String soneId) {
663 checkNotNull(sone, "sone must not be null");
664 checkNotNull(soneId, "soneId must not be null");
665 sone.addFriend(soneId);
666 synchronized (soneFollowingTimes) {
667 if (!soneFollowingTimes.containsKey(soneId)) {
668 long now = System.currentTimeMillis();
669 soneFollowingTimes.put(soneId, now);
670 Optional<Sone> followedSone = getSone(soneId);
671 if (!followedSone.isPresent()) {
674 for (Post post : followedSone.get().getPosts()) {
675 if (post.getTime() < now) {
679 for (PostReply reply : followedSone.get().getReplies()) {
680 if (reply.getTime() < now) {
681 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
686 touchConfiguration();
690 * Lets the given local Sone unfollow the Sone with the given ID.
693 * The local Sone that should unfollow another Sone
695 * The ID of the Sone being unfollowed
697 public void unfollowSone(Sone sone, String soneId) {
698 checkNotNull(sone, "sone must not be null");
699 checkNotNull(soneId, "soneId must not be null");
700 sone.removeFriend(soneId);
701 boolean unfollowedSoneStillFollowed = false;
702 for (Sone localSone : getLocalSones()) {
703 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
705 if (!unfollowedSoneStillFollowed) {
706 synchronized (soneFollowingTimes) {
707 soneFollowingTimes.remove(soneId);
710 touchConfiguration();
714 * Sets the trust value of the given origin Sone for the target Sone.
721 * The trust value (from {@code -100} to {@code 100})
723 public void setTrust(Sone origin, Sone target, int trustValue) {
724 checkNotNull(origin, "origin must not be null");
725 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
726 checkNotNull(target, "target must not be null");
727 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
728 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
732 * Removes any trust assignment for the given target Sone.
739 public void removeTrust(Sone origin, Sone target) {
740 checkNotNull(origin, "origin must not be null");
741 checkNotNull(target, "target must not be null");
742 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
743 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
747 * Assigns the configured positive trust value for the given target.
754 public void trustSone(Sone origin, Sone target) {
755 setTrust(origin, target, preferences.getPositiveTrust());
759 * Assigns the configured negative trust value for the given target.
766 public void distrustSone(Sone origin, Sone target) {
767 setTrust(origin, target, preferences.getNegativeTrust());
771 * Removes the trust assignment for the given target.
778 public void untrustSone(Sone origin, Sone target) {
779 removeTrust(origin, target);
783 * Updates the stored Sone with the given Sone.
788 public void updateSone(Sone sone) {
789 updateSone(sone, false);
793 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
794 * {@code true}, an older Sone than the current Sone can be given to restore an
799 * @param soneRescueMode
800 * {@code true} if the stored Sone should be updated regardless of the age of
803 public void updateSone(Sone sone, boolean soneRescueMode) {
804 Optional<Sone> storedSone = getSone(sone.getId());
805 if (storedSone.isPresent()) {
806 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
807 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
810 /* find removed posts. */
811 Collection<Post> existingPosts = database.getPosts(sone.getId());
812 for (Post oldPost : existingPosts) {
813 if (!sone.getPosts().contains(oldPost)) {
814 eventBus.post(new PostRemovedEvent(oldPost));
817 /* find new posts. */
818 for (Post newPost : sone.getPosts()) {
819 if (existingPosts.contains(newPost)) {
822 if (newPost.getTime() < getSoneFollowingTime(sone)) {
823 newPost.setKnown(true);
824 } else if (!newPost.isKnown()) {
825 eventBus.post(new NewPostFoundEvent(newPost));
829 database.storePosts(sone, sone.getPosts());
830 if (!soneRescueMode) {
831 for (PostReply reply : storedSone.get().getReplies()) {
832 if (!sone.getReplies().contains(reply)) {
833 eventBus.post(new PostReplyRemovedEvent(reply));
837 Set<PostReply> storedReplies = storedSone.get().getReplies();
838 for (PostReply reply : sone.getReplies()) {
839 if (storedReplies.contains(reply)) {
842 if (reply.getTime() < getSoneFollowingTime(sone)) {
843 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
844 } else if (!reply.isKnown()) {
845 eventBus.post(new NewPostReplyFoundEvent(reply));
848 database.storePostReplies(sone, sone.getReplies());
849 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
850 database.removeAlbum(album);
851 for (Image image : album.getImages()) {
852 database.removeImage(image);
855 for (Album album : sone.getRootAlbum().getAlbums()) {
856 database.storeAlbum(album);
857 for (Image image : album.getImages()) {
858 database.storeImage(image);
861 synchronized (sones) {
862 sone.setOptions(storedSone.get().getOptions());
863 sone.setKnown(storedSone.get().isKnown());
864 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
865 if (sone.isLocal()) {
866 soneInserters.get(storedSone.get()).setSone(sone);
867 touchConfiguration();
869 sones.put(sone.getId(), sone);
875 * Deletes the given Sone. This will remove the Sone from the {@link
876 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
877 * context from its identity.
882 public void deleteSone(Sone sone) {
883 if (!(sone.getIdentity() instanceof OwnIdentity)) {
884 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
887 synchronized (sones) {
888 if (!getLocalSones().contains(sone)) {
889 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
892 sones.remove(sone.getId());
893 SoneInserter soneInserter = soneInserters.remove(sone);
896 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
897 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
899 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
900 } catch (ConfigurationException ce1) {
901 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
906 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
907 * known} before, a {@link MarkSoneKnownEvent} is fired.
910 * The Sone to mark as known
912 public void markSoneKnown(Sone sone) {
913 if (!sone.isKnown()) {
915 synchronized (knownSones) {
916 knownSones.add(sone.getId());
918 eventBus.post(new MarkSoneKnownEvent(sone));
919 touchConfiguration();
924 * Loads and updates the given Sone from the configuration. If any error is
925 * encountered, loading is aborted and the given Sone is not changed.
928 * The Sone to load and update
930 public void loadSone(Sone sone) {
931 if (!sone.isLocal()) {
932 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
935 logger.info(String.format("Loading local Sone: %s", sone));
937 /* initialize options. */
938 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
939 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
940 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
941 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
942 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
943 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
946 String sonePrefix = "Sone/" + sone.getId();
947 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
948 if (soneTime == null) {
949 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
952 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
955 Profile profile = new Profile(sone);
956 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
957 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
958 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
959 profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
960 Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
961 Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
962 Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
963 profile.modify().setBirthYear(birthYear).setBirthMonth(birthMonth).setBirthDay(birthDay).update();
965 /* load profile fields. */
967 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
968 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
969 if (fieldName == null) {
972 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
973 profile.addField(fieldName).setValue(fieldValue);
977 Set<Post> posts = new HashSet<Post>();
979 String postPrefix = sonePrefix + "/Posts/" + posts.size();
980 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
981 if (postId == null) {
984 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
985 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
986 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
987 if ((postTime == 0) || (postText == null)) {
988 logger.log(Level.WARNING, "Invalid post found, aborting load!");
991 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
992 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
993 postBuilder.to(of(postRecipientId));
995 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
999 Set<PostReply> replies = new HashSet<PostReply>();
1001 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1002 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1003 if (replyId == null) {
1006 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1007 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1008 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1009 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1010 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1013 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1014 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1017 /* load post likes. */
1018 Set<String> likedPostIds = new HashSet<String>();
1020 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1021 if (likedPostId == null) {
1024 likedPostIds.add(likedPostId);
1027 /* load reply likes. */
1028 Set<String> likedReplyIds = new HashSet<String>();
1030 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1031 if (likedReplyId == null) {
1034 likedReplyIds.add(likedReplyId);
1038 Set<String> friends = new HashSet<String>();
1040 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1041 if (friendId == null) {
1044 friends.add(friendId);
1048 Map<String, Album> albums = Maps.newHashMap();
1049 int albumCounter = 0;
1051 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1052 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1053 if (albumId == null) {
1056 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1057 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1058 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1059 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1060 if ((albumTitle == null) || (albumDescription == null)) {
1061 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1064 Album parentAlbum = sone.getRootAlbum();
1065 if (albumParentId != null) {
1066 parentAlbum = albums.get(albumParentId);
1068 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1069 albums.put(album.getId(), album);
1073 int imageCounter = 0;
1075 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1076 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1077 if (imageId == null) {
1080 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1081 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1082 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1083 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1084 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1085 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1086 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1087 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1088 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1091 Album album = albums.get(albumId);
1092 if (album == null) {
1093 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1096 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1100 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1101 if (avatarId != null) {
1102 profile.setAvatar(getImage(avatarId).orNull());
1106 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1107 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1108 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1109 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1110 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1111 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1113 /* if we’re still here, Sone was loaded successfully. */
1114 synchronized (sone) {
1115 sone.setTime(soneTime);
1116 sone.setProfile(profile);
1117 sone.setPosts(posts);
1118 sone.setReplies(replies);
1119 sone.setLikePostIds(likedPostIds);
1120 sone.setLikeReplyIds(likedReplyIds);
1121 for (String friendId : friends) {
1122 followSone(sone, friendId);
1124 for (Album album : sone.getRootAlbum().getAlbums()) {
1127 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1129 synchronized (knownSones) {
1130 for (String friend : friends) {
1131 knownSones.add(friend);
1134 database.storePosts(sone, posts);
1135 for (Post post : posts) {
1136 post.setKnown(true);
1138 database.storePostReplies(sone, replies);
1139 for (PostReply reply : replies) {
1140 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
1143 logger.info(String.format("Sone loaded successfully: %s", sone));
1147 * Deletes the given post.
1150 * The post to delete
1152 public void deletePost(Post post) {
1153 if (!post.getSone().isLocal()) {
1154 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1157 database.removePost(post);
1158 eventBus.post(new PostRemovedEvent(post));
1159 markPostKnown(post);
1160 touchConfiguration();
1164 * Marks the given post as known, if it is currently not a known post
1165 * (according to {@link Post#isKnown()}).
1168 * The post to mark as known
1170 public void markPostKnown(Post post) {
1171 post.setKnown(true);
1172 eventBus.post(new MarkPostKnownEvent(post));
1173 touchConfiguration();
1174 for (PostReply reply : post.getReplies()) {
1175 reply.modify().setKnown().update(postReplyUpdated());
1180 * Bookmarks the post with the given ID.
1183 * The ID of the post to bookmark
1185 public void bookmarkPost(String id) {
1186 synchronized (bookmarkedPosts) {
1187 bookmarkedPosts.add(id);
1192 * Removes the given post from the bookmarks.
1195 * The post to unbookmark
1197 public void unbookmark(Post post) {
1198 unbookmarkPost(post.getId());
1202 * Removes the post with the given ID from the bookmarks.
1205 * The ID of the post to unbookmark
1207 public void unbookmarkPost(String id) {
1208 synchronized (bookmarkedPosts) {
1209 bookmarkedPosts.remove(id);
1214 * Deletes the given reply.
1217 * The reply to delete
1219 public void deleteReply(PostReply reply) {
1220 Sone sone = reply.getSone();
1221 if (!sone.isLocal()) {
1222 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1225 postReplyUpdated().get().replyUpdated(reply);
1226 database.removePostReply(reply);
1227 touchConfiguration();
1231 * Creates a new image.
1234 * The Sone creating the image
1236 * The album the image will be inserted into
1237 * @param temporaryImage
1238 * The temporary image to create the image from
1239 * @return The newly created image
1241 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1242 checkNotNull(sone, "sone must not be null");
1243 checkNotNull(album, "album must not be null");
1244 checkNotNull(temporaryImage, "temporaryImage must not be null");
1245 checkArgument(sone.isLocal(), "sone must be a local Sone");
1246 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1247 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1248 imageInserter.insertImage(temporaryImage, image);
1253 * Deletes the given image. This method will also delete a matching temporary
1257 * The image to delete
1258 * @see #deleteTemporaryImage(String)
1260 public void deleteImage(Image image) {
1261 checkNotNull(image, "image must not be null");
1262 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1263 deleteTemporaryImage(image.getId());
1265 touchConfiguration();
1269 * Creates a new temporary image.
1272 * The MIME type of the temporary image
1274 * The encoded data of the image
1275 * @return The temporary image
1277 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1278 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1279 synchronized (temporaryImages) {
1280 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1282 return temporaryImage;
1286 * Deletes the temporary image with the given ID.
1289 * The ID of the temporary image to delete
1291 public void deleteTemporaryImage(String imageId) {
1292 checkNotNull(imageId, "imageId must not be null");
1293 synchronized (temporaryImages) {
1294 temporaryImages.remove(imageId);
1296 Optional<Image> image = getImage(imageId);
1297 if (image.isPresent()) {
1298 imageInserter.cancelImageInsert(image.get());
1303 * Notifies the core that the configuration, either of the core or of a single
1304 * local Sone, has changed, and that the configuration should be saved.
1306 public void touchConfiguration() {
1307 lastConfigurationUpdate = System.currentTimeMillis();
1315 public void serviceStart() {
1316 loadConfiguration();
1317 updateChecker.start();
1318 identityManager.start();
1319 webOfTrustUpdater.init();
1320 webOfTrustUpdater.start();
1325 public void serviceRun() {
1326 long lastSaved = System.currentTimeMillis();
1327 while (!shouldStop()) {
1329 long now = System.currentTimeMillis();
1330 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1331 for (Sone localSone : getLocalSones()) {
1332 saveSone(localSone);
1334 saveConfiguration();
1341 public void serviceStop() {
1342 localElementTicker.shutdownNow();
1343 synchronized (sones) {
1344 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1345 soneInserter.getValue().stop();
1346 saveSone(soneInserter.getKey());
1349 saveConfiguration();
1351 webOfTrustUpdater.stop();
1352 updateChecker.stop();
1353 soneDownloader.stop();
1354 soneDownloaders.shutdown();
1355 identityManager.stop();
1363 * Saves the given Sone. This will persist all local settings for the given
1364 * Sone, such as the friends list and similar, private options.
1369 private synchronized void saveSone(Sone sone) {
1370 if (!sone.isLocal()) {
1371 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1374 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1375 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1379 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1381 /* save Sone into configuration. */
1382 String sonePrefix = "Sone/" + sone.getId();
1383 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1384 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1387 Profile profile = sone.getProfile();
1388 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1389 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1390 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1391 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1392 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1393 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1394 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1396 /* save profile fields. */
1397 int fieldCounter = 0;
1398 for (Field profileField : profile.getFields()) {
1399 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1400 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1401 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1403 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1406 int postCounter = 0;
1407 for (Post post : sone.getPosts()) {
1408 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1409 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1410 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1411 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1412 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1414 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1417 int replyCounter = 0;
1418 for (PostReply reply : sone.getReplies()) {
1419 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1420 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1421 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1422 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1423 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1425 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1427 /* save post likes. */
1428 int postLikeCounter = 0;
1429 for (String postId : sone.getLikedPostIds()) {
1430 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1432 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1434 /* save reply likes. */
1435 int replyLikeCounter = 0;
1436 for (String replyId : sone.getLikedReplyIds()) {
1437 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1439 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1442 int friendCounter = 0;
1443 for (String friendId : sone.getFriends()) {
1444 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1446 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1448 /* save albums. first, collect in a flat structure, top-level first. */
1449 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1451 int albumCounter = 0;
1452 for (Album album : albums) {
1453 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1454 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1455 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1456 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1457 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1458 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1460 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1463 int imageCounter = 0;
1464 for (Album album : albums) {
1465 for (Image image : album.getImages()) {
1466 if (!image.isInserted()) {
1469 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1470 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1471 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1472 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1473 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1474 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1475 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1476 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1477 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1480 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1483 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1484 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1485 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1486 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1487 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1488 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1490 configuration.save();
1492 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1494 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1495 } catch (ConfigurationException ce1) {
1496 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1500 /** Saves the current options. */
1501 private void saveConfiguration() {
1502 synchronized (configuration) {
1503 if (storingConfiguration) {
1504 logger.log(Level.FINE, "Already storing configuration…");
1507 storingConfiguration = true;
1510 /* store the options first. */
1512 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1513 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1514 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1515 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1516 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1517 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1518 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1519 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1520 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1521 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1522 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1523 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1525 /* save known Sones. */
1526 int soneCounter = 0;
1527 synchronized (knownSones) {
1528 for (String knownSoneId : knownSones) {
1529 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1531 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1534 /* save Sone following times. */
1536 synchronized (soneFollowingTimes) {
1537 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1538 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1539 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1542 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1545 /* save known posts. */
1548 /* save bookmarked posts. */
1549 int bookmarkedPostCounter = 0;
1550 synchronized (bookmarkedPosts) {
1551 for (String bookmarkedPostId : bookmarkedPosts) {
1552 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1555 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1558 configuration.save();
1560 } catch (ConfigurationException ce1) {
1561 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1562 } catch (DatabaseException de1) {
1563 logger.log(Level.SEVERE, "Could not save database!", de1);
1565 synchronized (configuration) {
1566 storingConfiguration = false;
1571 /** Loads the configuration. */
1572 private void loadConfiguration() {
1573 /* create options. */
1574 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1577 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1578 SoneInserter.setInsertionDelay(newValue);
1582 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1583 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1584 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1585 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1586 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1587 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1588 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1589 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1590 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1593 @SuppressWarnings("synthetic-access")
1594 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1595 fcpInterface.setActive(newValue);
1598 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1601 @SuppressWarnings("synthetic-access")
1602 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1603 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1608 loadConfigurationValue("InsertionDelay");
1609 loadConfigurationValue("PostsPerPage");
1610 loadConfigurationValue("ImagesPerPage");
1611 loadConfigurationValue("CharactersPerPost");
1612 loadConfigurationValue("PostCutOffLength");
1613 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1614 loadConfigurationValue("PositiveTrust");
1615 loadConfigurationValue("NegativeTrust");
1616 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1617 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1618 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1620 /* load known Sones. */
1621 int soneCounter = 0;
1623 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1624 if (knownSoneId == null) {
1627 synchronized (knownSones) {
1628 knownSones.add(knownSoneId);
1632 /* load Sone following times. */
1635 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1636 if (soneId == null) {
1639 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1640 synchronized (soneFollowingTimes) {
1641 soneFollowingTimes.put(soneId, time);
1646 /* load bookmarked posts. */
1647 int bookmarkedPostCounter = 0;
1649 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1650 if (bookmarkedPostId == null) {
1653 synchronized (bookmarkedPosts) {
1654 bookmarkedPosts.add(bookmarkedPostId);
1661 * Loads an {@link Integer} configuration value for the option with the given
1662 * name, logging validation failures.
1665 * The name of the option to load
1667 private void loadConfigurationValue(String optionName) {
1669 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1670 } catch (IllegalArgumentException iae1) {
1671 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1676 * Notifies the core that a new {@link OwnIdentity} was added.
1678 * @param ownIdentityAddedEvent
1682 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1683 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1684 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1685 if (ownIdentity.hasContext("Sone")) {
1686 addLocalSone(ownIdentity);
1691 * Notifies the core that an {@link OwnIdentity} was removed.
1693 * @param ownIdentityRemovedEvent
1697 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1698 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1699 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1700 trustedIdentities.removeAll(ownIdentity);
1704 * Notifies the core that a new {@link Identity} was added.
1706 * @param identityAddedEvent
1710 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1711 Identity identity = identityAddedEvent.identity();
1712 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1713 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1714 addRemoteSone(identity);
1718 * Notifies the core that an {@link Identity} was updated.
1720 * @param identityUpdatedEvent
1724 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1725 final Identity identity = identityUpdatedEvent.identity();
1726 soneDownloaders.execute(new Runnable() {
1729 @SuppressWarnings("synthetic-access")
1731 Optional<Sone> sone = getRemoteSone(identity.getId());
1732 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1733 soneDownloader.addSone(sone.get());
1734 soneDownloader.fetchSone(sone.get());
1740 * Notifies the core that an {@link Identity} was removed.
1742 * @param identityRemovedEvent
1746 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1747 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1748 Identity identity = identityRemovedEvent.identity();
1749 trustedIdentities.remove(ownIdentity, identity);
1750 boolean foundIdentity = false;
1751 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1752 if (trustedIdentity.getKey().equals(ownIdentity)) {
1755 if (trustedIdentity.getValue().contains(identity)) {
1756 foundIdentity = true;
1759 if (foundIdentity) {
1760 /* some local identity still trusts this identity, don’t remove. */
1763 Optional<Sone> sone = getSone(identity.getId());
1764 if (!sone.isPresent()) {
1765 /* TODO - we don’t have the Sone anymore. should this happen? */
1768 database.removePosts(sone.get());
1769 for (Post post : sone.get().getPosts()) {
1770 eventBus.post(new PostRemovedEvent(post));
1772 database.removePostReplies(sone.get());
1773 for (PostReply reply : sone.get().getReplies()) {
1774 eventBus.post(new PostReplyRemovedEvent(reply));
1776 synchronized (sones) {
1777 sones.remove(identity.getId());
1779 eventBus.post(new SoneRemovedEvent(sone.get()));
1783 * Deletes the temporary image.
1785 * @param imageInsertFinishedEvent
1789 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1790 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1791 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1792 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1793 touchConfiguration();
1796 public Optional<PostCreated> postCreated() {
1797 return Optional.<PostCreated>of(new PostCreated() {
1799 public void postCreated(final Post post) {
1800 if (post.isKnown()) {
1803 eventBus.post(new NewPostFoundEvent(post));
1804 if (post.getSone().isLocal()) {
1805 localElementTicker.schedule(new Runnable() {
1808 markPostKnown(post);
1810 }, 10, TimeUnit.SECONDS);
1816 public Optional<PostReplyCreated> postReplyCreated() {
1817 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1819 public void postReplyCreated(final PostReply postReply) {
1820 if (postReply.isKnown()) {
1823 eventBus.post(new NewPostReplyFoundEvent(postReply));
1824 if (postReply.getSone().isLocal()) {
1825 localElementTicker.schedule(new Runnable() {
1832 postReplyUpdated().get().replyUpdated(postReply);
1834 }, 10, TimeUnit.SECONDS);
1840 public Optional<ReplyUpdated<PostReply>> postReplyUpdated() {
1841 return Optional.<ReplyUpdated<PostReply>>of(new ReplyUpdated<PostReply>() {
1843 public void replyUpdated(PostReply reply) {
1844 eventBus.post(new MarkPostReplyKnownEvent(reply));
1849 public Optional<ImageCreated> imageCreated() {
1850 return Optional.<ImageCreated>of(new ImageCreated() {
1852 public void imageCreated(Image image) {
1853 /* nothing happens here yet. */