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;
28 import static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
30 import java.net.MalformedURLException;
31 import java.util.Collection;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
36 import java.util.Map.Entry;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.ScheduledExecutorService;
41 import java.util.concurrent.TimeUnit;
42 import java.util.logging.Level;
43 import java.util.logging.Logger;
45 import net.pterodactylus.sone.core.Options.DefaultOption;
46 import net.pterodactylus.sone.core.Options.Option;
47 import net.pterodactylus.sone.core.Options.OptionWatcher;
48 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
49 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
52 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
53 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
54 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
55 import net.pterodactylus.sone.core.event.PostRemovedEvent;
56 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneLockedEvent;
58 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
60 import net.pterodactylus.sone.data.Album;
61 import net.pterodactylus.sone.data.Client;
62 import net.pterodactylus.sone.data.Image;
63 import net.pterodactylus.sone.data.Post;
64 import net.pterodactylus.sone.data.PostReply;
65 import net.pterodactylus.sone.data.Profile;
66 import net.pterodactylus.sone.data.Profile.Field;
67 import net.pterodactylus.sone.data.Reply.Modifier.ReplyUpdated;
68 import net.pterodactylus.sone.data.Sone;
69 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
70 import net.pterodactylus.sone.data.Sone.SoneStatus;
71 import net.pterodactylus.sone.data.TemporaryImage;
72 import net.pterodactylus.sone.database.Database;
73 import net.pterodactylus.sone.database.DatabaseException;
74 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
75 import net.pterodactylus.sone.database.PostBuilder;
76 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
77 import net.pterodactylus.sone.database.PostReplyBuilder;
78 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
79 import net.pterodactylus.sone.database.SoneBuilder.SoneCreated;
80 import net.pterodactylus.sone.database.SoneProvider;
81 import net.pterodactylus.sone.fcp.FcpInterface;
82 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
83 import net.pterodactylus.sone.freenet.wot.Identity;
84 import net.pterodactylus.sone.freenet.wot.IdentityManager;
85 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
91 import net.pterodactylus.sone.main.SonePlugin;
92 import net.pterodactylus.sone.utils.IntegerRangePredicate;
93 import net.pterodactylus.util.config.Configuration;
94 import net.pterodactylus.util.config.ConfigurationException;
95 import net.pterodactylus.util.logging.Logging;
96 import net.pterodactylus.util.number.Numbers;
97 import net.pterodactylus.util.service.AbstractService;
98 import net.pterodactylus.util.thread.NamedThreadFactory;
100 import freenet.keys.FreenetURI;
102 import com.google.common.base.Optional;
103 import com.google.common.base.Predicate;
104 import com.google.common.base.Predicates;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.ImmutableSet;
107 import com.google.common.collect.Maps;
108 import com.google.common.collect.Multimap;
109 import com.google.common.collect.Multimaps;
110 import com.google.common.eventbus.EventBus;
111 import com.google.common.eventbus.Subscribe;
112 import com.google.inject.Inject;
117 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
119 public class Core extends AbstractService implements SoneProvider {
122 private static final Logger logger = Logging.getLogger(Core.class);
125 private final Options options = new Options();
127 /** The preferences. */
128 private final Preferences preferences = new Preferences(options);
130 /** The event bus. */
131 private final EventBus eventBus;
133 /** The configuration. */
134 private Configuration configuration;
136 /** Whether we’re currently saving the configuration. */
137 private boolean storingConfiguration = false;
139 /** The identity manager. */
140 private final IdentityManager identityManager;
142 /** Interface to freenet. */
143 private final FreenetInterface freenetInterface;
145 /** The Sone downloader. */
146 private final SoneDownloader soneDownloader;
148 /** The image inserter. */
149 private final ImageInserter imageInserter;
151 /** Sone downloader thread-pool. */
152 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154 /** The update checker. */
155 private final UpdateChecker updateChecker;
157 /** The trust updater. */
158 private final WebOfTrustUpdater webOfTrustUpdater;
160 /** The FCP interface. */
161 private volatile FcpInterface fcpInterface;
163 /** The times Sones were followed. */
164 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
166 /** Locked local Sones. */
167 /* synchronize on itself. */
168 private final Set<Sone> lockedSones = new HashSet<Sone>();
170 /** Sone inserters. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
174 /** Sone rescuers. */
175 /* synchronize access on this on sones. */
176 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
179 /* synchronize access on this on itself. */
180 private final Map<String, Sone> sones = new HashMap<String, Sone>();
182 /** All known Sones. */
183 private final Set<String> knownSones = new HashSet<String>();
185 /** The post database. */
186 private final Database database;
188 /** All bookmarked posts. */
189 /* synchronize access on itself. */
190 private final Set<String> bookmarkedPosts = new HashSet<String>();
192 /** Trusted identities, sorted by own identities. */
193 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
195 /** All temporary images. */
196 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
198 /** Ticker for threads that mark own elements as known. */
199 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
201 /** The time the configuration was last touched. */
202 private volatile long lastConfigurationUpdate;
205 * Creates a new core.
207 * @param configuration
208 * The configuration of the core
209 * @param freenetInterface
210 * The freenet interface
211 * @param identityManager
212 * The identity manager
213 * @param webOfTrustUpdater
214 * The WebOfTrust updater
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloader(this, freenetInterface);
227 this.imageInserter = new ImageInserter(freenetInterface);
228 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
231 this.database = database;
239 * Sets the configuration to use. This will automatically save the current
240 * configuration to the given configuration.
242 * @param configuration
243 * The new configuration to use
245 public void setConfiguration(Configuration configuration) {
246 this.configuration = configuration;
247 touchConfiguration();
251 * Returns the options used by the core.
253 * @return The options of the core
255 public Preferences getPreferences() {
260 * Returns the identity manager used by the core.
262 * @return The identity manager
264 public IdentityManager getIdentityManager() {
265 return identityManager;
269 * Returns the update checker.
271 * @return The update checker
273 public UpdateChecker getUpdateChecker() {
274 return updateChecker;
278 * Sets the FCP interface to use.
280 * @param fcpInterface
281 * The FCP interface to use
283 public void setFcpInterface(FcpInterface fcpInterface) {
284 this.fcpInterface = fcpInterface;
287 public Database getDatabase() {
292 * Returns the Sone rescuer for the given local Sone.
295 * The local Sone to get the rescuer for
296 * @return The Sone rescuer for the given Sone
298 public SoneRescuer getSoneRescuer(Sone sone) {
299 checkNotNull(sone, "sone must not be null");
300 checkArgument(sone.isLocal(), "sone must be local");
301 synchronized (sones) {
302 SoneRescuer soneRescuer = soneRescuers.get(sone);
303 if (soneRescuer == null) {
304 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
305 soneRescuers.put(sone, soneRescuer);
313 * Returns whether the given Sone is currently locked.
317 * @return {@code true} if the Sone is locked, {@code false} if it is not
319 public boolean isLocked(Sone sone) {
320 synchronized (lockedSones) {
321 return lockedSones.contains(sone);
326 public Collection<Sone> getSones() {
327 synchronized (sones) {
328 return ImmutableSet.copyOf(sones.values());
333 public Optional<Sone> getSone(String id) {
334 synchronized (sones) {
335 return Optional.fromNullable(sones.get(id));
340 public Collection<Sone> getLocalSones() {
341 synchronized (sones) {
342 return from(sones.values()).filter(new Predicate<Sone>() {
345 public boolean apply(Sone sone) {
346 return sone.isLocal();
353 * Returns the local Sone with the given ID, optionally creating a new Sone.
357 * @return The Sone with the given ID, or {@code null}
359 public Optional<Sone> getLocalSone(String id) {
360 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
364 public Collection<Sone> getRemoteSones() {
365 synchronized (sones) {
366 return from(sones.values()).filter(new Predicate<Sone>() {
369 public boolean apply(Sone sone) {
370 return !sone.isLocal();
377 * Returns the remote Sone with the given ID.
380 * The ID of the remote Sone to get
381 * @return The Sone with the given ID
383 public Optional<Sone> getRemoteSone(String id) {
384 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
388 * Returns whether the given Sone has been modified.
391 * The Sone to check for modifications
392 * @return {@code true} if a modification has been detected in the Sone, {@code
395 public boolean isModifiedSone(Sone sone) {
396 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
400 * Returns the time when the given was first followed by any local Sone.
403 * The Sone to get the time for
404 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
405 * followed, or {@link Long#MAX_VALUE}
407 public long getSoneFollowingTime(Sone sone) {
408 synchronized (soneFollowingTimes) {
409 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
414 * Returns all Sones that have liked the given post.
417 * The post to get the liking Sones for
418 * @return The Sones that like the given post
420 public Set<Sone> getLikes(Post post) {
421 Set<Sone> sones = new HashSet<Sone>();
422 for (Sone sone : getSones()) {
423 if (sone.getLikedPostIds().contains(post.getId())) {
431 * Returns all Sones that have liked the given reply.
434 * The reply to get the liking Sones for
435 * @return The Sones that like the given reply
437 public Set<Sone> getLikes(PostReply reply) {
438 Set<Sone> sones = new HashSet<Sone>();
439 for (Sone sone : getSones()) {
440 if (sone.getLikedReplyIds().contains(reply.getId())) {
448 * Returns whether the given post is bookmarked.
452 * @return {@code true} if the given post is bookmarked, {@code false}
455 public boolean isBookmarked(Post post) {
456 return isPostBookmarked(post.getId());
460 * Returns whether the post with the given ID is bookmarked.
463 * The ID of the post to check
464 * @return {@code true} if the post with the given ID is bookmarked, {@code
467 public boolean isPostBookmarked(String id) {
468 synchronized (bookmarkedPosts) {
469 return bookmarkedPosts.contains(id);
474 * Returns all currently known bookmarked posts.
476 * @return All bookmarked posts
478 public Set<Post> getBookmarkedPosts() {
479 Set<Post> posts = new HashSet<Post>();
480 synchronized (bookmarkedPosts) {
481 for (String bookmarkedPostId : bookmarkedPosts) {
482 Optional<Post> post = database.getPost(bookmarkedPostId);
483 if (post.isPresent()) {
484 posts.add(post.get());
491 public Optional<Album> getAlbum(String albumId) {
492 return database.getAlbum(albumId);
495 public Optional<Image> getImage(String imageId) {
496 return database.getImage(imageId);
500 * Returns the temporary image with the given ID.
503 * The ID of the temporary image
504 * @return The temporary image, or {@code null} if there is no temporary image
507 public TemporaryImage getTemporaryImage(String imageId) {
508 synchronized (temporaryImages) {
509 return temporaryImages.get(imageId);
518 * Locks the given Sone. A locked Sone will not be inserted by {@link
519 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
524 public void lockSone(Sone sone) {
525 synchronized (lockedSones) {
526 if (lockedSones.add(sone)) {
527 eventBus.post(new SoneLockedEvent(sone));
533 * Unlocks the given Sone.
537 * @see #lockSone(Sone)
539 public void unlockSone(Sone sone) {
540 synchronized (lockedSones) {
541 if (lockedSones.remove(sone)) {
542 eventBus.post(new SoneUnlockedEvent(sone));
548 * Adds a local Sone from the given own identity.
551 * The own identity to create a Sone from
552 * @return The added (or already existing) Sone
554 public Sone addLocalSone(OwnIdentity ownIdentity) {
555 if (ownIdentity == null) {
556 logger.log(Level.WARNING, "Given OwnIdentity is null!");
559 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
560 synchronized (sones) {
562 sone = database.newSoneBuilder().by(ownIdentity.getId()).local().using(new Client("Sone", SonePlugin.VERSION.toString())).build(Optional.<SoneCreated>absent());
563 sone.modify().setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0)).update();
565 /* TODO - load posts ’n stuff */
566 sones.put(ownIdentity.getId(), sone);
567 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
568 soneInserters.put(sone, soneInserter);
569 sone.setStatus(SoneStatus.idle);
571 soneInserter.start();
577 * Creates a new Sone for the given own identity.
580 * The own identity to create a Sone for
581 * @return The created Sone
583 public Sone createSone(OwnIdentity ownIdentity) {
584 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
585 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
588 Sone sone = addLocalSone(ownIdentity);
589 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
590 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
591 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
592 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
593 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
594 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
596 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
597 touchConfiguration();
602 * Adds the Sone of the given identity.
605 * The identity whose Sone to add
606 * @return The added or already existing Sone
608 public Sone addRemoteSone(Identity identity) {
609 if (identity == null) {
610 logger.log(Level.WARNING, "Given Identity is null!");
613 synchronized (sones) {
614 Optional<Sone> existingSone = database.getSone(identity.getId());
615 if (existingSone.isPresent() && existingSone.get().isLocal()) {
616 return existingSone.get();
618 boolean newSone = !existingSone.isPresent();
619 final Sone sone = newSone ? database.newSoneBuilder().by(identity.getId()).build(Optional.<SoneCreated>absent()) : existingSone.get();
620 sone.modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0)).update();
622 synchronized (knownSones) {
623 newSone = !knownSones.contains(sone.getId());
625 sone.setKnown(!newSone);
627 eventBus.post(new NewSoneFoundEvent(sone));
628 for (Sone localSone : getLocalSones()) {
629 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
630 followSone(localSone, sone.getId());
635 soneDownloader.addSone(sone);
636 soneDownloaders.execute(new Runnable() {
639 @SuppressWarnings("synthetic-access")
641 soneDownloader.fetchSone(sone, TO_FREENET_URI.apply(sone));
650 * Lets the given local Sone follow the Sone with the given ID.
653 * The local Sone that should follow another Sone
655 * The ID of the Sone to follow
657 public void followSone(Sone sone, String soneId) {
658 checkNotNull(sone, "sone must not be null");
659 checkNotNull(soneId, "soneId must not be null");
660 sone.addFriend(soneId);
661 synchronized (soneFollowingTimes) {
662 if (!soneFollowingTimes.containsKey(soneId)) {
663 long now = System.currentTimeMillis();
664 soneFollowingTimes.put(soneId, now);
665 Optional<Sone> followedSone = getSone(soneId);
666 if (!followedSone.isPresent()) {
669 for (Post post : followedSone.get().getPosts()) {
670 if (post.getTime() < now) {
674 for (PostReply reply : followedSone.get().getReplies()) {
675 if (reply.getTime() < now) {
676 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
681 touchConfiguration();
685 * Lets the given local Sone unfollow the Sone with the given ID.
688 * The local Sone that should unfollow another Sone
690 * The ID of the Sone being unfollowed
692 public void unfollowSone(Sone sone, String soneId) {
693 checkNotNull(sone, "sone must not be null");
694 checkNotNull(soneId, "soneId must not be null");
695 sone.removeFriend(soneId);
696 boolean unfollowedSoneStillFollowed = false;
697 for (Sone localSone : getLocalSones()) {
698 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
700 if (!unfollowedSoneStillFollowed) {
701 synchronized (soneFollowingTimes) {
702 soneFollowingTimes.remove(soneId);
705 touchConfiguration();
709 * Sets the trust value of the given origin Sone for the target Sone.
716 * The trust value (from {@code -100} to {@code 100})
718 public void setTrust(Sone origin, Sone target, int trustValue) {
719 checkNotNull(origin, "origin must not be null");
720 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
721 checkNotNull(target, "target must not be null");
722 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
723 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
727 * Removes any trust assignment for the given target Sone.
734 public void removeTrust(Sone origin, Sone target) {
735 checkNotNull(origin, "origin must not be null");
736 checkNotNull(target, "target must not be null");
737 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
738 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
742 * Assigns the configured positive trust value for the given target.
749 public void trustSone(Sone origin, Sone target) {
750 setTrust(origin, target, preferences.getPositiveTrust());
754 * Assigns the configured negative trust value for the given target.
761 public void distrustSone(Sone origin, Sone target) {
762 setTrust(origin, target, preferences.getNegativeTrust());
766 * Removes the trust assignment for the given target.
773 public void untrustSone(Sone origin, Sone target) {
774 removeTrust(origin, target);
778 * Updates the stored Sone with the given Sone.
783 public void updateSone(Sone sone) {
784 updateSone(sone, false);
788 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
789 * {@code true}, an older Sone than the current Sone can be given to restore an
794 * @param soneRescueMode
795 * {@code true} if the stored Sone should be updated regardless of the age of
798 public void updateSone(Sone sone, boolean soneRescueMode) {
799 Optional<Sone> storedSone = getSone(sone.getId());
800 if (storedSone.isPresent()) {
801 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
802 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
805 /* find removed posts. */
806 Collection<Post> existingPosts = database.getPosts(sone.getId());
807 for (Post oldPost : existingPosts) {
808 if (!sone.getPosts().contains(oldPost)) {
809 eventBus.post(new PostRemovedEvent(oldPost));
812 /* find new posts. */
813 for (Post newPost : sone.getPosts()) {
814 if (existingPosts.contains(newPost)) {
817 if (newPost.getTime() < getSoneFollowingTime(sone)) {
818 newPost.setKnown(true);
819 } else if (!newPost.isKnown()) {
820 eventBus.post(new NewPostFoundEvent(newPost));
824 database.storePosts(sone, sone.getPosts());
825 if (!soneRescueMode) {
826 for (PostReply reply : storedSone.get().getReplies()) {
827 if (!sone.getReplies().contains(reply)) {
828 eventBus.post(new PostReplyRemovedEvent(reply));
832 Set<PostReply> storedReplies = storedSone.get().getReplies();
833 for (PostReply reply : sone.getReplies()) {
834 if (storedReplies.contains(reply)) {
837 if (reply.getTime() < getSoneFollowingTime(sone)) {
838 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
839 } else if (!reply.isKnown()) {
840 eventBus.post(new NewPostReplyFoundEvent(reply));
843 database.storePostReplies(sone, sone.getReplies());
844 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
845 database.removeAlbum(album);
846 for (Image image : album.getImages()) {
847 database.removeImage(image);
850 for (Album album : sone.getRootAlbum().getAlbums()) {
851 database.storeAlbum(album);
852 for (Image image : album.getImages()) {
853 database.storeImage(image);
856 synchronized (sones) {
857 sone.setOptions(storedSone.get().getOptions());
858 sone.setKnown(storedSone.get().isKnown());
859 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
860 if (sone.isLocal()) {
861 soneInserters.get(storedSone.get()).setSone(sone);
862 touchConfiguration();
864 sones.put(sone.getId(), sone);
870 * Deletes the given Sone. This will remove the Sone from the {@link
871 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
872 * context from its identity.
877 public void deleteSone(Sone sone) {
878 if (!(sone.getIdentity() instanceof OwnIdentity)) {
879 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
882 synchronized (sones) {
883 if (!getLocalSones().contains(sone)) {
884 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
887 sones.remove(sone.getId());
888 SoneInserter soneInserter = soneInserters.remove(sone);
891 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
892 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
894 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
895 } catch (ConfigurationException ce1) {
896 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
901 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
902 * known} before, a {@link MarkSoneKnownEvent} is fired.
905 * The Sone to mark as known
907 public void markSoneKnown(Sone sone) {
908 if (!sone.isKnown()) {
910 synchronized (knownSones) {
911 knownSones.add(sone.getId());
913 eventBus.post(new MarkSoneKnownEvent(sone));
914 touchConfiguration();
919 * Loads and updates the given Sone from the configuration. If any error is
920 * encountered, loading is aborted and the given Sone is not changed.
923 * The Sone to load and update
925 public void loadSone(Sone sone) {
926 if (!sone.isLocal()) {
927 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
930 logger.info(String.format("Loading local Sone: %s", sone));
932 /* initialize options. */
933 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
934 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
935 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
936 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
937 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
938 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
941 String sonePrefix = "Sone/" + sone.getId();
942 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
943 if (soneTime == null) {
944 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
947 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
950 Profile profile = new Profile(sone);
951 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
952 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
953 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
954 profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
955 Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
956 Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
957 Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
958 profile.modify().setBirthYear(birthYear).setBirthMonth(birthMonth).setBirthDay(birthDay).update();
960 /* load profile fields. */
962 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
963 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
964 if (fieldName == null) {
967 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
968 profile.setField(profile.addField(fieldName), fieldValue);
972 Set<Post> posts = new HashSet<Post>();
974 String postPrefix = sonePrefix + "/Posts/" + posts.size();
975 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
976 if (postId == null) {
979 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
980 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
981 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
982 if ((postTime == 0) || (postText == null)) {
983 logger.log(Level.WARNING, "Invalid post found, aborting load!");
986 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
987 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
988 postBuilder.to(of(postRecipientId));
990 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
994 Set<PostReply> replies = new HashSet<PostReply>();
996 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
997 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
998 if (replyId == null) {
1001 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1002 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1003 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1004 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1005 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1008 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
1009 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
1012 /* load post likes. */
1013 Set<String> likedPostIds = new HashSet<String>();
1015 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1016 if (likedPostId == null) {
1019 likedPostIds.add(likedPostId);
1022 /* load reply likes. */
1023 Set<String> likedReplyIds = new HashSet<String>();
1025 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1026 if (likedReplyId == null) {
1029 likedReplyIds.add(likedReplyId);
1033 Set<String> friends = new HashSet<String>();
1035 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1036 if (friendId == null) {
1039 friends.add(friendId);
1043 Map<String, Album> albums = Maps.newHashMap();
1044 int albumCounter = 0;
1046 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1047 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1048 if (albumId == null) {
1051 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1052 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1053 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1054 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1055 if ((albumTitle == null) || (albumDescription == null)) {
1056 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1059 Album parentAlbum = sone.getRootAlbum();
1060 if (albumParentId != null) {
1061 parentAlbum = albums.get(albumParentId);
1063 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1064 albums.put(album.getId(), album);
1068 int imageCounter = 0;
1070 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1071 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1072 if (imageId == null) {
1075 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1076 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1077 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1078 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1079 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1080 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1081 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1082 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1083 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1086 Album album = albums.get(albumId);
1087 if (album == null) {
1088 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1091 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1095 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1096 if (avatarId != null) {
1097 profile.setAvatar(getImage(avatarId).transform(GET_ID));
1101 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1102 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1103 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1104 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1105 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1106 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1108 /* if we’re still here, Sone was loaded successfully. */
1109 synchronized (sone) {
1110 sone.setTime(soneTime);
1111 sone.setProfile(profile);
1112 sone.setPosts(posts);
1113 sone.setReplies(replies);
1114 sone.setLikePostIds(likedPostIds);
1115 sone.setLikeReplyIds(likedReplyIds);
1116 for (String friendId : friends) {
1117 followSone(sone, friendId);
1119 for (Album album : sone.getRootAlbum().getAlbums()) {
1122 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1124 synchronized (knownSones) {
1125 for (String friend : friends) {
1126 knownSones.add(friend);
1129 database.storePosts(sone, posts);
1130 for (Post post : posts) {
1131 post.setKnown(true);
1133 database.storePostReplies(sone, replies);
1134 for (PostReply reply : replies) {
1135 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
1138 logger.info(String.format("Sone loaded successfully: %s", sone));
1142 * Deletes the given post.
1145 * The post to delete
1147 public void deletePost(Post post) {
1148 if (!post.getSone().isLocal()) {
1149 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1152 database.removePost(post);
1153 eventBus.post(new PostRemovedEvent(post));
1154 markPostKnown(post);
1155 touchConfiguration();
1159 * Marks the given post as known, if it is currently not a known post
1160 * (according to {@link Post#isKnown()}).
1163 * The post to mark as known
1165 public void markPostKnown(Post post) {
1166 post.setKnown(true);
1167 eventBus.post(new MarkPostKnownEvent(post));
1168 touchConfiguration();
1169 for (PostReply reply : post.getReplies()) {
1170 reply.modify().setKnown().update(postReplyUpdated());
1175 * Bookmarks the post with the given ID.
1178 * The ID of the post to bookmark
1180 public void bookmarkPost(String id) {
1181 synchronized (bookmarkedPosts) {
1182 bookmarkedPosts.add(id);
1187 * Removes the given post from the bookmarks.
1190 * The post to unbookmark
1192 public void unbookmark(Post post) {
1193 unbookmarkPost(post.getId());
1197 * Removes the post with the given ID from the bookmarks.
1200 * The ID of the post to unbookmark
1202 public void unbookmarkPost(String id) {
1203 synchronized (bookmarkedPosts) {
1204 bookmarkedPosts.remove(id);
1209 * Deletes the given reply.
1212 * The reply to delete
1214 public void deleteReply(PostReply reply) {
1215 Sone sone = reply.getSone();
1216 if (!sone.isLocal()) {
1217 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1220 postReplyUpdated().get().replyUpdated(reply);
1221 database.removePostReply(reply);
1222 touchConfiguration();
1226 * Creates a new image.
1229 * The Sone creating the image
1231 * The album the image will be inserted into
1232 * @param temporaryImage
1233 * The temporary image to create the image from
1234 * @return The newly created image
1236 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1237 checkNotNull(sone, "sone must not be null");
1238 checkNotNull(album, "album must not be null");
1239 checkNotNull(temporaryImage, "temporaryImage must not be null");
1240 checkArgument(sone.isLocal(), "sone must be a local Sone");
1241 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1242 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1243 imageInserter.insertImage(temporaryImage, image);
1248 * Deletes the given image. This method will also delete a matching temporary
1252 * The image to delete
1253 * @see #deleteTemporaryImage(String)
1255 public void deleteImage(Image image) {
1256 checkNotNull(image, "image must not be null");
1257 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1258 deleteTemporaryImage(image.getId());
1260 touchConfiguration();
1264 * Creates a new temporary image.
1267 * The MIME type of the temporary image
1269 * The encoded data of the image
1270 * @return The temporary image
1272 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1273 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1274 synchronized (temporaryImages) {
1275 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1277 return temporaryImage;
1281 * Deletes the temporary image with the given ID.
1284 * The ID of the temporary image to delete
1286 public void deleteTemporaryImage(String imageId) {
1287 checkNotNull(imageId, "imageId must not be null");
1288 synchronized (temporaryImages) {
1289 temporaryImages.remove(imageId);
1291 Optional<Image> image = getImage(imageId);
1292 if (image.isPresent()) {
1293 imageInserter.cancelImageInsert(image.get());
1298 * Notifies the core that the configuration, either of the core or of a single
1299 * local Sone, has changed, and that the configuration should be saved.
1301 public void touchConfiguration() {
1302 lastConfigurationUpdate = System.currentTimeMillis();
1310 public void serviceStart() {
1311 loadConfiguration();
1312 updateChecker.start();
1313 identityManager.start();
1314 webOfTrustUpdater.init();
1315 webOfTrustUpdater.start();
1320 public void serviceRun() {
1321 long lastSaved = System.currentTimeMillis();
1322 while (!shouldStop()) {
1324 long now = System.currentTimeMillis();
1325 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1326 for (Sone localSone : getLocalSones()) {
1327 saveSone(localSone);
1329 saveConfiguration();
1336 public void serviceStop() {
1337 localElementTicker.shutdownNow();
1338 synchronized (sones) {
1339 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1340 soneInserter.getValue().stop();
1341 saveSone(soneInserter.getKey());
1344 saveConfiguration();
1346 webOfTrustUpdater.stop();
1347 updateChecker.stop();
1348 soneDownloader.stop();
1349 soneDownloaders.shutdown();
1350 identityManager.stop();
1358 * Saves the given Sone. This will persist all local settings for the given
1359 * Sone, such as the friends list and similar, private options.
1364 private synchronized void saveSone(Sone sone) {
1365 if (!sone.isLocal()) {
1366 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1369 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1370 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1374 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1376 /* save Sone into configuration. */
1377 String sonePrefix = "Sone/" + sone.getId();
1378 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1379 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1382 Profile profile = sone.getProfile();
1383 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1384 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1385 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1386 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1387 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1388 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1389 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1391 /* save profile fields. */
1392 int fieldCounter = 0;
1393 for (Field profileField : profile.getFields()) {
1394 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1395 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1396 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1398 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1401 int postCounter = 0;
1402 for (Post post : sone.getPosts()) {
1403 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1404 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1405 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1406 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1407 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1409 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1412 int replyCounter = 0;
1413 for (PostReply reply : sone.getReplies()) {
1414 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1415 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1416 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1417 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1418 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1420 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1422 /* save post likes. */
1423 int postLikeCounter = 0;
1424 for (String postId : sone.getLikedPostIds()) {
1425 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1427 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1429 /* save reply likes. */
1430 int replyLikeCounter = 0;
1431 for (String replyId : sone.getLikedReplyIds()) {
1432 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1434 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1437 int friendCounter = 0;
1438 for (String friendId : sone.getFriends()) {
1439 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1441 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1443 /* save albums. first, collect in a flat structure, top-level first. */
1444 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1446 int albumCounter = 0;
1447 for (Album album : albums) {
1448 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1449 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1450 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1451 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1452 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1453 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1455 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1458 int imageCounter = 0;
1459 for (Album album : albums) {
1460 for (Image image : album.getImages()) {
1461 if (!image.isInserted()) {
1464 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1465 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1466 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1467 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1468 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1469 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1470 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1471 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1472 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1475 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1478 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1479 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1480 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1481 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1482 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1483 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1485 configuration.save();
1487 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1489 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1490 } catch (ConfigurationException ce1) {
1491 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1495 /** Saves the current options. */
1496 private void saveConfiguration() {
1497 synchronized (configuration) {
1498 if (storingConfiguration) {
1499 logger.log(Level.FINE, "Already storing configuration…");
1502 storingConfiguration = true;
1505 /* store the options first. */
1507 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1508 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1509 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1510 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1511 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1512 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1513 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1514 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1515 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1516 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1517 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1518 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1520 /* save known Sones. */
1521 int soneCounter = 0;
1522 synchronized (knownSones) {
1523 for (String knownSoneId : knownSones) {
1524 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1526 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1529 /* save Sone following times. */
1531 synchronized (soneFollowingTimes) {
1532 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1533 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1534 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1537 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1540 /* save known posts. */
1543 /* save bookmarked posts. */
1544 int bookmarkedPostCounter = 0;
1545 synchronized (bookmarkedPosts) {
1546 for (String bookmarkedPostId : bookmarkedPosts) {
1547 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1550 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1553 configuration.save();
1555 } catch (ConfigurationException ce1) {
1556 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1557 } catch (DatabaseException de1) {
1558 logger.log(Level.SEVERE, "Could not save database!", de1);
1560 synchronized (configuration) {
1561 storingConfiguration = false;
1566 /** Loads the configuration. */
1567 private void loadConfiguration() {
1568 /* create options. */
1569 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1572 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1573 SoneInserter.setInsertionDelay(newValue);
1577 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1578 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1579 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1580 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1581 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1582 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1583 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1584 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1585 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1588 @SuppressWarnings("synthetic-access")
1589 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1590 fcpInterface.setActive(newValue);
1593 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1596 @SuppressWarnings("synthetic-access")
1597 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1598 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1603 loadConfigurationValue("InsertionDelay");
1604 loadConfigurationValue("PostsPerPage");
1605 loadConfigurationValue("ImagesPerPage");
1606 loadConfigurationValue("CharactersPerPost");
1607 loadConfigurationValue("PostCutOffLength");
1608 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1609 loadConfigurationValue("PositiveTrust");
1610 loadConfigurationValue("NegativeTrust");
1611 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1612 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1613 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1615 /* load known Sones. */
1616 int soneCounter = 0;
1618 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1619 if (knownSoneId == null) {
1622 synchronized (knownSones) {
1623 knownSones.add(knownSoneId);
1627 /* load Sone following times. */
1630 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1631 if (soneId == null) {
1634 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1635 synchronized (soneFollowingTimes) {
1636 soneFollowingTimes.put(soneId, time);
1641 /* load bookmarked posts. */
1642 int bookmarkedPostCounter = 0;
1644 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1645 if (bookmarkedPostId == null) {
1648 synchronized (bookmarkedPosts) {
1649 bookmarkedPosts.add(bookmarkedPostId);
1656 * Loads an {@link Integer} configuration value for the option with the given
1657 * name, logging validation failures.
1660 * The name of the option to load
1662 private void loadConfigurationValue(String optionName) {
1664 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1665 } catch (IllegalArgumentException iae1) {
1666 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1671 * Notifies the core that a new {@link OwnIdentity} was added.
1673 * @param ownIdentityAddedEvent
1677 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1678 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1679 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1680 if (ownIdentity.hasContext("Sone")) {
1681 addLocalSone(ownIdentity);
1686 * Notifies the core that an {@link OwnIdentity} was removed.
1688 * @param ownIdentityRemovedEvent
1692 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1693 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1694 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1695 trustedIdentities.removeAll(ownIdentity);
1699 * Notifies the core that a new {@link Identity} was added.
1701 * @param identityAddedEvent
1705 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1706 Identity identity = identityAddedEvent.identity();
1707 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1708 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1709 addRemoteSone(identity);
1713 * Notifies the core that an {@link Identity} was updated.
1715 * @param identityUpdatedEvent
1719 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1720 final Identity identity = identityUpdatedEvent.identity();
1721 soneDownloaders.execute(new Runnable() {
1724 @SuppressWarnings("synthetic-access")
1726 Optional<Sone> sone = getRemoteSone(identity.getId());
1727 sone.get().modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition())).update();
1728 soneDownloader.addSone(sone.get());
1729 soneDownloader.fetchSone(sone.get());
1735 * Notifies the core that an {@link Identity} was removed.
1737 * @param identityRemovedEvent
1741 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1742 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1743 Identity identity = identityRemovedEvent.identity();
1744 trustedIdentities.remove(ownIdentity, identity);
1745 boolean foundIdentity = false;
1746 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1747 if (trustedIdentity.getKey().equals(ownIdentity)) {
1750 if (trustedIdentity.getValue().contains(identity)) {
1751 foundIdentity = true;
1754 if (foundIdentity) {
1755 /* some local identity still trusts this identity, don’t remove. */
1758 Optional<Sone> sone = getSone(identity.getId());
1759 if (!sone.isPresent()) {
1760 /* TODO - we don’t have the Sone anymore. should this happen? */
1763 database.removePosts(sone.get());
1764 for (Post post : sone.get().getPosts()) {
1765 eventBus.post(new PostRemovedEvent(post));
1767 database.removePostReplies(sone.get());
1768 for (PostReply reply : sone.get().getReplies()) {
1769 eventBus.post(new PostReplyRemovedEvent(reply));
1771 synchronized (sones) {
1772 sones.remove(identity.getId());
1774 eventBus.post(new SoneRemovedEvent(sone.get()));
1778 * Deletes the temporary image.
1780 * @param imageInsertFinishedEvent
1784 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1785 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1786 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1787 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1788 touchConfiguration();
1791 public Optional<PostCreated> postCreated() {
1792 return Optional.<PostCreated>of(new PostCreated() {
1794 public void postCreated(final Post post) {
1795 if (post.isKnown()) {
1798 eventBus.post(new NewPostFoundEvent(post));
1799 if (post.getSone().isLocal()) {
1800 localElementTicker.schedule(new Runnable() {
1803 markPostKnown(post);
1805 }, 10, TimeUnit.SECONDS);
1811 public Optional<PostReplyCreated> postReplyCreated() {
1812 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1814 public void postReplyCreated(final PostReply postReply) {
1815 if (postReply.isKnown()) {
1818 eventBus.post(new NewPostReplyFoundEvent(postReply));
1819 if (postReply.getSone().isLocal()) {
1820 localElementTicker.schedule(new Runnable() {
1827 postReplyUpdated().get().replyUpdated(postReply);
1829 }, 10, TimeUnit.SECONDS);
1835 public Optional<ReplyUpdated<PostReply>> postReplyUpdated() {
1836 return Optional.<ReplyUpdated<PostReply>>of(new ReplyUpdated<PostReply>() {
1838 public void replyUpdated(PostReply reply) {
1839 eventBus.post(new MarkPostReplyKnownEvent(reply));
1844 public Optional<ImageCreated> imageCreated() {
1845 return Optional.<ImageCreated>of(new ImageCreated() {
1847 public void imageCreated(Image image) {
1848 /* nothing happens here yet. */