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 Optional<Sone> existingSone = database.getSone(identity.getId());
620 if (existingSone.isPresent() && existingSone.get().isLocal()) {
621 return existingSone.get();
623 boolean newSone = !existingSone.isPresent();
624 final Sone sone = newSone ? database.newSoneBuilder().by(identity.getId()).build(Optional.<SoneCreated>absent()) : existingSone.get();
625 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
626 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
628 synchronized (knownSones) {
629 newSone = !knownSones.contains(sone.getId());
631 sone.setKnown(!newSone);
633 eventBus.post(new NewSoneFoundEvent(sone));
634 for (Sone localSone : getLocalSones()) {
635 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
636 followSone(localSone, sone.getId());
641 soneDownloader.addSone(sone);
642 soneDownloaders.execute(new Runnable() {
645 @SuppressWarnings("synthetic-access")
647 soneDownloader.fetchSone(sone, sone.getRequestUri());
656 * Lets the given local Sone follow the Sone with the given ID.
659 * The local Sone that should follow another Sone
661 * The ID of the Sone to follow
663 public void followSone(Sone sone, String soneId) {
664 checkNotNull(sone, "sone must not be null");
665 checkNotNull(soneId, "soneId must not be null");
666 sone.addFriend(soneId);
667 synchronized (soneFollowingTimes) {
668 if (!soneFollowingTimes.containsKey(soneId)) {
669 long now = System.currentTimeMillis();
670 soneFollowingTimes.put(soneId, now);
671 Optional<Sone> followedSone = getSone(soneId);
672 if (!followedSone.isPresent()) {
675 for (Post post : followedSone.get().getPosts()) {
676 if (post.getTime() < now) {
680 for (PostReply reply : followedSone.get().getReplies()) {
681 if (reply.getTime() < now) {
682 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
687 touchConfiguration();
691 * Lets the given local Sone unfollow the Sone with the given ID.
694 * The local Sone that should unfollow another Sone
696 * The ID of the Sone being unfollowed
698 public void unfollowSone(Sone sone, String soneId) {
699 checkNotNull(sone, "sone must not be null");
700 checkNotNull(soneId, "soneId must not be null");
701 sone.removeFriend(soneId);
702 boolean unfollowedSoneStillFollowed = false;
703 for (Sone localSone : getLocalSones()) {
704 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
706 if (!unfollowedSoneStillFollowed) {
707 synchronized (soneFollowingTimes) {
708 soneFollowingTimes.remove(soneId);
711 touchConfiguration();
715 * Sets the trust value of the given origin Sone for the target Sone.
722 * The trust value (from {@code -100} to {@code 100})
724 public void setTrust(Sone origin, Sone target, int trustValue) {
725 checkNotNull(origin, "origin must not be null");
726 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
727 checkNotNull(target, "target must not be null");
728 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
729 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
733 * Removes any trust assignment for the given target Sone.
740 public void removeTrust(Sone origin, Sone target) {
741 checkNotNull(origin, "origin must not be null");
742 checkNotNull(target, "target must not be null");
743 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
744 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
748 * Assigns the configured positive trust value for the given target.
755 public void trustSone(Sone origin, Sone target) {
756 setTrust(origin, target, preferences.getPositiveTrust());
760 * Assigns the configured negative trust value for the given target.
767 public void distrustSone(Sone origin, Sone target) {
768 setTrust(origin, target, preferences.getNegativeTrust());
772 * Removes the trust assignment for the given target.
779 public void untrustSone(Sone origin, Sone target) {
780 removeTrust(origin, target);
784 * Updates the stored Sone with the given Sone.
789 public void updateSone(Sone sone) {
790 updateSone(sone, false);
794 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
795 * {@code true}, an older Sone than the current Sone can be given to restore an
800 * @param soneRescueMode
801 * {@code true} if the stored Sone should be updated regardless of the age of
804 public void updateSone(Sone sone, boolean soneRescueMode) {
805 Optional<Sone> storedSone = getSone(sone.getId());
806 if (storedSone.isPresent()) {
807 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
808 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
811 /* find removed posts. */
812 Collection<Post> existingPosts = database.getPosts(sone.getId());
813 for (Post oldPost : existingPosts) {
814 if (!sone.getPosts().contains(oldPost)) {
815 eventBus.post(new PostRemovedEvent(oldPost));
818 /* find new posts. */
819 for (Post newPost : sone.getPosts()) {
820 if (existingPosts.contains(newPost)) {
823 if (newPost.getTime() < getSoneFollowingTime(sone)) {
824 newPost.setKnown(true);
825 } else if (!newPost.isKnown()) {
826 eventBus.post(new NewPostFoundEvent(newPost));
830 database.storePosts(sone, sone.getPosts());
831 if (!soneRescueMode) {
832 for (PostReply reply : storedSone.get().getReplies()) {
833 if (!sone.getReplies().contains(reply)) {
834 eventBus.post(new PostReplyRemovedEvent(reply));
838 Set<PostReply> storedReplies = storedSone.get().getReplies();
839 for (PostReply reply : sone.getReplies()) {
840 if (storedReplies.contains(reply)) {
843 if (reply.getTime() < getSoneFollowingTime(sone)) {
844 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
845 } else if (!reply.isKnown()) {
846 eventBus.post(new NewPostReplyFoundEvent(reply));
849 database.storePostReplies(sone, sone.getReplies());
850 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
851 database.removeAlbum(album);
852 for (Image image : album.getImages()) {
853 database.removeImage(image);
856 for (Album album : sone.getRootAlbum().getAlbums()) {
857 database.storeAlbum(album);
858 for (Image image : album.getImages()) {
859 database.storeImage(image);
862 synchronized (sones) {
863 sone.setOptions(storedSone.get().getOptions());
864 sone.setKnown(storedSone.get().isKnown());
865 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
866 if (sone.isLocal()) {
867 soneInserters.get(storedSone.get()).setSone(sone);
868 touchConfiguration();
870 sones.put(sone.getId(), sone);
876 * Deletes the given Sone. This will remove the Sone from the {@link
877 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
878 * context from its identity.
883 public void deleteSone(Sone sone) {
884 if (!(sone.getIdentity() instanceof OwnIdentity)) {
885 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
888 synchronized (sones) {
889 if (!getLocalSones().contains(sone)) {
890 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
893 sones.remove(sone.getId());
894 SoneInserter soneInserter = soneInserters.remove(sone);
897 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
898 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
900 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
901 } catch (ConfigurationException ce1) {
902 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
907 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
908 * known} before, a {@link MarkSoneKnownEvent} is fired.
911 * The Sone to mark as known
913 public void markSoneKnown(Sone sone) {
914 if (!sone.isKnown()) {
916 synchronized (knownSones) {
917 knownSones.add(sone.getId());
919 eventBus.post(new MarkSoneKnownEvent(sone));
920 touchConfiguration();
925 * Loads and updates the given Sone from the configuration. If any error is
926 * encountered, loading is aborted and the given Sone is not changed.
929 * The Sone to load and update
931 public void loadSone(Sone sone) {
932 if (!sone.isLocal()) {
933 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
936 logger.info(String.format("Loading local Sone: %s", sone));
938 /* initialize options. */
939 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
940 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
941 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
942 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
943 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
944 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
947 String sonePrefix = "Sone/" + sone.getId();
948 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
949 if (soneTime == null) {
950 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
953 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
956 Profile profile = new Profile(sone);
957 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
958 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
959 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
960 profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
961 Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
962 Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
963 Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
964 profile.modify().setBirthYear(birthYear).setBirthMonth(birthMonth).setBirthDay(birthDay).update();
966 /* load profile fields. */
968 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
969 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
970 if (fieldName == null) {
973 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
974 profile.addField(fieldName).setValue(fieldValue);
978 Set<Post> posts = new HashSet<Post>();
980 String postPrefix = sonePrefix + "/Posts/" + posts.size();
981 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
982 if (postId == null) {
985 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
986 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
987 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
988 if ((postTime == 0) || (postText == null)) {
989 logger.log(Level.WARNING, "Invalid post found, aborting load!");
992 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
993 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
994 postBuilder.to(of(postRecipientId));
996 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
1000 Set<PostReply> replies = new HashSet<PostReply>();
1002 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1003 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1004 if (replyId == null) {
1007 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1008 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1009 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1010 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1011 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1014 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1015 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1018 /* load post likes. */
1019 Set<String> likedPostIds = new HashSet<String>();
1021 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1022 if (likedPostId == null) {
1025 likedPostIds.add(likedPostId);
1028 /* load reply likes. */
1029 Set<String> likedReplyIds = new HashSet<String>();
1031 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1032 if (likedReplyId == null) {
1035 likedReplyIds.add(likedReplyId);
1039 Set<String> friends = new HashSet<String>();
1041 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1042 if (friendId == null) {
1045 friends.add(friendId);
1049 Map<String, Album> albums = Maps.newHashMap();
1050 int albumCounter = 0;
1052 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1053 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1054 if (albumId == null) {
1057 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1058 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1059 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1060 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1061 if ((albumTitle == null) || (albumDescription == null)) {
1062 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1065 Album parentAlbum = sone.getRootAlbum();
1066 if (albumParentId != null) {
1067 parentAlbum = albums.get(albumParentId);
1069 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1070 albums.put(album.getId(), album);
1074 int imageCounter = 0;
1076 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1077 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1078 if (imageId == null) {
1081 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1082 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1083 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1084 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1085 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1086 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1087 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1088 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1089 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1092 Album album = albums.get(albumId);
1093 if (album == null) {
1094 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1097 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1101 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1102 if (avatarId != null) {
1103 profile.setAvatar(getImage(avatarId).orNull());
1107 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1108 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1109 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1110 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1111 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1112 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1114 /* if we’re still here, Sone was loaded successfully. */
1115 synchronized (sone) {
1116 sone.setTime(soneTime);
1117 sone.setProfile(profile);
1118 sone.setPosts(posts);
1119 sone.setReplies(replies);
1120 sone.setLikePostIds(likedPostIds);
1121 sone.setLikeReplyIds(likedReplyIds);
1122 for (String friendId : friends) {
1123 followSone(sone, friendId);
1125 for (Album album : sone.getRootAlbum().getAlbums()) {
1128 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1130 synchronized (knownSones) {
1131 for (String friend : friends) {
1132 knownSones.add(friend);
1135 database.storePosts(sone, posts);
1136 for (Post post : posts) {
1137 post.setKnown(true);
1139 database.storePostReplies(sone, replies);
1140 for (PostReply reply : replies) {
1141 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
1144 logger.info(String.format("Sone loaded successfully: %s", sone));
1148 * Deletes the given post.
1151 * The post to delete
1153 public void deletePost(Post post) {
1154 if (!post.getSone().isLocal()) {
1155 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1158 database.removePost(post);
1159 eventBus.post(new PostRemovedEvent(post));
1160 markPostKnown(post);
1161 touchConfiguration();
1165 * Marks the given post as known, if it is currently not a known post
1166 * (according to {@link Post#isKnown()}).
1169 * The post to mark as known
1171 public void markPostKnown(Post post) {
1172 post.setKnown(true);
1173 eventBus.post(new MarkPostKnownEvent(post));
1174 touchConfiguration();
1175 for (PostReply reply : post.getReplies()) {
1176 reply.modify().setKnown().update(postReplyUpdated());
1181 * Bookmarks the post with the given ID.
1184 * The ID of the post to bookmark
1186 public void bookmarkPost(String id) {
1187 synchronized (bookmarkedPosts) {
1188 bookmarkedPosts.add(id);
1193 * Removes the given post from the bookmarks.
1196 * The post to unbookmark
1198 public void unbookmark(Post post) {
1199 unbookmarkPost(post.getId());
1203 * Removes the post with the given ID from the bookmarks.
1206 * The ID of the post to unbookmark
1208 public void unbookmarkPost(String id) {
1209 synchronized (bookmarkedPosts) {
1210 bookmarkedPosts.remove(id);
1215 * Deletes the given reply.
1218 * The reply to delete
1220 public void deleteReply(PostReply reply) {
1221 Sone sone = reply.getSone();
1222 if (!sone.isLocal()) {
1223 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1226 postReplyUpdated().get().replyUpdated(reply);
1227 database.removePostReply(reply);
1228 touchConfiguration();
1232 * Creates a new image.
1235 * The Sone creating the image
1237 * The album the image will be inserted into
1238 * @param temporaryImage
1239 * The temporary image to create the image from
1240 * @return The newly created image
1242 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1243 checkNotNull(sone, "sone must not be null");
1244 checkNotNull(album, "album must not be null");
1245 checkNotNull(temporaryImage, "temporaryImage must not be null");
1246 checkArgument(sone.isLocal(), "sone must be a local Sone");
1247 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1248 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1249 imageInserter.insertImage(temporaryImage, image);
1254 * Deletes the given image. This method will also delete a matching temporary
1258 * The image to delete
1259 * @see #deleteTemporaryImage(String)
1261 public void deleteImage(Image image) {
1262 checkNotNull(image, "image must not be null");
1263 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1264 deleteTemporaryImage(image.getId());
1266 touchConfiguration();
1270 * Creates a new temporary image.
1273 * The MIME type of the temporary image
1275 * The encoded data of the image
1276 * @return The temporary image
1278 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1279 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1280 synchronized (temporaryImages) {
1281 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1283 return temporaryImage;
1287 * Deletes the temporary image with the given ID.
1290 * The ID of the temporary image to delete
1292 public void deleteTemporaryImage(String imageId) {
1293 checkNotNull(imageId, "imageId must not be null");
1294 synchronized (temporaryImages) {
1295 temporaryImages.remove(imageId);
1297 Optional<Image> image = getImage(imageId);
1298 if (image.isPresent()) {
1299 imageInserter.cancelImageInsert(image.get());
1304 * Notifies the core that the configuration, either of the core or of a single
1305 * local Sone, has changed, and that the configuration should be saved.
1307 public void touchConfiguration() {
1308 lastConfigurationUpdate = System.currentTimeMillis();
1316 public void serviceStart() {
1317 loadConfiguration();
1318 updateChecker.start();
1319 identityManager.start();
1320 webOfTrustUpdater.init();
1321 webOfTrustUpdater.start();
1326 public void serviceRun() {
1327 long lastSaved = System.currentTimeMillis();
1328 while (!shouldStop()) {
1330 long now = System.currentTimeMillis();
1331 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1332 for (Sone localSone : getLocalSones()) {
1333 saveSone(localSone);
1335 saveConfiguration();
1342 public void serviceStop() {
1343 localElementTicker.shutdownNow();
1344 synchronized (sones) {
1345 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1346 soneInserter.getValue().stop();
1347 saveSone(soneInserter.getKey());
1350 saveConfiguration();
1352 webOfTrustUpdater.stop();
1353 updateChecker.stop();
1354 soneDownloader.stop();
1355 soneDownloaders.shutdown();
1356 identityManager.stop();
1364 * Saves the given Sone. This will persist all local settings for the given
1365 * Sone, such as the friends list and similar, private options.
1370 private synchronized void saveSone(Sone sone) {
1371 if (!sone.isLocal()) {
1372 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1375 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1376 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1380 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1382 /* save Sone into configuration. */
1383 String sonePrefix = "Sone/" + sone.getId();
1384 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1385 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1388 Profile profile = sone.getProfile();
1389 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1390 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1391 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1392 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1393 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1394 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1395 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1397 /* save profile fields. */
1398 int fieldCounter = 0;
1399 for (Field profileField : profile.getFields()) {
1400 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1401 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1402 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1404 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1407 int postCounter = 0;
1408 for (Post post : sone.getPosts()) {
1409 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1410 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1411 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1412 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1413 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1415 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1418 int replyCounter = 0;
1419 for (PostReply reply : sone.getReplies()) {
1420 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1421 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1422 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1423 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1424 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1426 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1428 /* save post likes. */
1429 int postLikeCounter = 0;
1430 for (String postId : sone.getLikedPostIds()) {
1431 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1433 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1435 /* save reply likes. */
1436 int replyLikeCounter = 0;
1437 for (String replyId : sone.getLikedReplyIds()) {
1438 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1440 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1443 int friendCounter = 0;
1444 for (String friendId : sone.getFriends()) {
1445 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1447 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1449 /* save albums. first, collect in a flat structure, top-level first. */
1450 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1452 int albumCounter = 0;
1453 for (Album album : albums) {
1454 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1455 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1456 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1457 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1458 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1459 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1461 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1464 int imageCounter = 0;
1465 for (Album album : albums) {
1466 for (Image image : album.getImages()) {
1467 if (!image.isInserted()) {
1470 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1471 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1472 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1473 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1474 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1475 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1476 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1477 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1478 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1481 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1484 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1485 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1486 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1487 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1488 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1489 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1491 configuration.save();
1493 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1495 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1496 } catch (ConfigurationException ce1) {
1497 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1501 /** Saves the current options. */
1502 private void saveConfiguration() {
1503 synchronized (configuration) {
1504 if (storingConfiguration) {
1505 logger.log(Level.FINE, "Already storing configuration…");
1508 storingConfiguration = true;
1511 /* store the options first. */
1513 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1514 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1515 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1516 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1517 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1518 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1519 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1520 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1521 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1522 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1523 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1524 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1526 /* save known Sones. */
1527 int soneCounter = 0;
1528 synchronized (knownSones) {
1529 for (String knownSoneId : knownSones) {
1530 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1532 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1535 /* save Sone following times. */
1537 synchronized (soneFollowingTimes) {
1538 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1539 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1540 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1543 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1546 /* save known posts. */
1549 /* save bookmarked posts. */
1550 int bookmarkedPostCounter = 0;
1551 synchronized (bookmarkedPosts) {
1552 for (String bookmarkedPostId : bookmarkedPosts) {
1553 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1556 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1559 configuration.save();
1561 } catch (ConfigurationException ce1) {
1562 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1563 } catch (DatabaseException de1) {
1564 logger.log(Level.SEVERE, "Could not save database!", de1);
1566 synchronized (configuration) {
1567 storingConfiguration = false;
1572 /** Loads the configuration. */
1573 private void loadConfiguration() {
1574 /* create options. */
1575 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1578 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1579 SoneInserter.setInsertionDelay(newValue);
1583 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1584 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1585 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1586 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1587 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1588 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1589 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1590 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1591 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1594 @SuppressWarnings("synthetic-access")
1595 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1596 fcpInterface.setActive(newValue);
1599 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1602 @SuppressWarnings("synthetic-access")
1603 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1604 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1609 loadConfigurationValue("InsertionDelay");
1610 loadConfigurationValue("PostsPerPage");
1611 loadConfigurationValue("ImagesPerPage");
1612 loadConfigurationValue("CharactersPerPost");
1613 loadConfigurationValue("PostCutOffLength");
1614 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1615 loadConfigurationValue("PositiveTrust");
1616 loadConfigurationValue("NegativeTrust");
1617 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1618 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1619 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1621 /* load known Sones. */
1622 int soneCounter = 0;
1624 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1625 if (knownSoneId == null) {
1628 synchronized (knownSones) {
1629 knownSones.add(knownSoneId);
1633 /* load Sone following times. */
1636 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1637 if (soneId == null) {
1640 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1641 synchronized (soneFollowingTimes) {
1642 soneFollowingTimes.put(soneId, time);
1647 /* load bookmarked posts. */
1648 int bookmarkedPostCounter = 0;
1650 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1651 if (bookmarkedPostId == null) {
1654 synchronized (bookmarkedPosts) {
1655 bookmarkedPosts.add(bookmarkedPostId);
1662 * Loads an {@link Integer} configuration value for the option with the given
1663 * name, logging validation failures.
1666 * The name of the option to load
1668 private void loadConfigurationValue(String optionName) {
1670 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1671 } catch (IllegalArgumentException iae1) {
1672 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1677 * Notifies the core that a new {@link OwnIdentity} was added.
1679 * @param ownIdentityAddedEvent
1683 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1684 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1685 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1686 if (ownIdentity.hasContext("Sone")) {
1687 addLocalSone(ownIdentity);
1692 * Notifies the core that an {@link OwnIdentity} was removed.
1694 * @param ownIdentityRemovedEvent
1698 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1699 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1700 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1701 trustedIdentities.removeAll(ownIdentity);
1705 * Notifies the core that a new {@link Identity} was added.
1707 * @param identityAddedEvent
1711 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1712 Identity identity = identityAddedEvent.identity();
1713 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1714 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1715 addRemoteSone(identity);
1719 * Notifies the core that an {@link Identity} was updated.
1721 * @param identityUpdatedEvent
1725 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1726 final Identity identity = identityUpdatedEvent.identity();
1727 soneDownloaders.execute(new Runnable() {
1730 @SuppressWarnings("synthetic-access")
1732 Optional<Sone> sone = getRemoteSone(identity.getId());
1733 sone.get().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition()));
1734 soneDownloader.addSone(sone.get());
1735 soneDownloader.fetchSone(sone.get());
1741 * Notifies the core that an {@link Identity} was removed.
1743 * @param identityRemovedEvent
1747 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1748 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1749 Identity identity = identityRemovedEvent.identity();
1750 trustedIdentities.remove(ownIdentity, identity);
1751 boolean foundIdentity = false;
1752 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1753 if (trustedIdentity.getKey().equals(ownIdentity)) {
1756 if (trustedIdentity.getValue().contains(identity)) {
1757 foundIdentity = true;
1760 if (foundIdentity) {
1761 /* some local identity still trusts this identity, don’t remove. */
1764 Optional<Sone> sone = getSone(identity.getId());
1765 if (!sone.isPresent()) {
1766 /* TODO - we don’t have the Sone anymore. should this happen? */
1769 database.removePosts(sone.get());
1770 for (Post post : sone.get().getPosts()) {
1771 eventBus.post(new PostRemovedEvent(post));
1773 database.removePostReplies(sone.get());
1774 for (PostReply reply : sone.get().getReplies()) {
1775 eventBus.post(new PostReplyRemovedEvent(reply));
1777 synchronized (sones) {
1778 sones.remove(identity.getId());
1780 eventBus.post(new SoneRemovedEvent(sone.get()));
1784 * Deletes the temporary image.
1786 * @param imageInsertFinishedEvent
1790 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1791 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1792 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1793 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1794 touchConfiguration();
1797 public Optional<PostCreated> postCreated() {
1798 return Optional.<PostCreated>of(new PostCreated() {
1800 public void postCreated(final Post post) {
1801 if (post.isKnown()) {
1804 eventBus.post(new NewPostFoundEvent(post));
1805 if (post.getSone().isLocal()) {
1806 localElementTicker.schedule(new Runnable() {
1809 markPostKnown(post);
1811 }, 10, TimeUnit.SECONDS);
1817 public Optional<PostReplyCreated> postReplyCreated() {
1818 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1820 public void postReplyCreated(final PostReply postReply) {
1821 if (postReply.isKnown()) {
1824 eventBus.post(new NewPostReplyFoundEvent(postReply));
1825 if (postReply.getSone().isLocal()) {
1826 localElementTicker.schedule(new Runnable() {
1833 postReplyUpdated().get().replyUpdated(postReply);
1835 }, 10, TimeUnit.SECONDS);
1841 public Optional<ReplyUpdated<PostReply>> postReplyUpdated() {
1842 return Optional.<ReplyUpdated<PostReply>>of(new ReplyUpdated<PostReply>() {
1844 public void replyUpdated(PostReply reply) {
1845 eventBus.post(new MarkPostReplyKnownEvent(reply));
1850 public Optional<ImageCreated> imageCreated() {
1851 return Optional.<ImageCreated>of(new ImageCreated() {
1853 public void imageCreated(Image image) {
1854 /* nothing happens here yet. */