2 * Sone - Core.java - Copyright © 2010–2016 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.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
48 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
50 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
51 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
52 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
54 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
55 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
56 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
57 import net.pterodactylus.sone.core.event.PostRemovedEvent;
58 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneLockedEvent;
60 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
61 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
62 import net.pterodactylus.sone.data.Album;
63 import net.pterodactylus.sone.data.Client;
64 import net.pterodactylus.sone.data.Image;
65 import net.pterodactylus.sone.data.Post;
66 import net.pterodactylus.sone.data.PostReply;
67 import net.pterodactylus.sone.data.Profile;
68 import net.pterodactylus.sone.data.Profile.Field;
69 import net.pterodactylus.sone.data.Reply;
70 import net.pterodactylus.sone.data.Sone;
71 import net.pterodactylus.sone.data.Sone.SoneStatus;
72 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
73 import net.pterodactylus.sone.data.TemporaryImage;
74 import net.pterodactylus.sone.database.AlbumBuilder;
75 import net.pterodactylus.sone.database.Database;
76 import net.pterodactylus.sone.database.DatabaseException;
77 import net.pterodactylus.sone.database.ImageBuilder;
78 import net.pterodactylus.sone.database.PostBuilder;
79 import net.pterodactylus.sone.database.PostProvider;
80 import net.pterodactylus.sone.database.PostReplyBuilder;
81 import net.pterodactylus.sone.database.PostReplyProvider;
82 import net.pterodactylus.sone.database.SoneBuilder;
83 import net.pterodactylus.sone.database.SoneProvider;
84 import net.pterodactylus.sone.freenet.wot.Identity;
85 import net.pterodactylus.sone.freenet.wot.IdentityManager;
86 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
92 import net.pterodactylus.sone.main.SonePlugin;
93 import net.pterodactylus.util.config.Configuration;
94 import net.pterodactylus.util.config.ConfigurationException;
95 import net.pterodactylus.util.service.AbstractService;
96 import net.pterodactylus.util.thread.NamedThreadFactory;
98 import com.google.common.annotations.VisibleForTesting;
99 import com.google.common.base.Function;
100 import com.google.common.base.Optional;
101 import com.google.common.collect.FluentIterable;
102 import com.google.common.collect.HashMultimap;
103 import com.google.common.collect.Multimap;
104 import com.google.common.collect.Multimaps;
105 import com.google.common.eventbus.EventBus;
106 import com.google.common.eventbus.Subscribe;
107 import com.google.inject.Inject;
108 import com.google.inject.Singleton;
113 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
116 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
119 private static final Logger logger = getLogger(Core.class.getName());
121 /** The start time. */
122 private final long startupTime = System.currentTimeMillis();
124 /** The preferences. */
125 private final Preferences preferences;
127 /** The event bus. */
128 private final EventBus eventBus;
130 /** The configuration. */
131 private final Configuration configuration;
133 /** Whether we’re currently saving the configuration. */
134 private boolean storingConfiguration = false;
136 /** The identity manager. */
137 private final IdentityManager identityManager;
139 /** Interface to freenet. */
140 private final FreenetInterface freenetInterface;
142 /** The Sone downloader. */
143 private final SoneDownloader soneDownloader;
145 /** The image inserter. */
146 private final ImageInserter imageInserter;
148 /** Sone downloader thread-pool. */
149 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151 /** The update checker. */
152 private final UpdateChecker updateChecker;
154 /** The trust updater. */
155 private final WebOfTrustUpdater webOfTrustUpdater;
157 /** The times Sones were followed. */
158 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
160 /** Locked local Sones. */
161 /* synchronize on itself. */
162 private final Set<Sone> lockedSones = new HashSet<Sone>();
164 /** Sone inserters. */
165 /* synchronize access on this on sones. */
166 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
168 /** Sone rescuers. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
172 /** All known Sones. */
173 private final Set<String> knownSones = new HashSet<String>();
175 /** The post database. */
176 private final Database database;
178 /** Trusted identities, sorted by own identities. */
179 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
181 /** All temporary images. */
182 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
184 /** Ticker for threads that mark own elements as known. */
185 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
187 /** The time the configuration was last touched. */
188 private volatile long lastConfigurationUpdate;
191 * Creates a new core.
193 * @param configuration
194 * The configuration of the core
195 * @param freenetInterface
196 * The freenet interface
197 * @param identityManager
198 * The identity manager
199 * @param webOfTrustUpdater
200 * The WebOfTrust updater
207 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
209 this.configuration = configuration;
210 this.freenetInterface = freenetInterface;
211 this.identityManager = identityManager;
212 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
213 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
214 this.updateChecker = updateChecker;
215 this.webOfTrustUpdater = webOfTrustUpdater;
216 this.eventBus = eventBus;
217 this.database = database;
218 preferences = new Preferences(eventBus);
222 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = soneDownloader;
228 this.imageInserter = imageInserter;
229 this.updateChecker = updateChecker;
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
232 this.database = database;
233 preferences = new Preferences(eventBus);
241 * Returns the time Sone was started.
243 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
245 public long getStartupTime() {
250 * Returns the options used by the core.
252 * @return The options of the core
254 public Preferences getPreferences() {
259 * Returns the identity manager used by the core.
261 * @return The identity manager
263 public IdentityManager getIdentityManager() {
264 return identityManager;
268 * Returns the update checker.
270 * @return The update checker
272 public UpdateChecker getUpdateChecker() {
273 return updateChecker;
277 * Returns the Sone rescuer for the given local Sone.
280 * The local Sone to get the rescuer for
281 * @return The Sone rescuer for the given Sone
283 public SoneRescuer getSoneRescuer(Sone sone) {
284 checkNotNull(sone, "sone must not be null");
285 checkArgument(sone.isLocal(), "sone must be local");
286 synchronized (soneRescuers) {
287 SoneRescuer soneRescuer = soneRescuers.get(sone);
288 if (soneRescuer == null) {
289 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
290 soneRescuers.put(sone, soneRescuer);
298 * Returns whether the given Sone is currently locked.
302 * @return {@code true} if the Sone is locked, {@code false} if it is not
304 public boolean isLocked(Sone sone) {
305 synchronized (lockedSones) {
306 return lockedSones.contains(sone);
310 public SoneBuilder soneBuilder() {
311 return database.newSoneBuilder();
318 public Collection<Sone> getSones() {
319 return database.getSones();
323 public Function<String, Optional<Sone>> soneLoader() {
324 return database.soneLoader();
328 * Returns the Sone with the given ID, regardless whether it’s local or
332 * The ID of the Sone to get
333 * @return The Sone with the given ID, or {@code null} if there is no such
337 public Optional<Sone> getSone(String id) {
338 return database.getSone(id);
345 public Collection<Sone> getLocalSones() {
346 return database.getLocalSones();
350 * Returns the local Sone with the given ID, optionally creating a new Sone.
354 * @return The Sone with the given ID, or {@code null}
356 public Sone getLocalSone(String id) {
357 Optional<Sone> sone = database.getSone(id);
358 if (sone.isPresent() && sone.get().isLocal()) {
368 public Collection<Sone> getRemoteSones() {
369 return database.getRemoteSones();
373 * Returns the remote Sone with the given ID.
377 * The ID of the remote Sone to get
378 * @return The Sone with the given ID
380 public Sone getRemoteSone(String id) {
381 return database.getSone(id).orNull();
385 * Returns whether the given Sone has been modified.
388 * The Sone to check for modifications
389 * @return {@code true} if a modification has been detected in the Sone,
390 * {@code false} otherwise
392 public boolean isModifiedSone(Sone sone) {
393 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
397 * Returns the time when the given was first followed by any local Sone.
400 * The Sone to get the time for
401 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
402 * been followed, or {@link Long#MAX_VALUE}
404 public long getSoneFollowingTime(Sone sone) {
405 synchronized (soneFollowingTimes) {
406 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
411 * Returns a post builder.
413 * @return A new post builder
415 public PostBuilder postBuilder() {
416 return database.newPostBuilder();
423 public Optional<Post> getPost(String postId) {
424 return database.getPost(postId);
431 public Collection<Post> getPosts(String soneId) {
432 return database.getPosts(soneId);
439 public Collection<Post> getDirectedPosts(final String recipientId) {
440 checkNotNull(recipientId, "recipient must not be null");
441 return database.getDirectedPosts(recipientId);
445 * Returns a post reply builder.
447 * @return A new post reply builder
449 public PostReplyBuilder postReplyBuilder() {
450 return database.newPostReplyBuilder();
457 public Optional<PostReply> getPostReply(String replyId) {
458 return database.getPostReply(replyId);
465 public List<PostReply> getReplies(final String postId) {
466 return database.getReplies(postId);
470 * Returns all Sones that have liked the given post.
473 * The post to get the liking Sones for
474 * @return The Sones that like the given post
476 public Set<Sone> getLikes(Post post) {
477 Set<Sone> sones = new HashSet<Sone>();
478 for (Sone sone : getSones()) {
479 if (sone.getLikedPostIds().contains(post.getId())) {
487 * Returns all Sones that have liked the given reply.
490 * The reply to get the liking Sones for
491 * @return The Sones that like the given reply
493 public Set<Sone> getLikes(PostReply reply) {
494 Set<Sone> sones = new HashSet<Sone>();
495 for (Sone sone : getSones()) {
496 if (sone.getLikedReplyIds().contains(reply.getId())) {
504 * Returns whether the given post is bookmarked.
508 * @return {@code true} if the given post is bookmarked, {@code false}
511 public boolean isBookmarked(Post post) {
512 return database.isPostBookmarked(post);
516 * Returns all currently known bookmarked posts.
518 * @return All bookmarked posts
520 public Set<Post> getBookmarkedPosts() {
521 return database.getBookmarkedPosts();
524 public AlbumBuilder albumBuilder() {
525 return database.newAlbumBuilder();
529 * Returns the album with the given ID, optionally creating a new album if
530 * an album with the given ID can not be found.
533 * The ID of the album
534 * @return The album with the given ID, or {@code null} if no album with the
537 public Album getAlbum(String albumId) {
538 return database.getAlbum(albumId).orNull();
541 public ImageBuilder imageBuilder() {
542 return database.newImageBuilder();
546 * Returns the image with the given ID, creating it if necessary.
549 * The ID of the image
550 * @return The image with the given ID
552 public Image getImage(String imageId) {
553 return getImage(imageId, true);
557 * Returns the image with the given ID, optionally creating it if it does
561 * The ID of the image
563 * {@code true} to create an image if none exists with the given
565 * @return The image with the given ID, or {@code null} if none exists and
568 public Image getImage(String imageId, boolean create) {
569 Optional<Image> image = database.getImage(imageId);
570 if (image.isPresent()) {
576 Image newImage = database.newImageBuilder().withId(imageId).build();
577 database.storeImage(newImage);
582 * Returns the temporary image with the given ID.
585 * The ID of the temporary image
586 * @return The temporary image, or {@code null} if there is no temporary
587 * image with the given ID
589 public TemporaryImage getTemporaryImage(String imageId) {
590 synchronized (temporaryImages) {
591 return temporaryImages.get(imageId);
600 * Locks the given Sone. A locked Sone will not be inserted by
601 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
607 public void lockSone(Sone sone) {
608 synchronized (lockedSones) {
609 if (lockedSones.add(sone)) {
610 eventBus.post(new SoneLockedEvent(sone));
616 * Unlocks the given Sone.
618 * @see #lockSone(Sone)
622 public void unlockSone(Sone sone) {
623 synchronized (lockedSones) {
624 if (lockedSones.remove(sone)) {
625 eventBus.post(new SoneUnlockedEvent(sone));
631 * Adds a local Sone from the given own identity.
634 * The own identity to create a Sone from
635 * @return The added (or already existing) Sone
637 public Sone addLocalSone(OwnIdentity ownIdentity) {
638 if (ownIdentity == null) {
639 logger.log(Level.WARNING, "Given OwnIdentity is null!");
642 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
643 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
644 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
645 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
646 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
648 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
649 eventBus.register(soneInserter);
650 synchronized (soneInserters) {
651 soneInserters.put(sone, soneInserter);
654 database.storeSone(sone);
655 sone.setStatus(SoneStatus.idle);
656 soneInserter.start();
661 * Creates a new Sone for the given own identity.
664 * The own identity to create a Sone for
665 * @return The created Sone
667 public Sone createSone(OwnIdentity ownIdentity) {
668 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
669 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
672 Sone sone = addLocalSone(ownIdentity);
674 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
675 touchConfiguration();
680 * Adds the Sone of the given identity.
683 * The identity whose Sone to add
684 * @return The added or already existing Sone
686 public Sone addRemoteSone(Identity identity) {
687 if (identity == null) {
688 logger.log(Level.WARNING, "Given Identity is null!");
691 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
692 long latestEdition = fromNullable(tryParse(property)).or(0L);
693 Optional<Sone> existingSone = getSone(identity.getId());
694 if (existingSone.isPresent() && existingSone.get().isLocal()) {
695 return existingSone.get();
697 boolean newSone = !existingSone.isPresent();
698 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
699 sone.setLatestEdition(latestEdition);
701 synchronized (knownSones) {
702 newSone = !knownSones.contains(sone.getId());
704 sone.setKnown(!newSone);
706 eventBus.post(new NewSoneFoundEvent(sone));
707 for (Sone localSone : getLocalSones()) {
708 if (localSone.getOptions().isAutoFollow()) {
709 followSone(localSone, sone.getId());
714 database.storeSone(sone);
715 soneDownloader.addSone(sone);
716 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
721 * Lets the given local Sone follow the Sone with the given ID.
724 * The local Sone that should follow another Sone
726 * The ID of the Sone to follow
728 public void followSone(Sone sone, String soneId) {
729 checkNotNull(sone, "sone must not be null");
730 checkNotNull(soneId, "soneId must not be null");
731 database.addFriend(sone, soneId);
732 synchronized (soneFollowingTimes) {
733 if (!soneFollowingTimes.containsKey(soneId)) {
734 long now = System.currentTimeMillis();
735 soneFollowingTimes.put(soneId, now);
736 Optional<Sone> followedSone = getSone(soneId);
737 if (!followedSone.isPresent()) {
740 for (Post post : followedSone.get().getPosts()) {
741 if (post.getTime() < now) {
745 for (PostReply reply : followedSone.get().getReplies()) {
746 if (reply.getTime() < now) {
747 markReplyKnown(reply);
752 touchConfiguration();
756 * Lets the given local Sone unfollow the Sone with the given ID.
759 * The local Sone that should unfollow another Sone
761 * The ID of the Sone being unfollowed
763 public void unfollowSone(Sone sone, String soneId) {
764 checkNotNull(sone, "sone must not be null");
765 checkNotNull(soneId, "soneId must not be null");
766 database.removeFriend(sone, soneId);
767 boolean unfollowedSoneStillFollowed = false;
768 for (Sone localSone : getLocalSones()) {
769 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
771 if (!unfollowedSoneStillFollowed) {
772 synchronized (soneFollowingTimes) {
773 soneFollowingTimes.remove(soneId);
776 touchConfiguration();
780 * Sets the trust value of the given origin Sone for the target Sone.
787 * The trust value (from {@code -100} to {@code 100})
789 public void setTrust(Sone origin, Sone target, int trustValue) {
790 checkNotNull(origin, "origin must not be null");
791 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
792 checkNotNull(target, "target must not be null");
793 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
794 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
798 * Removes any trust assignment for the given target Sone.
805 public void removeTrust(Sone origin, Sone target) {
806 checkNotNull(origin, "origin must not be null");
807 checkNotNull(target, "target must not be null");
808 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
809 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
813 * Assigns the configured positive trust value for the given target.
820 public void trustSone(Sone origin, Sone target) {
821 setTrust(origin, target, preferences.getPositiveTrust());
825 * Assigns the configured negative trust value for the given target.
832 public void distrustSone(Sone origin, Sone target) {
833 setTrust(origin, target, preferences.getNegativeTrust());
837 * Removes the trust assignment for the given target.
844 public void untrustSone(Sone origin, Sone target) {
845 removeTrust(origin, target);
849 * Updates the stored Sone with the given Sone.
854 public void updateSone(Sone sone) {
855 updateSone(sone, false);
859 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
860 * {@code true}, an older Sone than the current Sone can be given to restore
865 * @param soneRescueMode
866 * {@code true} if the stored Sone should be updated regardless
867 * of the age of the given Sone
869 public void updateSone(final Sone sone, boolean soneRescueMode) {
870 Optional<Sone> storedSone = getSone(sone.getId());
871 if (storedSone.isPresent()) {
872 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
873 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
876 List<Object> events =
877 collectEventsForChangesInSone(storedSone.get(), sone);
878 database.storeSone(sone);
879 for (Object event : events) {
880 eventBus.post(event);
882 sone.setOptions(storedSone.get().getOptions());
883 sone.setKnown(storedSone.get().isKnown());
884 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
885 if (sone.isLocal()) {
886 touchConfiguration();
891 private List<Object> collectEventsForChangesInSone(Sone oldSone,
892 final Sone newSone) {
893 final List<Object> events = new ArrayList<Object>();
894 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
896 soneChangeDetector.onNewPosts(new PostProcessor() {
898 public void processPost(Post post) {
899 if (post.getTime() < getSoneFollowingTime(newSone)) {
901 } else if (!post.isKnown()) {
902 events.add(new NewPostFoundEvent(post));
906 soneChangeDetector.onRemovedPosts(new PostProcessor() {
908 public void processPost(Post post) {
909 events.add(new PostRemovedEvent(post));
912 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
914 public void processPostReply(PostReply postReply) {
915 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
916 postReply.setKnown(true);
917 } else if (!postReply.isKnown()) {
918 events.add(new NewPostReplyFoundEvent(postReply));
922 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
924 public void processPostReply(PostReply postReply) {
925 events.add(new PostReplyRemovedEvent(postReply));
928 soneChangeDetector.detectChanges(newSone);
933 * Deletes the given Sone. This will remove the Sone from the
934 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
935 * remove the context from its identity.
940 public void deleteSone(Sone sone) {
941 if (!(sone.getIdentity() instanceof OwnIdentity)) {
942 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
945 if (!getLocalSones().contains(sone)) {
946 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
949 SoneInserter soneInserter = soneInserters.remove(sone);
951 database.removeSone(sone);
952 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
953 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
955 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
956 } catch (ConfigurationException ce1) {
957 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
962 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
963 * known} before, a {@link MarkSoneKnownEvent} is fired.
966 * The Sone to mark as known
968 public void markSoneKnown(Sone sone) {
969 if (!sone.isKnown()) {
971 synchronized (knownSones) {
972 knownSones.add(sone.getId());
974 eventBus.post(new MarkSoneKnownEvent(sone));
975 touchConfiguration();
980 * Loads and updates the given Sone from the configuration. If any error is
981 * encountered, loading is aborted and the given Sone is not changed.
984 * The Sone to load and update
986 public void loadSone(Sone sone) {
987 if (!sone.isLocal()) {
988 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
991 logger.info(String.format("Loading local Sone: %s", sone));
994 String sonePrefix = "Sone/" + sone.getId();
995 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
996 if (soneTime == null) {
997 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1000 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1003 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1004 Profile profile = configurationSoneParser.parseProfile();
1007 Collection<Post> posts;
1009 posts = configurationSoneParser.parsePosts(database);
1010 } catch (InvalidPostFound ipf) {
1011 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1016 Collection<PostReply> replies;
1018 replies = configurationSoneParser.parsePostReplies(database);
1019 } catch (InvalidPostReplyFound iprf) {
1020 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1024 /* load post likes. */
1025 Set<String> likedPostIds =
1026 configurationSoneParser.parseLikedPostIds();
1028 /* load reply likes. */
1029 Set<String> likedReplyIds =
1030 configurationSoneParser.parseLikedPostReplyIds();
1033 List<Album> topLevelAlbums;
1036 configurationSoneParser.parseTopLevelAlbums(database);
1037 } catch (InvalidAlbumFound iaf) {
1038 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1040 } catch (InvalidParentAlbumFound ipaf) {
1041 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1042 ipaf.getAlbumParentId()));
1048 configurationSoneParser.parseImages(database);
1049 } catch (InvalidImageFound iif) {
1050 logger.log(WARNING, "Invalid image found, aborting load!");
1052 } catch (InvalidParentAlbumFound ipaf) {
1053 logger.log(Level.WARNING,
1054 format("Invalid album image (%s) encountered, aborting load!",
1055 ipaf.getAlbumParentId()));
1060 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1061 if (avatarId != null) {
1062 final Map<String, Image> images =
1063 configurationSoneParser.getImages();
1064 profile.setAvatar(images.get(avatarId));
1068 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1069 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1070 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1071 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1072 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1073 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1074 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1076 /* if we’re still here, Sone was loaded successfully. */
1077 synchronized (sone) {
1078 sone.setTime(soneTime);
1079 sone.setProfile(profile);
1080 sone.setPosts(posts);
1081 sone.setReplies(replies);
1082 sone.setLikePostIds(likedPostIds);
1083 sone.setLikeReplyIds(likedReplyIds);
1084 for (Album album : sone.getRootAlbum().getAlbums()) {
1085 sone.getRootAlbum().removeAlbum(album);
1087 for (Album album : topLevelAlbums) {
1088 sone.getRootAlbum().addAlbum(album);
1090 synchronized (soneInserters) {
1091 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1094 for (Post post : posts) {
1095 post.setKnown(true);
1097 for (PostReply reply : replies) {
1098 reply.setKnown(true);
1101 logger.info(String.format("Sone loaded successfully: %s", sone));
1105 * Creates a new post.
1108 * The Sone that creates the post
1110 * The recipient Sone, or {@code null} if this post does not have
1113 * The text of the post
1114 * @return The created post
1116 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1117 checkNotNull(text, "text must not be null");
1118 checkArgument(text.trim().length() > 0, "text must not be empty");
1119 if (!sone.isLocal()) {
1120 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1123 PostBuilder postBuilder = database.newPostBuilder();
1124 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1125 if (recipient.isPresent()) {
1126 postBuilder.to(recipient.get().getId());
1128 final Post post = postBuilder.build();
1129 database.storePost(post);
1130 eventBus.post(new NewPostFoundEvent(post));
1132 touchConfiguration();
1133 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1138 * Deletes the given post.
1141 * The post to delete
1143 public void deletePost(Post post) {
1144 if (!post.getSone().isLocal()) {
1145 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1148 database.removePost(post);
1149 eventBus.post(new PostRemovedEvent(post));
1150 markPostKnown(post);
1151 touchConfiguration();
1155 * Marks the given post as known, if it is currently not a known post
1156 * (according to {@link Post#isKnown()}).
1159 * The post to mark as known
1161 public void markPostKnown(Post post) {
1162 post.setKnown(true);
1163 eventBus.post(new MarkPostKnownEvent(post));
1164 touchConfiguration();
1165 for (PostReply reply : getReplies(post.getId())) {
1166 markReplyKnown(reply);
1170 public void bookmarkPost(Post post) {
1171 database.bookmarkPost(post);
1175 * Removes the given post from the bookmarks.
1178 * The post to unbookmark
1180 public void unbookmarkPost(Post post) {
1181 database.unbookmarkPost(post);
1185 * Creates a new reply.
1188 * The Sone that creates the reply
1190 * The post that this reply refers to
1192 * The text of the reply
1193 * @return The created reply
1195 public PostReply createReply(Sone sone, Post post, String text) {
1196 checkNotNull(text, "text must not be null");
1197 checkArgument(text.trim().length() > 0, "text must not be empty");
1198 if (!sone.isLocal()) {
1199 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1202 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1203 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1204 final PostReply reply = postReplyBuilder.build();
1205 database.storePostReply(reply);
1206 eventBus.post(new NewPostReplyFoundEvent(reply));
1207 sone.addReply(reply);
1208 touchConfiguration();
1209 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1214 * Deletes the given reply.
1217 * The reply to delete
1219 public void deleteReply(PostReply reply) {
1220 Sone sone = reply.getSone();
1221 if (!sone.isLocal()) {
1222 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1225 database.removePostReply(reply);
1226 markReplyKnown(reply);
1227 sone.removeReply(reply);
1228 touchConfiguration();
1232 * Marks the given reply as known, if it is currently not a known reply
1233 * (according to {@link Reply#isKnown()}).
1236 * The reply to mark as known
1238 public void markReplyKnown(PostReply reply) {
1239 boolean previouslyKnown = reply.isKnown();
1240 reply.setKnown(true);
1241 eventBus.post(new MarkPostReplyKnownEvent(reply));
1242 if (!previouslyKnown) {
1243 touchConfiguration();
1248 * Creates a new album for the given Sone.
1251 * The Sone to create the album for
1253 * The parent of the album (may be {@code null} to create a
1255 * @return The new album
1257 public Album createAlbum(Sone sone, Album parent) {
1258 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1259 database.storeAlbum(album);
1260 parent.addAlbum(album);
1265 * Deletes the given album. The owner of the album has to be a local Sone,
1266 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1269 * The album to remove
1271 public void deleteAlbum(Album album) {
1272 checkNotNull(album, "album must not be null");
1273 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1274 if (!album.isEmpty()) {
1277 album.getParent().removeAlbum(album);
1278 database.removeAlbum(album);
1279 touchConfiguration();
1283 * Creates a new image.
1286 * The Sone creating the image
1288 * The album the image will be inserted into
1289 * @param temporaryImage
1290 * The temporary image to create the image from
1291 * @return The newly created image
1293 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1294 checkNotNull(sone, "sone must not be null");
1295 checkNotNull(album, "album must not be null");
1296 checkNotNull(temporaryImage, "temporaryImage must not be null");
1297 checkArgument(sone.isLocal(), "sone must be a local Sone");
1298 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1299 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1300 album.addImage(image);
1301 database.storeImage(image);
1302 imageInserter.insertImage(temporaryImage, image);
1307 * Deletes the given image. This method will also delete a matching
1310 * @see #deleteTemporaryImage(String)
1312 * The image to delete
1314 public void deleteImage(Image image) {
1315 checkNotNull(image, "image must not be null");
1316 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1317 deleteTemporaryImage(image.getId());
1318 image.getAlbum().removeImage(image);
1319 database.removeImage(image);
1320 touchConfiguration();
1324 * Creates a new temporary image.
1327 * The MIME type of the temporary image
1329 * The encoded data of the image
1330 * @return The temporary image
1332 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1333 TemporaryImage temporaryImage = new TemporaryImage();
1334 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1335 synchronized (temporaryImages) {
1336 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1338 return temporaryImage;
1342 * Deletes the temporary image with the given ID.
1345 * The ID of the temporary image to delete
1347 public void deleteTemporaryImage(String imageId) {
1348 checkNotNull(imageId, "imageId must not be null");
1349 synchronized (temporaryImages) {
1350 temporaryImages.remove(imageId);
1352 Image image = getImage(imageId, false);
1353 if (image != null) {
1354 imageInserter.cancelImageInsert(image);
1359 * Notifies the core that the configuration, either of the core or of a
1360 * single local Sone, has changed, and that the configuration should be
1363 public void touchConfiguration() {
1364 lastConfigurationUpdate = System.currentTimeMillis();
1375 public void serviceStart() {
1376 loadConfiguration();
1377 updateChecker.start();
1378 identityManager.start();
1379 webOfTrustUpdater.init();
1380 webOfTrustUpdater.start();
1388 public void serviceRun() {
1389 long lastSaved = System.currentTimeMillis();
1390 while (!shouldStop()) {
1392 long now = System.currentTimeMillis();
1393 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1394 for (Sone localSone : getLocalSones()) {
1395 saveSone(localSone);
1397 saveConfiguration();
1407 public void serviceStop() {
1408 localElementTicker.shutdownNow();
1409 synchronized (soneInserters) {
1410 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1411 soneInserter.getValue().stop();
1412 saveSone(soneInserter.getKey());
1415 synchronized (soneRescuers) {
1416 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1420 saveConfiguration();
1422 webOfTrustUpdater.stop();
1423 updateChecker.stop();
1424 soneDownloader.stop();
1425 soneDownloaders.shutdown();
1426 identityManager.stop();
1434 * Saves the given Sone. This will persist all local settings for the given
1435 * Sone, such as the friends list and similar, private options.
1440 private synchronized void saveSone(Sone sone) {
1441 if (!sone.isLocal()) {
1442 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1445 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1446 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1450 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1452 /* save Sone into configuration. */
1453 String sonePrefix = "Sone/" + sone.getId();
1454 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1455 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1458 Profile profile = sone.getProfile();
1459 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1460 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1461 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1462 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1463 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1464 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1465 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1467 /* save profile fields. */
1468 int fieldCounter = 0;
1469 for (Field profileField : profile.getFields()) {
1470 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1471 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1472 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1474 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1477 int postCounter = 0;
1478 for (Post post : sone.getPosts()) {
1479 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1480 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1481 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1482 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1483 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1485 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1488 int replyCounter = 0;
1489 for (PostReply reply : sone.getReplies()) {
1490 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1491 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1492 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1493 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1494 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1496 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1498 /* save post likes. */
1499 int postLikeCounter = 0;
1500 for (String postId : sone.getLikedPostIds()) {
1501 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1503 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1505 /* save reply likes. */
1506 int replyLikeCounter = 0;
1507 for (String replyId : sone.getLikedReplyIds()) {
1508 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1510 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1512 /* save albums. first, collect in a flat structure, top-level first. */
1513 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1515 int albumCounter = 0;
1516 for (Album album : albums) {
1517 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1518 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1519 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1520 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1521 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1523 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1526 int imageCounter = 0;
1527 for (Album album : albums) {
1528 for (Image image : album.getImages()) {
1529 if (!image.isInserted()) {
1532 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1533 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1534 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1535 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1536 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1537 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1538 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1539 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1540 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1543 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1546 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1547 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1548 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1549 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1550 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1551 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1552 configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1554 configuration.save();
1556 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1558 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1559 } catch (ConfigurationException ce1) {
1560 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1565 * Saves the current options.
1567 private void saveConfiguration() {
1568 synchronized (configuration) {
1569 if (storingConfiguration) {
1570 logger.log(Level.FINE, "Already storing configuration…");
1573 storingConfiguration = true;
1576 /* store the options first. */
1578 preferences.saveTo(configuration);
1580 /* save known Sones. */
1581 int soneCounter = 0;
1582 synchronized (knownSones) {
1583 for (String knownSoneId : knownSones) {
1584 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1586 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1589 /* save Sone following times. */
1591 synchronized (soneFollowingTimes) {
1592 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1593 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1594 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1597 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1600 /* save known posts. */
1604 configuration.save();
1606 } catch (ConfigurationException ce1) {
1607 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1608 } catch (DatabaseException de1) {
1609 logger.log(Level.SEVERE, "Could not save database!", de1);
1611 synchronized (configuration) {
1612 storingConfiguration = false;
1618 * Loads the configuration.
1620 private void loadConfiguration() {
1621 new PreferencesLoader(preferences).loadFrom(configuration);
1623 /* load known Sones. */
1624 int soneCounter = 0;
1626 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1627 if (knownSoneId == null) {
1630 synchronized (knownSones) {
1631 knownSones.add(knownSoneId);
1635 /* load Sone following times. */
1638 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1639 if (soneId == null) {
1642 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1643 synchronized (soneFollowingTimes) {
1644 soneFollowingTimes.put(soneId, time);
1651 * Notifies the core that a new {@link OwnIdentity} was added.
1653 * @param ownIdentityAddedEvent
1657 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1658 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1659 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1660 if (ownIdentity.hasContext("Sone")) {
1661 addLocalSone(ownIdentity);
1666 * Notifies the core that an {@link OwnIdentity} was removed.
1668 * @param ownIdentityRemovedEvent
1672 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1673 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1674 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1675 trustedIdentities.removeAll(ownIdentity);
1679 * Notifies the core that a new {@link Identity} was added.
1681 * @param identityAddedEvent
1685 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1686 Identity identity = identityAddedEvent.identity();
1687 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1688 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1689 addRemoteSone(identity);
1693 * Notifies the core that an {@link Identity} was updated.
1695 * @param identityUpdatedEvent
1699 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1700 Identity identity = identityUpdatedEvent.identity();
1701 final Sone sone = getRemoteSone(identity.getId());
1702 if (sone.isLocal()) {
1705 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1706 soneDownloader.addSone(sone);
1707 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1711 * Notifies the core that an {@link Identity} was removed.
1713 * @param identityRemovedEvent
1717 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1718 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1719 Identity identity = identityRemovedEvent.identity();
1720 trustedIdentities.remove(ownIdentity, identity);
1721 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1722 if (trustedIdentity.getKey().equals(ownIdentity)) {
1725 if (trustedIdentity.getValue().contains(identity)) {
1729 Optional<Sone> sone = getSone(identity.getId());
1730 if (!sone.isPresent()) {
1731 /* TODO - we don’t have the Sone anymore. should this happen? */
1734 for (PostReply postReply : sone.get().getReplies()) {
1735 eventBus.post(new PostReplyRemovedEvent(postReply));
1737 for (Post post : sone.get().getPosts()) {
1738 eventBus.post(new PostRemovedEvent(post));
1740 eventBus.post(new SoneRemovedEvent(sone.get()));
1741 database.removeSone(sone.get());
1745 * Deletes the temporary image.
1747 * @param imageInsertFinishedEvent
1751 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1752 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1753 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1754 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1755 touchConfiguration();
1759 class MarkPostKnown implements Runnable {
1761 private final Post post;
1763 public MarkPostKnown(Post post) {
1769 markPostKnown(post);
1775 class MarkReplyKnown implements Runnable {
1777 private final PostReply postReply;
1779 public MarkReplyKnown(PostReply postReply) {
1780 this.postReply = postReply;
1785 markReplyKnown(postReply);