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.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.EnumSet;
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.ConfigurationSoneParser.InvalidAlbumFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
50 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
51 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
52 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
54 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
55 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
56 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
57 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
58 import net.pterodactylus.sone.core.event.PostRemovedEvent;
59 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
60 import net.pterodactylus.sone.core.event.SoneLockedEvent;
61 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
63 import net.pterodactylus.sone.data.Album;
64 import net.pterodactylus.sone.data.Client;
65 import net.pterodactylus.sone.data.Image;
66 import net.pterodactylus.sone.data.Post;
67 import net.pterodactylus.sone.data.PostReply;
68 import net.pterodactylus.sone.data.Profile;
69 import net.pterodactylus.sone.data.Profile.Field;
70 import net.pterodactylus.sone.data.Reply;
71 import net.pterodactylus.sone.data.Sone;
72 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
73 import net.pterodactylus.sone.data.Sone.SoneStatus;
74 import net.pterodactylus.sone.data.TemporaryImage;
75 import net.pterodactylus.sone.database.AlbumBuilder;
76 import net.pterodactylus.sone.database.Database;
77 import net.pterodactylus.sone.database.DatabaseException;
78 import net.pterodactylus.sone.database.ImageBuilder;
79 import net.pterodactylus.sone.database.PostBuilder;
80 import net.pterodactylus.sone.database.PostProvider;
81 import net.pterodactylus.sone.database.PostReplyBuilder;
82 import net.pterodactylus.sone.database.PostReplyProvider;
83 import net.pterodactylus.sone.database.SoneBuilder;
84 import net.pterodactylus.sone.database.SoneProvider;
85 import net.pterodactylus.sone.freenet.wot.Identity;
86 import net.pterodactylus.sone.freenet.wot.IdentityManager;
87 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
93 import net.pterodactylus.sone.main.SonePlugin;
94 import net.pterodactylus.util.config.Configuration;
95 import net.pterodactylus.util.config.ConfigurationException;
96 import net.pterodactylus.util.service.AbstractService;
97 import net.pterodactylus.util.thread.NamedThreadFactory;
99 import com.google.common.annotations.VisibleForTesting;
100 import com.google.common.base.Function;
101 import com.google.common.base.Optional;
102 import com.google.common.collect.FluentIterable;
103 import com.google.common.collect.HashMultimap;
104 import com.google.common.collect.Multimap;
105 import com.google.common.collect.Multimaps;
106 import com.google.common.eventbus.EventBus;
107 import com.google.common.eventbus.Subscribe;
108 import com.google.inject.Inject;
109 import com.google.inject.Singleton;
114 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
117 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
120 private static final Logger logger = getLogger(Core.class.getName());
122 /** The start time. */
123 private final long startupTime = System.currentTimeMillis();
125 /** The preferences. */
126 private final Preferences preferences;
128 /** The event bus. */
129 private final EventBus eventBus;
131 /** The configuration. */
132 private final 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 private final Set<CompatibilityMode> compatibilityModes = EnumSet.noneOf(CompatibilityMode.class);
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /** All known Sones. */
176 private final Set<String> knownSones = new HashSet<String>();
178 /** The post database. */
179 private final Database database;
181 /** Trusted identities, sorted by own identities. */
182 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
184 /** All temporary images. */
185 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
187 /** Ticker for threads that mark own elements as known. */
188 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
190 /** The time the configuration was last touched. */
191 private volatile long lastConfigurationUpdate;
194 * Creates a new core.
196 * @param configuration
197 * The configuration of the core
198 * @param freenetInterface
199 * The freenet interface
200 * @param identityManager
201 * The identity manager
202 * @param webOfTrustUpdater
203 * The WebOfTrust updater
210 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
212 this.configuration = configuration;
213 this.freenetInterface = freenetInterface;
214 this.identityManager = identityManager;
215 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
216 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
217 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
218 this.webOfTrustUpdater = webOfTrustUpdater;
219 this.eventBus = eventBus;
220 this.database = database;
221 preferences = new Preferences(eventBus);
225 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
227 this.configuration = configuration;
228 this.freenetInterface = freenetInterface;
229 this.identityManager = identityManager;
230 this.soneDownloader = soneDownloader;
231 this.imageInserter = imageInserter;
232 this.updateChecker = updateChecker;
233 this.webOfTrustUpdater = webOfTrustUpdater;
234 this.eventBus = eventBus;
235 this.database = database;
236 preferences = new Preferences(eventBus);
244 * Returns the time Sone was started.
246 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
248 public long getStartupTime() {
253 * Returns the options used by the core.
255 * @return The options of the core
257 public Preferences getPreferences() {
262 * Returns the identity manager used by the core.
264 * @return The identity manager
266 public IdentityManager getIdentityManager() {
267 return identityManager;
271 * Returns the update checker.
273 * @return The update checker
275 public UpdateChecker getUpdateChecker() {
276 return updateChecker;
279 public boolean isCompatibilityMode(CompatibilityMode compatibilityMode) {
280 return compatibilityModes.contains(compatibilityMode);
283 public void setCompatibilityMode(CompatibilityMode compatibilityMode) {
284 compatibilityModes.add(compatibilityMode);
287 public void clearCompatibilityMod(CompatibilityMode compatibilityMode) {
288 compatibilityModes.remove(compatibilityMode);
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 (soneRescuers) {
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);
325 public SoneBuilder soneBuilder() {
326 return database.newSoneBuilder();
333 public Collection<Sone> getSones() {
334 return database.getSones();
338 public Function<String, Optional<Sone>> soneLoader() {
339 return database.soneLoader();
343 * Returns the Sone with the given ID, regardless whether it’s local or
347 * The ID of the Sone to get
348 * @return The Sone with the given ID, or {@code null} if there is no such
352 public Optional<Sone> getSone(String id) {
353 return database.getSone(id);
360 public Collection<Sone> getLocalSones() {
361 return database.getLocalSones();
365 * Returns the local Sone with the given ID, optionally creating a new Sone.
369 * @return The Sone with the given ID, or {@code null}
371 public Sone getLocalSone(String id) {
372 Optional<Sone> sone = database.getSone(id);
373 if (sone.isPresent() && sone.get().isLocal()) {
383 public Collection<Sone> getRemoteSones() {
384 return database.getRemoteSones();
388 * Returns the remote Sone with the given ID.
392 * The ID of the remote Sone to get
393 * @return The Sone with the given ID
395 public Sone getRemoteSone(String id) {
396 return database.getSone(id).orNull();
400 * Returns whether the given Sone has been modified.
403 * The Sone to check for modifications
404 * @return {@code true} if a modification has been detected in the Sone,
405 * {@code false} otherwise
407 public boolean isModifiedSone(Sone sone) {
408 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
412 * Returns the time when the given was first followed by any local Sone.
415 * The Sone to get the time for
416 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
417 * been followed, or {@link Long#MAX_VALUE}
419 public long getSoneFollowingTime(Sone sone) {
420 synchronized (soneFollowingTimes) {
421 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
426 * Returns a post builder.
428 * @return A new post builder
430 public PostBuilder postBuilder() {
431 return database.newPostBuilder();
438 public Optional<Post> getPost(String postId) {
439 return database.getPost(postId);
446 public Collection<Post> getPosts(String soneId) {
447 return database.getPosts(soneId);
454 public Collection<Post> getDirectedPosts(final String recipientId) {
455 checkNotNull(recipientId, "recipient must not be null");
456 return database.getDirectedPosts(recipientId);
460 * Returns a post reply builder.
462 * @return A new post reply builder
464 public PostReplyBuilder postReplyBuilder() {
465 return database.newPostReplyBuilder();
472 public Optional<PostReply> getPostReply(String replyId) {
473 return database.getPostReply(replyId);
480 public List<PostReply> getReplies(final String postId) {
481 return database.getReplies(postId);
485 * Returns all Sones that have liked the given post.
488 * The post to get the liking Sones for
489 * @return The Sones that like the given post
491 public Set<Sone> getLikes(Post post) {
492 Set<Sone> sones = new HashSet<Sone>();
493 for (Sone sone : getSones()) {
494 if (sone.getLikedPostIds().contains(post.getId())) {
502 * Returns all Sones that have liked the given reply.
505 * The reply to get the liking Sones for
506 * @return The Sones that like the given reply
508 public Set<Sone> getLikes(PostReply reply) {
509 Set<Sone> sones = new HashSet<Sone>();
510 for (Sone sone : getSones()) {
511 if (sone.getLikedReplyIds().contains(reply.getId())) {
519 * Returns whether the given post is bookmarked.
523 * @return {@code true} if the given post is bookmarked, {@code false}
526 public boolean isBookmarked(Post post) {
527 return database.isPostBookmarked(post);
531 * Returns all currently known bookmarked posts.
533 * @return All bookmarked posts
535 public Set<Post> getBookmarkedPosts() {
536 return database.getBookmarkedPosts();
539 public AlbumBuilder albumBuilder() {
540 return database.newAlbumBuilder();
544 * Returns the album with the given ID, optionally creating a new album if
545 * an album with the given ID can not be found.
548 * The ID of the album
549 * @return The album with the given ID, or {@code null} if no album with the
552 public Album getAlbum(String albumId) {
553 return database.getAlbum(albumId).orNull();
556 public ImageBuilder imageBuilder() {
557 return database.newImageBuilder();
561 * Returns the image with the given ID, creating it if necessary.
564 * The ID of the image
565 * @return The image with the given ID
567 public Image getImage(String imageId) {
568 return getImage(imageId, true);
572 * Returns the image with the given ID, optionally creating it if it does
576 * The ID of the image
578 * {@code true} to create an image if none exists with the given
580 * @return The image with the given ID, or {@code null} if none exists and
583 public Image getImage(String imageId, boolean create) {
584 Optional<Image> image = database.getImage(imageId);
585 if (image.isPresent()) {
591 Image newImage = database.newImageBuilder().withId(imageId).build();
592 database.storeImage(newImage);
597 * Returns the temporary image with the given ID.
600 * The ID of the temporary image
601 * @return The temporary image, or {@code null} if there is no temporary
602 * image with the given ID
604 public TemporaryImage getTemporaryImage(String imageId) {
605 synchronized (temporaryImages) {
606 return temporaryImages.get(imageId);
615 * Locks the given Sone. A locked Sone will not be inserted by
616 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
622 public void lockSone(Sone sone) {
623 synchronized (lockedSones) {
624 if (lockedSones.add(sone)) {
625 eventBus.post(new SoneLockedEvent(sone));
631 * Unlocks the given Sone.
633 * @see #lockSone(Sone)
637 public void unlockSone(Sone sone) {
638 synchronized (lockedSones) {
639 if (lockedSones.remove(sone)) {
640 eventBus.post(new SoneUnlockedEvent(sone));
646 * Adds a local Sone from the given own identity.
649 * The own identity to create a Sone from
650 * @return The added (or already existing) Sone
652 public Sone addLocalSone(OwnIdentity ownIdentity) {
653 if (ownIdentity == null) {
654 logger.log(Level.WARNING, "Given OwnIdentity is null!");
657 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
658 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
659 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
660 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
661 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
663 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
664 eventBus.register(soneInserter);
665 synchronized (soneInserters) {
666 soneInserters.put(sone, soneInserter);
669 database.storeSone(sone);
670 sone.setStatus(SoneStatus.idle);
671 soneInserter.start();
676 * Creates a new Sone for the given own identity.
679 * The own identity to create a Sone for
680 * @return The created Sone
682 public Sone createSone(OwnIdentity ownIdentity) {
683 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
684 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
687 Sone sone = addLocalSone(ownIdentity);
689 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
690 touchConfiguration();
695 * Adds the Sone of the given identity.
698 * The identity whose Sone to add
699 * @return The added or already existing Sone
701 public Sone addRemoteSone(Identity identity) {
702 if (identity == null) {
703 logger.log(Level.WARNING, "Given Identity is null!");
706 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
707 long latestEdition = fromNullable(tryParse(property)).or(0L);
708 Optional<Sone> existingSone = getSone(identity.getId());
709 if (existingSone.isPresent() && existingSone.get().isLocal()) {
710 return existingSone.get();
712 boolean newSone = !existingSone.isPresent();
713 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
714 sone.setLatestEdition(latestEdition);
716 synchronized (knownSones) {
717 newSone = !knownSones.contains(sone.getId());
719 sone.setKnown(!newSone);
721 eventBus.post(new NewSoneFoundEvent(sone));
722 for (Sone localSone : getLocalSones()) {
723 if (localSone.getOptions().isAutoFollow()) {
724 followSone(localSone, sone.getId());
729 database.storeSone(sone);
730 soneDownloader.addSone(sone);
731 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
736 * Lets the given local Sone follow the Sone with the given ID.
739 * The local Sone that should follow another Sone
741 * The ID of the Sone to follow
743 public void followSone(Sone sone, String soneId) {
744 checkNotNull(sone, "sone must not be null");
745 checkNotNull(soneId, "soneId must not be null");
746 database.addFriend(sone, soneId);
747 synchronized (soneFollowingTimes) {
748 if (!soneFollowingTimes.containsKey(soneId)) {
749 long now = System.currentTimeMillis();
750 soneFollowingTimes.put(soneId, now);
751 Optional<Sone> followedSone = getSone(soneId);
752 if (!followedSone.isPresent()) {
755 for (Post post : followedSone.get().getPosts()) {
756 if (post.getTime() < now) {
760 for (PostReply reply : followedSone.get().getReplies()) {
761 if (reply.getTime() < now) {
762 markReplyKnown(reply);
767 touchConfiguration();
771 * Lets the given local Sone unfollow the Sone with the given ID.
774 * The local Sone that should unfollow another Sone
776 * The ID of the Sone being unfollowed
778 public void unfollowSone(Sone sone, String soneId) {
779 checkNotNull(sone, "sone must not be null");
780 checkNotNull(soneId, "soneId must not be null");
781 database.removeFriend(sone, soneId);
782 boolean unfollowedSoneStillFollowed = false;
783 for (Sone localSone : getLocalSones()) {
784 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
786 if (!unfollowedSoneStillFollowed) {
787 synchronized (soneFollowingTimes) {
788 soneFollowingTimes.remove(soneId);
791 touchConfiguration();
795 * Sets the trust value of the given origin Sone for the target Sone.
802 * The trust value (from {@code -100} to {@code 100})
804 public void setTrust(Sone origin, Sone target, int trustValue) {
805 checkNotNull(origin, "origin must not be null");
806 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
807 checkNotNull(target, "target must not be null");
808 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
809 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
813 * Removes any trust assignment for the given target Sone.
820 public void removeTrust(Sone origin, Sone target) {
821 checkNotNull(origin, "origin must not be null");
822 checkNotNull(target, "target must not be null");
823 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
824 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
828 * Assigns the configured positive trust value for the given target.
835 public void trustSone(Sone origin, Sone target) {
836 setTrust(origin, target, preferences.getPositiveTrust());
840 * Assigns the configured negative trust value for the given target.
847 public void distrustSone(Sone origin, Sone target) {
848 setTrust(origin, target, preferences.getNegativeTrust());
852 * Removes the trust assignment for the given target.
859 public void untrustSone(Sone origin, Sone target) {
860 removeTrust(origin, target);
864 * Updates the stored Sone with the given Sone.
869 public void updateSone(Sone sone) {
870 updateSone(sone, false);
874 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
875 * {@code true}, an older Sone than the current Sone can be given to restore
880 * @param soneRescueMode
881 * {@code true} if the stored Sone should be updated regardless
882 * of the age of the given Sone
884 public void updateSone(final Sone sone, boolean soneRescueMode) {
885 Optional<Sone> storedSone = getSone(sone.getId());
886 if (storedSone.isPresent()) {
887 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
888 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
891 List<Object> events =
892 collectEventsForChangesInSone(storedSone.get(), sone);
893 database.storeSone(sone);
894 for (Object event : events) {
895 eventBus.post(event);
897 sone.setOptions(storedSone.get().getOptions());
898 sone.setKnown(storedSone.get().isKnown());
899 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
900 if (sone.isLocal()) {
901 touchConfiguration();
906 private List<Object> collectEventsForChangesInSone(Sone oldSone,
907 final Sone newSone) {
908 final List<Object> events = new ArrayList<Object>();
909 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
911 soneChangeDetector.onNewPosts(new PostProcessor() {
913 public void processPost(Post post) {
914 if (post.getTime() < getSoneFollowingTime(newSone)) {
916 } else if (!post.isKnown()) {
917 events.add(new NewPostFoundEvent(post));
921 soneChangeDetector.onRemovedPosts(new PostProcessor() {
923 public void processPost(Post post) {
924 events.add(new PostRemovedEvent(post));
927 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
929 public void processPostReply(PostReply postReply) {
930 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
931 postReply.setKnown(true);
932 } else if (!postReply.isKnown()) {
933 events.add(new NewPostReplyFoundEvent(postReply));
937 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
939 public void processPostReply(PostReply postReply) {
940 events.add(new PostReplyRemovedEvent(postReply));
943 soneChangeDetector.detectChanges(newSone);
948 * Deletes the given Sone. This will remove the Sone from the
949 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
950 * remove the context from its identity.
955 public void deleteSone(Sone sone) {
956 if (!(sone.getIdentity() instanceof OwnIdentity)) {
957 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
960 if (!getLocalSones().contains(sone)) {
961 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
964 SoneInserter soneInserter = soneInserters.remove(sone);
966 database.removeSone(sone);
967 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
968 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
970 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
971 } catch (ConfigurationException ce1) {
972 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
977 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
978 * known} before, a {@link MarkSoneKnownEvent} is fired.
981 * The Sone to mark as known
983 public void markSoneKnown(Sone sone) {
984 if (!sone.isKnown()) {
986 synchronized (knownSones) {
987 knownSones.add(sone.getId());
989 eventBus.post(new MarkSoneKnownEvent(sone));
990 touchConfiguration();
995 * Loads and updates the given Sone from the configuration. If any error is
996 * encountered, loading is aborted and the given Sone is not changed.
999 * The Sone to load and update
1001 public void loadSone(Sone sone) {
1002 if (!sone.isLocal()) {
1003 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1006 logger.info(String.format("Loading local Sone: %s", sone));
1009 String sonePrefix = "Sone/" + sone.getId();
1010 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1011 if (soneTime == null) {
1012 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1015 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1018 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1019 Profile profile = configurationSoneParser.parseProfile();
1022 Collection<Post> posts;
1024 posts = configurationSoneParser.parsePosts(database);
1025 } catch (InvalidPostFound ipf) {
1026 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1031 Collection<PostReply> replies;
1033 replies = configurationSoneParser.parsePostReplies(database);
1034 } catch (InvalidPostReplyFound iprf) {
1035 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1039 /* load post likes. */
1040 Set<String> likedPostIds =
1041 configurationSoneParser.parseLikedPostIds();
1043 /* load reply likes. */
1044 Set<String> likedReplyIds =
1045 configurationSoneParser.parseLikedPostReplyIds();
1048 List<Album> topLevelAlbums;
1051 configurationSoneParser.parseTopLevelAlbums(database);
1052 } catch (InvalidAlbumFound iaf) {
1053 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1055 } catch (InvalidParentAlbumFound ipaf) {
1056 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1057 ipaf.getAlbumParentId()));
1063 configurationSoneParser.parseImages(database);
1064 } catch (InvalidImageFound iif) {
1065 logger.log(WARNING, "Invalid image found, aborting load!");
1067 } catch (InvalidParentAlbumFound ipaf) {
1068 logger.log(Level.WARNING,
1069 format("Invalid album image (%s) encountered, aborting load!",
1070 ipaf.getAlbumParentId()));
1075 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1076 if (avatarId != null) {
1077 final Map<String, Image> images =
1078 configurationSoneParser.getImages();
1079 profile.setAvatar(images.get(avatarId));
1083 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1084 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1085 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1086 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1087 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1088 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1090 /* if we’re still here, Sone was loaded successfully. */
1091 synchronized (sone) {
1092 sone.setTime(soneTime);
1093 sone.setProfile(profile);
1094 sone.setPosts(posts);
1095 sone.setReplies(replies);
1096 sone.setLikePostIds(likedPostIds);
1097 sone.setLikeReplyIds(likedReplyIds);
1098 for (Album album : sone.getRootAlbum().getAlbums()) {
1099 sone.getRootAlbum().removeAlbum(album);
1101 for (Album album : topLevelAlbums) {
1102 sone.getRootAlbum().addAlbum(album);
1104 synchronized (soneInserters) {
1105 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1108 for (Post post : posts) {
1109 post.setKnown(true);
1111 for (PostReply reply : replies) {
1112 reply.setKnown(true);
1115 logger.info(String.format("Sone loaded successfully: %s", sone));
1119 * Creates a new post.
1122 * The Sone that creates the post
1124 * The recipient Sone, or {@code null} if this post does not have
1127 * The text of the post
1128 * @return The created post
1130 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1131 checkNotNull(text, "text must not be null");
1132 checkArgument(text.trim().length() > 0, "text must not be empty");
1133 if (!sone.isLocal()) {
1134 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1137 PostBuilder postBuilder = database.newPostBuilder();
1138 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1139 if (recipient.isPresent()) {
1140 postBuilder.to(recipient.get().getId());
1142 final Post post = postBuilder.build();
1143 database.storePost(post);
1144 eventBus.post(new NewPostFoundEvent(post));
1146 touchConfiguration();
1147 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1152 * Deletes the given post.
1155 * The post to delete
1157 public void deletePost(Post post) {
1158 if (!post.getSone().isLocal()) {
1159 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1162 database.removePost(post);
1163 eventBus.post(new PostRemovedEvent(post));
1164 markPostKnown(post);
1165 touchConfiguration();
1169 * Marks the given post as known, if it is currently not a known post
1170 * (according to {@link Post#isKnown()}).
1173 * The post to mark as known
1175 public void markPostKnown(Post post) {
1176 post.setKnown(true);
1177 eventBus.post(new MarkPostKnownEvent(post));
1178 touchConfiguration();
1179 for (PostReply reply : getReplies(post.getId())) {
1180 markReplyKnown(reply);
1184 public void bookmarkPost(Post post) {
1185 database.bookmarkPost(post);
1189 * Removes the given post from the bookmarks.
1192 * The post to unbookmark
1194 public void unbookmarkPost(Post post) {
1195 database.unbookmarkPost(post);
1199 * Creates a new reply.
1202 * The Sone that creates the reply
1204 * The post that this reply refers to
1206 * The text of the reply
1207 * @return The created reply
1209 public PostReply createReply(Sone sone, Post post, String text) {
1210 checkNotNull(text, "text must not be null");
1211 checkArgument(text.trim().length() > 0, "text must not be empty");
1212 if (!sone.isLocal()) {
1213 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1216 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1217 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1218 final PostReply reply = postReplyBuilder.build();
1219 database.storePostReply(reply);
1220 eventBus.post(new NewPostReplyFoundEvent(reply));
1221 sone.addReply(reply);
1222 touchConfiguration();
1223 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1228 * Deletes the given reply.
1231 * The reply to delete
1233 public void deleteReply(PostReply reply) {
1234 Sone sone = reply.getSone();
1235 if (!sone.isLocal()) {
1236 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1239 database.removePostReply(reply);
1240 markReplyKnown(reply);
1241 sone.removeReply(reply);
1242 touchConfiguration();
1246 * Marks the given reply as known, if it is currently not a known reply
1247 * (according to {@link Reply#isKnown()}).
1250 * The reply to mark as known
1252 public void markReplyKnown(PostReply reply) {
1253 boolean previouslyKnown = reply.isKnown();
1254 reply.setKnown(true);
1255 eventBus.post(new MarkPostReplyKnownEvent(reply));
1256 if (!previouslyKnown) {
1257 touchConfiguration();
1262 * Creates a new album for the given Sone.
1265 * The Sone to create the album for
1267 * The parent of the album (may be {@code null} to create a
1269 * @return The new album
1271 public Album createAlbum(Sone sone, Album parent) {
1272 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1273 database.storeAlbum(album);
1274 parent.addAlbum(album);
1279 * Deletes the given album. The owner of the album has to be a local Sone,
1280 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1283 * The album to remove
1285 public void deleteAlbum(Album album) {
1286 checkNotNull(album, "album must not be null");
1287 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1288 if (!album.isEmpty()) {
1291 album.getParent().removeAlbum(album);
1292 database.removeAlbum(album);
1293 touchConfiguration();
1297 * Creates a new image.
1300 * The Sone creating the image
1302 * The album the image will be inserted into
1303 * @param temporaryImage
1304 * The temporary image to create the image from
1305 * @return The newly created image
1307 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1308 checkNotNull(sone, "sone must not be null");
1309 checkNotNull(album, "album must not be null");
1310 checkNotNull(temporaryImage, "temporaryImage must not be null");
1311 checkArgument(sone.isLocal(), "sone must be a local Sone");
1312 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1313 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1314 album.addImage(image);
1315 database.storeImage(image);
1316 imageInserter.insertImage(temporaryImage, image);
1321 * Deletes the given image. This method will also delete a matching
1324 * @see #deleteTemporaryImage(String)
1326 * The image to delete
1328 public void deleteImage(Image image) {
1329 checkNotNull(image, "image must not be null");
1330 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1331 deleteTemporaryImage(image.getId());
1332 image.getAlbum().removeImage(image);
1333 database.removeImage(image);
1334 touchConfiguration();
1338 * Creates a new temporary image.
1341 * The MIME type of the temporary image
1343 * The encoded data of the image
1344 * @return The temporary image
1346 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1347 TemporaryImage temporaryImage = new TemporaryImage();
1348 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1349 synchronized (temporaryImages) {
1350 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1352 return temporaryImage;
1356 * Deletes the temporary image with the given ID.
1359 * The ID of the temporary image to delete
1361 public void deleteTemporaryImage(String imageId) {
1362 checkNotNull(imageId, "imageId must not be null");
1363 synchronized (temporaryImages) {
1364 temporaryImages.remove(imageId);
1366 Image image = getImage(imageId, false);
1367 if (image != null) {
1368 imageInserter.cancelImageInsert(image);
1373 * Notifies the core that the configuration, either of the core or of a
1374 * single local Sone, has changed, and that the configuration should be
1377 public void touchConfiguration() {
1378 lastConfigurationUpdate = System.currentTimeMillis();
1389 public void serviceStart() {
1390 loadConfiguration();
1391 updateChecker.start();
1392 identityManager.start();
1393 webOfTrustUpdater.init();
1394 webOfTrustUpdater.start();
1402 public void serviceRun() {
1403 long lastSaved = System.currentTimeMillis();
1404 while (!shouldStop()) {
1406 long now = System.currentTimeMillis();
1407 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1408 for (Sone localSone : getLocalSones()) {
1409 saveSone(localSone);
1411 saveConfiguration();
1421 public void serviceStop() {
1422 localElementTicker.shutdownNow();
1423 synchronized (soneInserters) {
1424 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1425 soneInserter.getValue().stop();
1426 saveSone(soneInserter.getKey());
1429 synchronized (soneRescuers) {
1430 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1434 saveConfiguration();
1436 webOfTrustUpdater.stop();
1437 updateChecker.stop();
1438 soneDownloader.stop();
1439 soneDownloaders.shutdown();
1440 identityManager.stop();
1448 * Saves the given Sone. This will persist all local settings for the given
1449 * Sone, such as the friends list and similar, private options.
1454 private synchronized void saveSone(Sone sone) {
1455 if (!sone.isLocal()) {
1456 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1459 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1460 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1464 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1466 /* save Sone into configuration. */
1467 String sonePrefix = "Sone/" + sone.getId();
1468 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1469 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1472 Profile profile = sone.getProfile();
1473 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1474 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1475 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1476 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1477 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1478 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1479 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1481 /* save profile fields. */
1482 int fieldCounter = 0;
1483 for (Field profileField : profile.getFields()) {
1484 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1485 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1486 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1488 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1491 int postCounter = 0;
1492 for (Post post : sone.getPosts()) {
1493 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1494 configuration.getStringValue(postPrefix + "/ID").setValue(post.getInternalId());
1495 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1496 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1497 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1499 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1502 int replyCounter = 0;
1503 for (PostReply reply : sone.getReplies()) {
1504 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1505 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1506 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1507 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1508 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1510 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1512 /* save post likes. */
1513 int postLikeCounter = 0;
1514 for (String postId : sone.getLikedPostIds()) {
1515 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1517 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1519 /* save reply likes. */
1520 int replyLikeCounter = 0;
1521 for (String replyId : sone.getLikedReplyIds()) {
1522 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1524 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1526 /* save albums. first, collect in a flat structure, top-level first. */
1527 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1529 int albumCounter = 0;
1530 for (Album album : albums) {
1531 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1532 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getInternalId());
1533 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1534 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1535 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1536 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1538 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1541 int imageCounter = 0;
1542 for (Album album : albums) {
1543 for (Image image : album.getImages()) {
1544 if (!image.isInserted()) {
1547 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1548 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getInternalId());
1549 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getInternalId());
1550 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1551 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1552 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1553 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1554 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1555 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1558 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1561 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1562 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1563 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1564 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1565 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1566 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1568 configuration.save();
1570 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1572 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1573 } catch (ConfigurationException ce1) {
1574 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1579 * Saves the current options.
1581 private void saveConfiguration() {
1582 synchronized (configuration) {
1583 if (storingConfiguration) {
1584 logger.log(Level.FINE, "Already storing configuration…");
1587 storingConfiguration = true;
1590 /* store the options first. */
1592 preferences.saveTo(configuration);
1594 /* save known Sones. */
1595 int soneCounter = 0;
1596 synchronized (knownSones) {
1597 for (String knownSoneId : knownSones) {
1598 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1600 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1603 /* save Sone following times. */
1605 synchronized (soneFollowingTimes) {
1606 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1607 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1608 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1611 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1614 /* save known posts. */
1618 configuration.save();
1620 } catch (ConfigurationException ce1) {
1621 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1622 } catch (DatabaseException de1) {
1623 logger.log(Level.SEVERE, "Could not save database!", de1);
1625 synchronized (configuration) {
1626 storingConfiguration = false;
1632 * Loads the configuration.
1634 private void loadConfiguration() {
1635 new PreferencesLoader(preferences).loadFrom(configuration);
1637 /* load known Sones. */
1638 int soneCounter = 0;
1640 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1641 if (knownSoneId == null) {
1644 synchronized (knownSones) {
1645 knownSones.add(knownSoneId);
1649 /* load Sone following times. */
1652 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1653 if (soneId == null) {
1656 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1657 synchronized (soneFollowingTimes) {
1658 soneFollowingTimes.put(soneId, time);
1665 * Notifies the core that a new {@link OwnIdentity} was added.
1667 * @param ownIdentityAddedEvent
1671 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1672 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1673 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1674 if (ownIdentity.hasContext("Sone")) {
1675 addLocalSone(ownIdentity);
1680 * Notifies the core that an {@link OwnIdentity} was removed.
1682 * @param ownIdentityRemovedEvent
1686 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1687 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1688 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1689 trustedIdentities.removeAll(ownIdentity);
1693 * Notifies the core that a new {@link Identity} was added.
1695 * @param identityAddedEvent
1699 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1700 Identity identity = identityAddedEvent.identity();
1701 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1702 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1703 addRemoteSone(identity);
1707 * Notifies the core that an {@link Identity} was updated.
1709 * @param identityUpdatedEvent
1713 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1714 Identity identity = identityUpdatedEvent.identity();
1715 final Sone sone = getRemoteSone(identity.getId());
1716 if (sone.isLocal()) {
1719 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1720 soneDownloader.addSone(sone);
1721 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1725 * Notifies the core that an {@link Identity} was removed.
1727 * @param identityRemovedEvent
1731 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1732 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1733 Identity identity = identityRemovedEvent.identity();
1734 trustedIdentities.remove(ownIdentity, identity);
1735 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1736 if (trustedIdentity.getKey().equals(ownIdentity)) {
1739 if (trustedIdentity.getValue().contains(identity)) {
1743 Optional<Sone> sone = getSone(identity.getId());
1744 if (!sone.isPresent()) {
1745 /* TODO - we don’t have the Sone anymore. should this happen? */
1748 database.removeSone(sone.get());
1749 eventBus.post(new SoneRemovedEvent(sone.get()));
1753 * Deletes the temporary image.
1755 * @param imageInsertFinishedEvent
1759 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1760 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1761 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1762 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1763 touchConfiguration();
1767 class MarkPostKnown implements Runnable {
1769 private final Post post;
1771 public MarkPostKnown(Post post) {
1777 markPostKnown(post);
1783 class MarkReplyKnown implements Runnable {
1785 private final PostReply postReply;
1787 public MarkReplyKnown(PostReply postReply) {
1788 this.postReply = postReply;
1793 markReplyKnown(postReply);