2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.of;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.collect.FluentIterable.from;
25 import static java.lang.String.format;
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.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 com.google.common.base.Function;
100 import com.google.common.base.Optional;
101 import com.google.common.base.Predicate;
102 import com.google.common.base.Predicates;
103 import com.google.common.collect.HashMultimap;
104 import com.google.common.collect.ImmutableSet;
105 import com.google.common.collect.Maps;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
115 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
117 public class Core extends AbstractService implements SoneProvider {
120 private static final Logger logger = Logging.getLogger(Core.class);
123 private final Options options = new Options();
125 /** The preferences. */
126 private final Preferences preferences = new Preferences(options);
128 /** The event bus. */
129 private final EventBus eventBus;
131 /** The configuration. */
132 private Configuration configuration;
134 /** Whether we’re currently saving the configuration. */
135 private boolean storingConfiguration = false;
137 /** The identity manager. */
138 private final IdentityManager identityManager;
140 /** Interface to freenet. */
141 private final FreenetInterface freenetInterface;
143 /** The Sone downloader. */
144 private final SoneDownloader soneDownloader;
146 /** The image inserter. */
147 private final ImageInserter imageInserter;
149 /** Sone downloader thread-pool. */
150 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
152 /** The update checker. */
153 private final UpdateChecker updateChecker;
155 /** The trust updater. */
156 private final WebOfTrustUpdater webOfTrustUpdater;
158 /** The FCP interface. */
159 private volatile FcpInterface fcpInterface;
161 /** The times Sones were followed. */
162 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
164 /** Locked local Sones. */
165 /* synchronize on itself. */
166 private final Set<Sone> lockedSones = new HashSet<Sone>();
168 /** Sone inserters. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
172 /** Sone rescuers. */
173 /* synchronize access on this on sones. */
174 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
176 /** All known Sones. */
177 private final Set<String> knownSones = new HashSet<String>();
179 /** The post database. */
180 private final Database database;
182 /** All bookmarked posts. */
183 /* synchronize access on itself. */
184 private final Set<String> bookmarkedPosts = new HashSet<String>();
186 /** Trusted identities, sorted by own identities. */
187 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
189 /** All temporary images. */
190 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
192 /** Ticker for threads that mark own elements as known. */
193 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
195 /** The time the configuration was last touched. */
196 private volatile long lastConfigurationUpdate;
199 * Creates a new core.
201 * @param configuration
202 * The configuration of the core
203 * @param freenetInterface
204 * The freenet interface
205 * @param identityManager
206 * The identity manager
207 * @param webOfTrustUpdater
208 * The WebOfTrust updater
215 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
217 this.configuration = configuration;
218 this.freenetInterface = freenetInterface;
219 this.identityManager = identityManager;
220 this.soneDownloader = new SoneDownloader(this, freenetInterface);
221 this.imageInserter = new ImageInserter(freenetInterface);
222 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
223 this.webOfTrustUpdater = webOfTrustUpdater;
224 this.eventBus = eventBus;
225 this.database = database;
233 * Sets the configuration to use. This will automatically save the current
234 * configuration to the given configuration.
236 * @param configuration
237 * The new configuration to use
239 public void setConfiguration(Configuration configuration) {
240 this.configuration = configuration;
241 touchConfiguration();
245 * Returns the options used by the core.
247 * @return The options of the core
249 public Preferences getPreferences() {
254 * Returns the identity manager used by the core.
256 * @return The identity manager
258 public IdentityManager getIdentityManager() {
259 return identityManager;
263 * Returns the update checker.
265 * @return The update checker
267 public UpdateChecker getUpdateChecker() {
268 return updateChecker;
272 * Sets the FCP interface to use.
274 * @param fcpInterface
275 * The FCP interface to use
277 public void setFcpInterface(FcpInterface fcpInterface) {
278 this.fcpInterface = fcpInterface;
281 public Database getDatabase() {
286 * Returns the Sone rescuer for the given local Sone.
289 * The local Sone to get the rescuer for
290 * @return The Sone rescuer for the given Sone
292 public SoneRescuer getSoneRescuer(Sone sone) {
293 checkNotNull(sone, "sone must not be null");
294 checkArgument(sone.isLocal(), "sone must be local");
295 synchronized (soneRescuers) {
296 SoneRescuer soneRescuer = soneRescuers.get(sone);
297 if (soneRescuer == null) {
298 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
299 soneRescuers.put(sone, soneRescuer);
307 * Returns whether the given Sone is currently locked.
311 * @return {@code true} if the Sone is locked, {@code false} if it is not
313 public boolean isLocked(Sone sone) {
314 synchronized (lockedSones) {
315 return lockedSones.contains(sone);
320 public Collection<Sone> getSones() {
321 return database.getSones();
325 public Function<String, Optional<Sone>> getSone() {
326 return database.getSone();
330 public Optional<Sone> getSone(String id) {
331 return database.getSone(id);
335 public Collection<Sone> getLocalSones() {
336 return database.getLocalSones();
340 * Returns the local Sone with the given ID, optionally creating a new Sone.
344 * @return The Sone with the given ID, or {@code null}
346 public Optional<Sone> getLocalSone(String id) {
347 return from(database.getSone(id).asSet()).firstMatch(LOCAL_SONE_FILTER);
351 public Collection<Sone> getRemoteSones() {
352 return database.getRemoteSones();
356 * Returns the remote Sone with the given ID.
359 * The ID of the remote Sone to get
360 * @return The Sone with the given ID
362 public Optional<Sone> getRemoteSone(String id) {
363 return from(database.getSone(id).asSet()).firstMatch(not(LOCAL_SONE_FILTER));
367 * Returns whether the given Sone has been modified.
370 * The Sone to check for modifications
371 * @return {@code true} if a modification has been detected in the Sone, {@code
374 public boolean isModifiedSone(Sone sone) {
375 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
379 * Returns the time when the given was first followed by any local Sone.
382 * The Sone to get the time for
383 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first been
384 * followed, or {@link Long#MAX_VALUE}
386 public long getSoneFollowingTime(Sone sone) {
387 synchronized (soneFollowingTimes) {
388 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
393 * Returns whether the given post is bookmarked.
397 * @return {@code true} if the given post is bookmarked, {@code false}
400 public boolean isBookmarked(Post post) {
401 return isPostBookmarked(post.getId());
405 * Returns whether the post with the given ID is bookmarked.
408 * The ID of the post to check
409 * @return {@code true} if the post with the given ID is bookmarked, {@code
412 public boolean isPostBookmarked(String id) {
413 synchronized (bookmarkedPosts) {
414 return bookmarkedPosts.contains(id);
419 * Returns all currently known bookmarked posts.
421 * @return All bookmarked posts
423 public Set<Post> getBookmarkedPosts() {
424 Set<Post> posts = new HashSet<Post>();
425 synchronized (bookmarkedPosts) {
426 for (String bookmarkedPostId : bookmarkedPosts) {
427 Optional<Post> post = database.getPost(bookmarkedPostId);
428 if (post.isPresent()) {
429 posts.add(post.get());
436 public Optional<Album> getAlbum(String albumId) {
437 return database.getAlbum(albumId);
440 public Optional<Image> getImage(String imageId) {
441 return database.getImage(imageId);
445 * Returns the temporary image with the given ID.
448 * The ID of the temporary image
449 * @return The temporary image, or {@code null} if there is no temporary image
452 public TemporaryImage getTemporaryImage(String imageId) {
453 synchronized (temporaryImages) {
454 return temporaryImages.get(imageId);
463 * Locks the given Sone. A locked Sone will not be inserted by {@link
464 * SoneInserter} until it is {@link #unlockSone(Sone) unlocked} again.
469 public void lockSone(Sone sone) {
470 synchronized (lockedSones) {
471 if (lockedSones.add(sone)) {
472 eventBus.post(new SoneLockedEvent(sone));
478 * Unlocks the given Sone.
482 * @see #lockSone(Sone)
484 public void unlockSone(Sone sone) {
485 synchronized (lockedSones) {
486 if (lockedSones.remove(sone)) {
487 eventBus.post(new SoneUnlockedEvent(sone));
493 * Adds a local Sone from the given own identity.
496 * The own identity to create a Sone from
497 * @return The added (or already existing) Sone
499 public Sone addLocalSone(OwnIdentity ownIdentity) {
500 if (ownIdentity == null) {
501 logger.log(Level.WARNING, "Given OwnIdentity is null!");
504 logger.info(format("Adding Sone from OwnIdentity: %s", ownIdentity));
505 synchronized (soneRescuers) {
507 sone = database.newSoneBuilder().by(ownIdentity.getId()).local().using(new Client("Sone", SonePlugin.VERSION.toString())).build(Optional.<SoneCreated>absent());
508 sone.modify().setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0)).update();
510 /* TODO - load posts ’n stuff */
511 database.storeSone(sone);
512 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
513 soneInserters.put(sone, soneInserter);
514 sone.setStatus(SoneStatus.idle);
516 soneInserter.start();
522 * Creates a new Sone for the given own identity.
525 * The own identity to create a Sone for
526 * @return The created Sone
528 public Sone createSone(OwnIdentity ownIdentity) {
529 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
530 logger.log(Level.SEVERE, format("Could not add “Sone” context to own identity: %s", ownIdentity));
533 Sone sone = addLocalSone(ownIdentity);
534 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
535 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
536 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
537 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
538 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
539 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
541 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
542 touchConfiguration();
547 * Adds the Sone of the given identity.
550 * The identity whose Sone to add
551 * @return The added or already existing Sone
553 public Sone addRemoteSone(Identity identity) {
554 if (identity == null) {
555 logger.log(Level.WARNING, "Given Identity is null!");
558 synchronized (soneRescuers) {
559 Optional<Sone> existingSone = database.getSone(identity.getId());
560 if (existingSone.isPresent() && existingSone.get().isLocal()) {
561 return existingSone.get();
563 boolean newSone = !existingSone.isPresent();
564 final Sone sone = newSone ? database.newSoneBuilder().by(identity.getId()).using(new Client("Sone", SonePlugin.VERSION.toString())).build(Optional.<SoneCreated>absent()) : existingSone.get();
565 sone.modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0)).update();
567 synchronized (knownSones) {
568 newSone = !knownSones.contains(sone.getId());
570 sone.setKnown(!newSone);
572 eventBus.post(new NewSoneFoundEvent(sone));
573 for (Sone localSone : getLocalSones()) {
574 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
575 followSone(localSone, sone.getId());
580 soneDownloader.addSone(sone);
581 soneDownloaders.execute(new Runnable() {
584 @SuppressWarnings("synthetic-access")
586 soneDownloader.fetchSone(sone, TO_FREENET_URI.apply(sone));
595 * Lets the given local Sone follow the Sone with the given ID.
598 * The local Sone that should follow another Sone
600 * The ID of the Sone to follow
602 public void followSone(Sone sone, String soneId) {
603 checkNotNull(sone, "sone must not be null");
604 checkNotNull(soneId, "soneId must not be null");
605 sone.addFriend(soneId);
606 synchronized (soneFollowingTimes) {
607 if (!soneFollowingTimes.containsKey(soneId)) {
608 long now = System.currentTimeMillis();
609 soneFollowingTimes.put(soneId, now);
610 Optional<Sone> followedSone = getSone(soneId);
611 if (!followedSone.isPresent()) {
614 for (Post post : followedSone.get().getPosts()) {
615 if (post.getTime() < now) {
619 for (PostReply reply : followedSone.get().getReplies()) {
620 if (reply.getTime() < now) {
621 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
626 touchConfiguration();
630 * Lets the given local Sone unfollow the Sone with the given ID.
633 * The local Sone that should unfollow another Sone
635 * The ID of the Sone being unfollowed
637 public void unfollowSone(Sone sone, String soneId) {
638 checkNotNull(sone, "sone must not be null");
639 checkNotNull(soneId, "soneId must not be null");
640 sone.removeFriend(soneId);
641 boolean unfollowedSoneStillFollowed = false;
642 for (Sone localSone : getLocalSones()) {
643 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
645 if (!unfollowedSoneStillFollowed) {
646 synchronized (soneFollowingTimes) {
647 soneFollowingTimes.remove(soneId);
650 touchConfiguration();
654 * Sets the trust value of the given origin Sone for the target Sone.
661 * The trust value (from {@code -100} to {@code 100})
663 public void setTrust(Sone origin, Sone target, int trustValue) {
664 checkNotNull(origin, "origin must not be null");
665 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
666 checkNotNull(target, "target must not be null");
667 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
668 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
672 * Removes any trust assignment for the given target Sone.
679 public void removeTrust(Sone origin, Sone target) {
680 checkNotNull(origin, "origin must not be null");
681 checkNotNull(target, "target must not be null");
682 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
683 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
687 * Assigns the configured positive trust value for the given target.
694 public void trustSone(Sone origin, Sone target) {
695 setTrust(origin, target, preferences.getPositiveTrust());
699 * Assigns the configured negative trust value for the given target.
706 public void distrustSone(Sone origin, Sone target) {
707 setTrust(origin, target, preferences.getNegativeTrust());
711 * Removes the trust assignment for the given target.
718 public void untrustSone(Sone origin, Sone target) {
719 removeTrust(origin, target);
723 * Updates the stored Sone with the given Sone.
728 public void updateSone(Sone sone) {
729 updateSone(sone, false);
733 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
734 * {@code true}, an older Sone than the current Sone can be given to restore an
739 * @param soneRescueMode
740 * {@code true} if the stored Sone should be updated regardless of the age of
743 public void updateSone(Sone sone, boolean soneRescueMode) {
744 Optional<Sone> storedSone = getSone(sone.getId());
745 if (storedSone.isPresent()) {
746 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
747 logger.log(Level.FINE, format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
750 /* find removed posts. */
751 Collection<Post> existingPosts = database.getPosts(sone.getId());
752 for (Post oldPost : existingPosts) {
753 if (!sone.getPosts().contains(oldPost)) {
754 eventBus.post(new PostRemovedEvent(oldPost));
757 /* find new posts. */
758 for (Post newPost : sone.getPosts()) {
759 if (existingPosts.contains(newPost)) {
762 if (newPost.getTime() < getSoneFollowingTime(sone)) {
764 } else if (!newPost.isKnown()) {
765 eventBus.post(new NewPostFoundEvent(newPost));
769 database.storePosts(sone, sone.getPosts());
770 if (!soneRescueMode) {
771 for (PostReply reply : storedSone.get().getReplies()) {
772 if (!sone.getReplies().contains(reply)) {
773 eventBus.post(new PostReplyRemovedEvent(reply));
777 Set<PostReply> storedReplies = storedSone.get().getReplies();
778 for (PostReply reply : sone.getReplies()) {
779 if (storedReplies.contains(reply)) {
782 if (reply.getTime() < getSoneFollowingTime(sone)) {
783 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
784 } else if (!reply.isKnown()) {
785 eventBus.post(new NewPostReplyFoundEvent(reply));
788 database.storePostReplies(sone, sone.getReplies());
789 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
790 database.removeAlbum(album);
791 for (Image image : album.getImages()) {
792 database.removeImage(image);
795 for (Album album : sone.getRootAlbum().getAlbums()) {
796 database.storeAlbum(album);
797 for (Image image : album.getImages()) {
798 database.storeImage(image);
801 synchronized (soneRescuers) {
802 sone.setOptions(storedSone.get().getOptions());
803 sone.setKnown(storedSone.get().isKnown());
804 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
805 if (sone.isLocal()) {
806 soneInserters.get(storedSone.get()).setSone(sone);
807 touchConfiguration();
809 database.storeSone(sone);
815 * Deletes the given Sone. This will remove the Sone from the {@link
816 * #getLocalSones() local Sones}, stop its {@link SoneInserter} and remove the
817 * context from its identity.
822 public void deleteSone(Sone sone) {
823 if (!(sone.getIdentity() instanceof OwnIdentity)) {
824 logger.log(Level.WARNING, format("Tried to delete Sone of non-own identity: %s", sone));
827 synchronized (soneRescuers) {
828 if (!getLocalSones().contains(sone)) {
829 logger.log(Level.WARNING, format("Tried to delete non-local Sone: %s", sone));
832 SoneInserter soneInserter = soneInserters.remove(sone);
835 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
836 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
838 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
839 } catch (ConfigurationException ce1) {
840 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
845 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
846 * known} before, a {@link MarkSoneKnownEvent} is fired.
849 * The Sone to mark as known
851 public void markSoneKnown(Sone sone) {
852 if (!sone.isKnown()) {
854 synchronized (knownSones) {
855 knownSones.add(sone.getId());
857 eventBus.post(new MarkSoneKnownEvent(sone));
858 touchConfiguration();
863 * Loads and updates the given Sone from the configuration. If any error is
864 * encountered, loading is aborted and the given Sone is not changed.
867 * The Sone to load and update
869 public void loadSone(Sone sone) {
870 if (!sone.isLocal()) {
871 logger.log(Level.FINE, format("Tried to load non-local Sone: %s", sone));
874 logger.info(format("Loading local Sone: %s", sone));
876 /* initialize options. */
877 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
878 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
879 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
880 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
881 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
882 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
885 String sonePrefix = "Sone/" + sone.getId();
886 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
887 if (soneTime == null) {
888 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
891 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
894 Profile profile = new Profile(sone);
895 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
896 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
897 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
898 profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
899 Integer birthDay = configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null);
900 Integer birthMonth = configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null);
901 Integer birthYear = configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null);
902 profile.modify().setBirthYear(birthYear).setBirthMonth(birthMonth).setBirthDay(birthDay).update();
904 /* load profile fields. */
906 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
907 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
908 if (fieldName == null) {
911 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
912 profile.setField(profile.addField(fieldName), fieldValue);
916 Set<Post> posts = new HashSet<Post>();
918 String postPrefix = sonePrefix + "/Posts/" + posts.size();
919 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
920 if (postId == null) {
923 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
924 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
925 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
926 if ((postTime == 0) || (postText == null)) {
927 logger.log(Level.WARNING, "Invalid post found, aborting load!");
930 PostBuilder postBuilder = sone.newPostBuilder().withId(postId).withTime(postTime).withText(postText);
931 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
932 postBuilder.to(of(postRecipientId));
934 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
938 Set<PostReply> replies = new HashSet<PostReply>();
940 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
941 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
942 if (replyId == null) {
945 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
946 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
947 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
948 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
949 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
952 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(postId).withId(replyId).withTime(replyTime).withText(replyText);
953 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
956 /* load post likes. */
957 Set<String> likedPostIds = new HashSet<String>();
959 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
960 if (likedPostId == null) {
963 likedPostIds.add(likedPostId);
966 /* load reply likes. */
967 Set<String> likedReplyIds = new HashSet<String>();
969 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
970 if (likedReplyId == null) {
973 likedReplyIds.add(likedReplyId);
977 Set<String> friends = new HashSet<String>();
979 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
980 if (friendId == null) {
983 friends.add(friendId);
987 Map<String, Album> albums = Maps.newHashMap();
988 int albumCounter = 0;
990 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
991 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
992 if (albumId == null) {
995 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
996 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
997 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
998 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
999 if ((albumTitle == null) || (albumDescription == null)) {
1000 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1003 Album parentAlbum = sone.getRootAlbum();
1004 if (albumParentId != null) {
1005 parentAlbum = albums.get(albumParentId);
1007 Album album = parentAlbum.newAlbumBuilder().withId(albumId).build().modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1008 albums.put(album.getId(), album);
1012 int imageCounter = 0;
1014 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1015 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1016 if (imageId == null) {
1019 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1020 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1021 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1022 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1023 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1024 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1025 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1026 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1027 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1030 Album album = albums.get(albumId);
1031 if (album == null) {
1032 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1035 album.newImageBuilder().withId(imageId).created(creationTime).at(key).sized(width, height).build(Optional.<ImageCreated>absent()).modify().setTitle(title).setDescription(description).update();
1039 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1040 if (avatarId != null) {
1041 profile.setAvatar(getImage(avatarId).transform(GET_ID));
1045 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1046 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1047 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1048 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1049 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1050 sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1052 /* if we’re still here, Sone was loaded successfully. */
1053 synchronized (sone) {
1054 sone.setTime(soneTime);
1055 sone.setProfile(profile);
1056 sone.setPosts(posts);
1057 sone.setReplies(replies);
1058 sone.setLikePostIds(likedPostIds);
1059 sone.setLikeReplyIds(likedReplyIds);
1060 for (String friendId : friends) {
1061 followSone(sone, friendId);
1063 for (Album album : sone.getRootAlbum().getAlbums()) {
1066 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1068 synchronized (knownSones) {
1069 for (String friend : friends) {
1070 knownSones.add(friend);
1073 database.storePosts(sone, posts);
1074 for (Post post : posts) {
1077 database.storePostReplies(sone, replies);
1078 for (PostReply reply : replies) {
1079 reply.modify().setKnown().update(Optional.<ReplyUpdated<PostReply>>absent());
1082 logger.info(format("Sone loaded successfully: %s", sone));
1086 * Deletes the given post.
1089 * The post to delete
1091 public void deletePost(Post post) {
1092 if (!post.getSone().isLocal()) {
1093 logger.log(Level.WARNING, format("Tried to delete post of non-local Sone: %s", post.getSone()));
1096 database.removePost(post);
1097 eventBus.post(new PostRemovedEvent(post));
1098 markPostKnown(post);
1099 touchConfiguration();
1103 * Marks the given post as known, if it is currently not a known post
1104 * (according to {@link Post#isKnown()}).
1107 * The post to mark as known
1109 public void markPostKnown(Post post) {
1111 eventBus.post(new MarkPostKnownEvent(post));
1112 touchConfiguration();
1113 for (PostReply reply : post.getReplies()) {
1114 reply.modify().setKnown().update(postReplyUpdated());
1119 * Bookmarks the post with the given ID.
1122 * The ID of the post to bookmark
1124 public void bookmarkPost(String id) {
1125 synchronized (bookmarkedPosts) {
1126 bookmarkedPosts.add(id);
1131 * Removes the given post from the bookmarks.
1134 * The post to unbookmark
1136 public void unbookmark(Post post) {
1137 unbookmarkPost(post.getId());
1141 * Removes the post with the given ID from the bookmarks.
1144 * The ID of the post to unbookmark
1146 public void unbookmarkPost(String id) {
1147 synchronized (bookmarkedPosts) {
1148 bookmarkedPosts.remove(id);
1153 * Deletes the given reply.
1156 * The reply to delete
1158 public void deleteReply(PostReply reply) {
1159 Sone sone = reply.getSone();
1160 if (!sone.isLocal()) {
1161 logger.log(Level.FINE, format("Tried to delete non-local reply: %s", reply));
1164 postReplyUpdated().get().replyUpdated(reply);
1165 database.removePostReply(reply);
1166 touchConfiguration();
1170 * Creates a new image.
1173 * The Sone creating the image
1175 * The album the image will be inserted into
1176 * @param temporaryImage
1177 * The temporary image to create the image from
1178 * @return The newly created image
1180 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1181 checkNotNull(sone, "sone must not be null");
1182 checkNotNull(album, "album must not be null");
1183 checkNotNull(temporaryImage, "temporaryImage must not be null");
1184 checkArgument(sone.isLocal(), "sone must be a local Sone");
1185 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1186 Image image = album.newImageBuilder().withId(temporaryImage.getId()).sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build(imageCreated());
1187 imageInserter.insertImage(temporaryImage, image);
1192 * Deletes the given image. This method will also delete a matching temporary
1196 * The image to delete
1197 * @see #deleteTemporaryImage(String)
1199 public void deleteImage(Image image) {
1200 checkNotNull(image, "image must not be null");
1201 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1202 deleteTemporaryImage(image.getId());
1204 touchConfiguration();
1208 * Creates a new temporary image.
1211 * The MIME type of the temporary image
1213 * The encoded data of the image
1214 * @return The temporary image
1216 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1217 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1218 synchronized (temporaryImages) {
1219 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1221 return temporaryImage;
1225 * Deletes the temporary image with the given ID.
1228 * The ID of the temporary image to delete
1230 public void deleteTemporaryImage(String imageId) {
1231 checkNotNull(imageId, "imageId must not be null");
1232 synchronized (temporaryImages) {
1233 temporaryImages.remove(imageId);
1235 Optional<Image> image = getImage(imageId);
1236 if (image.isPresent()) {
1237 imageInserter.cancelImageInsert(image.get());
1242 * Notifies the core that the configuration, either of the core or of a single
1243 * local Sone, has changed, and that the configuration should be saved.
1245 public void touchConfiguration() {
1246 lastConfigurationUpdate = System.currentTimeMillis();
1254 public void serviceStart() {
1255 loadConfiguration();
1256 updateChecker.start();
1257 identityManager.start();
1258 webOfTrustUpdater.init();
1259 webOfTrustUpdater.start();
1264 public void serviceRun() {
1265 long lastSaved = System.currentTimeMillis();
1266 while (!shouldStop()) {
1268 long now = System.currentTimeMillis();
1269 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1270 for (Sone localSone : getLocalSones()) {
1271 saveSone(localSone);
1273 saveConfiguration();
1280 public void serviceStop() {
1281 localElementTicker.shutdownNow();
1282 synchronized (soneRescuers) {
1283 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1284 soneInserter.getValue().stop();
1285 saveSone(soneInserter.getKey());
1288 saveConfiguration();
1290 webOfTrustUpdater.stop();
1291 updateChecker.stop();
1292 soneDownloader.stop();
1293 identityManager.stop();
1294 soneDownloaders.shutdownNow();
1302 * Saves the given Sone. This will persist all local settings for the given
1303 * Sone, such as the friends list and similar, private options.
1308 private synchronized void saveSone(Sone sone) {
1309 if (!sone.isLocal()) {
1310 logger.log(Level.FINE, format("Tried to save non-local Sone: %s", sone));
1313 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1314 logger.log(Level.WARNING, format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1318 logger.log(Level.INFO, format("Saving Sone: %s", sone));
1320 /* save Sone into configuration. */
1321 String sonePrefix = "Sone/" + sone.getId();
1322 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1323 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1326 Profile profile = sone.getProfile();
1327 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1328 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1329 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1330 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1331 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1332 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1333 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1335 /* save profile fields. */
1336 int fieldCounter = 0;
1337 for (Field profileField : profile.getFields()) {
1338 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1339 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1340 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1342 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1345 int postCounter = 0;
1346 for (Post post : sone.getPosts()) {
1347 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1348 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1349 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1350 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1351 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1353 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1356 int replyCounter = 0;
1357 for (PostReply reply : sone.getReplies()) {
1358 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1359 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1360 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1361 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1362 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1364 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1366 /* save post likes. */
1367 int postLikeCounter = 0;
1368 for (String postId : sone.getLikedPostIds()) {
1369 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1371 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1373 /* save reply likes. */
1374 int replyLikeCounter = 0;
1375 for (String replyId : sone.getLikedReplyIds()) {
1376 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1378 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1381 int friendCounter = 0;
1382 for (String friendId : sone.getFriends()) {
1383 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1385 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1387 /* save albums. first, collect in a flat structure, top-level first. */
1388 List<Album> albums = from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1390 int albumCounter = 0;
1391 for (Album album : albums) {
1392 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1393 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1394 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1395 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1396 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1397 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage().transform(GET_ID).orNull());
1399 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1402 int imageCounter = 0;
1403 for (Album album : albums) {
1404 for (Image image : album.getImages()) {
1405 if (!image.isInserted()) {
1408 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1409 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1410 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1411 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1412 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1413 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1414 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1415 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1416 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1419 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1422 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1423 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1424 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1425 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1426 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1427 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars>getEnumOption("ShowCustomAvatars").get().name());
1429 configuration.save();
1431 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1433 logger.log(Level.INFO, format("Sone %s saved.", sone));
1434 } catch (ConfigurationException ce1) {
1435 logger.log(Level.WARNING, format("Could not save Sone: %s", sone), ce1);
1439 /** Saves the current options. */
1440 private void saveConfiguration() {
1441 synchronized (configuration) {
1442 if (storingConfiguration) {
1443 logger.log(Level.FINE, "Already storing configuration…");
1446 storingConfiguration = true;
1449 /* store the options first. */
1451 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1452 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1453 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1454 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1455 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1456 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1457 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1458 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1459 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1460 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1461 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1462 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1464 /* save known Sones. */
1465 int soneCounter = 0;
1466 synchronized (knownSones) {
1467 for (String knownSoneId : knownSones) {
1468 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1470 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1473 /* save Sone following times. */
1475 synchronized (soneFollowingTimes) {
1476 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1477 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1478 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1481 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1484 /* save bookmarked posts. */
1485 int bookmarkedPostCounter = 0;
1486 synchronized (bookmarkedPosts) {
1487 for (String bookmarkedPostId : bookmarkedPosts) {
1488 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1491 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1494 configuration.save();
1496 } catch (ConfigurationException ce1) {
1497 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1499 synchronized (configuration) {
1500 storingConfiguration = false;
1505 /** Loads the configuration. */
1506 private void loadConfiguration() {
1507 /* create options. */
1508 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1511 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1512 SoneInserter.setInsertionDelay(newValue);
1516 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1517 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1518 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1519 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1520 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1521 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1522 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1523 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1524 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1527 @SuppressWarnings("synthetic-access")
1528 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1529 fcpInterface.setActive(newValue);
1532 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1535 @SuppressWarnings("synthetic-access")
1536 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1537 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1542 loadConfigurationValue("InsertionDelay");
1543 loadConfigurationValue("PostsPerPage");
1544 loadConfigurationValue("ImagesPerPage");
1545 loadConfigurationValue("CharactersPerPost");
1546 loadConfigurationValue("PostCutOffLength");
1547 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1548 loadConfigurationValue("PositiveTrust");
1549 loadConfigurationValue("NegativeTrust");
1550 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1551 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1552 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1554 /* load known Sones. */
1555 int soneCounter = 0;
1557 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1558 if (knownSoneId == null) {
1561 synchronized (knownSones) {
1562 knownSones.add(knownSoneId);
1566 /* load Sone following times. */
1569 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1570 if (soneId == null) {
1573 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1574 synchronized (soneFollowingTimes) {
1575 soneFollowingTimes.put(soneId, time);
1580 /* load bookmarked posts. */
1581 int bookmarkedPostCounter = 0;
1583 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1584 if (bookmarkedPostId == null) {
1587 synchronized (bookmarkedPosts) {
1588 bookmarkedPosts.add(bookmarkedPostId);
1595 * Loads an {@link Integer} configuration value for the option with the given
1596 * name, logging validation failures.
1599 * The name of the option to load
1601 private void loadConfigurationValue(String optionName) {
1603 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1604 } catch (IllegalArgumentException iae1) {
1605 logger.log(Level.WARNING, format("Invalid value for %s in configuration, using default.", optionName));
1610 * Notifies the core that a new {@link OwnIdentity} was added.
1612 * @param ownIdentityAddedEvent
1616 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1617 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1618 logger.log(Level.FINEST, format("Adding OwnIdentity: %s", ownIdentity));
1619 if (ownIdentity.hasContext("Sone")) {
1620 database.storeIdentity(ownIdentity);
1621 addLocalSone(ownIdentity);
1626 * Notifies the core that an {@link OwnIdentity} was removed.
1628 * @param ownIdentityRemovedEvent
1632 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1633 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1634 logger.log(Level.FINEST, format("Removing OwnIdentity: %s", ownIdentity));
1635 trustedIdentities.removeAll(ownIdentity);
1639 * Notifies the core that a new {@link Identity} was added.
1641 * @param identityAddedEvent
1645 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1646 Identity identity = identityAddedEvent.identity();
1647 logger.log(Level.FINEST, format("Adding Identity: %s", identity));
1648 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1649 database.storeIdentity(identity);
1650 addRemoteSone(identity);
1654 * Notifies the core that an {@link Identity} was updated.
1656 * @param identityUpdatedEvent
1660 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1661 final Identity identity = identityUpdatedEvent.identity();
1662 database.storeIdentity(identity);
1663 soneDownloaders.execute(new Runnable() {
1666 @SuppressWarnings("synthetic-access")
1668 Optional<Sone> sone = getRemoteSone(identity.getId());
1669 sone.get().modify().setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.get().getLatestEdition())).update();
1670 soneDownloader.addSone(sone.get());
1671 soneDownloader.fetchSone(sone.get());
1677 * Notifies the core that an {@link Identity} was removed.
1679 * @param identityRemovedEvent
1683 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1684 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1685 Identity identity = identityRemovedEvent.identity();
1686 trustedIdentities.remove(ownIdentity, identity);
1687 boolean foundIdentity = false;
1688 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1689 if (trustedIdentity.getKey().equals(ownIdentity)) {
1692 if (trustedIdentity.getValue().contains(identity)) {
1693 foundIdentity = true;
1696 if (foundIdentity) {
1697 /* some local identity still trusts this identity, don’t remove. */
1700 Optional<Sone> sone = getSone(identity.getId());
1701 if (!sone.isPresent()) {
1702 /* TODO - we don’t have the Sone anymore. should this happen? */
1705 database.removePosts(sone.get());
1706 for (Post post : sone.get().getPosts()) {
1707 eventBus.post(new PostRemovedEvent(post));
1709 database.removePostReplies(sone.get());
1710 for (PostReply reply : sone.get().getReplies()) {
1711 eventBus.post(new PostReplyRemovedEvent(reply));
1713 eventBus.post(new SoneRemovedEvent(sone.get()));
1717 * Deletes the temporary image.
1719 * @param imageInsertFinishedEvent
1723 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1724 logger.log(Level.WARNING, format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1725 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1726 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1727 touchConfiguration();
1730 public Optional<PostCreated> postCreated() {
1731 return Optional.<PostCreated>of(new PostCreated() {
1733 public void postCreated(final Post post) {
1734 if (post.isKnown()) {
1737 eventBus.post(new NewPostFoundEvent(post));
1738 if (post.getSone().isLocal()) {
1739 localElementTicker.schedule(new Runnable() {
1742 markPostKnown(post);
1744 }, 10, TimeUnit.SECONDS);
1750 public Optional<PostReplyCreated> postReplyCreated() {
1751 return Optional.<PostReplyCreated>of(new PostReplyCreated() {
1753 public void postReplyCreated(final PostReply postReply) {
1754 if (postReply.isKnown()) {
1757 eventBus.post(new NewPostReplyFoundEvent(postReply));
1758 if (postReply.getSone().isLocal()) {
1759 localElementTicker.schedule(new Runnable() {
1766 postReplyUpdated().get().replyUpdated(postReply);
1768 }, 10, TimeUnit.SECONDS);
1774 public Optional<ReplyUpdated<PostReply>> postReplyUpdated() {
1775 return Optional.<ReplyUpdated<PostReply>>of(new ReplyUpdated<PostReply>() {
1777 public void replyUpdated(PostReply reply) {
1778 eventBus.post(new MarkPostReplyKnownEvent(reply));
1783 public Optional<ImageCreated> imageCreated() {
1784 return Optional.<ImageCreated>of(new ImageCreated() {
1786 public void imageCreated(Image image) {
1787 /* nothing happens here yet. */