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.ShowCustomAvatars;
72 import net.pterodactylus.sone.data.Sone.SoneStatus;
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.VERSION.toString()));
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(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1075 /* if we’re still here, Sone was loaded successfully. */
1076 synchronized (sone) {
1077 sone.setTime(soneTime);
1078 sone.setProfile(profile);
1079 sone.setPosts(posts);
1080 sone.setReplies(replies);
1081 sone.setLikePostIds(likedPostIds);
1082 sone.setLikeReplyIds(likedReplyIds);
1083 for (Album album : sone.getRootAlbum().getAlbums()) {
1084 sone.getRootAlbum().removeAlbum(album);
1086 for (Album album : topLevelAlbums) {
1087 sone.getRootAlbum().addAlbum(album);
1089 synchronized (soneInserters) {
1090 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1093 for (Post post : posts) {
1094 post.setKnown(true);
1096 for (PostReply reply : replies) {
1097 reply.setKnown(true);
1100 logger.info(String.format("Sone loaded successfully: %s", sone));
1104 * Creates a new post.
1107 * The Sone that creates the post
1109 * The recipient Sone, or {@code null} if this post does not have
1112 * The text of the post
1113 * @return The created post
1115 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1116 checkNotNull(text, "text must not be null");
1117 checkArgument(text.trim().length() > 0, "text must not be empty");
1118 if (!sone.isLocal()) {
1119 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1122 PostBuilder postBuilder = database.newPostBuilder();
1123 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1124 if (recipient.isPresent()) {
1125 postBuilder.to(recipient.get().getId());
1127 final Post post = postBuilder.build();
1128 database.storePost(post);
1129 eventBus.post(new NewPostFoundEvent(post));
1131 touchConfiguration();
1132 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1137 * Deletes the given post.
1140 * The post to delete
1142 public void deletePost(Post post) {
1143 if (!post.getSone().isLocal()) {
1144 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1147 database.removePost(post);
1148 eventBus.post(new PostRemovedEvent(post));
1149 markPostKnown(post);
1150 touchConfiguration();
1154 * Marks the given post as known, if it is currently not a known post
1155 * (according to {@link Post#isKnown()}).
1158 * The post to mark as known
1160 public void markPostKnown(Post post) {
1161 post.setKnown(true);
1162 eventBus.post(new MarkPostKnownEvent(post));
1163 touchConfiguration();
1164 for (PostReply reply : getReplies(post.getId())) {
1165 markReplyKnown(reply);
1169 public void bookmarkPost(Post post) {
1170 database.bookmarkPost(post);
1174 * Removes the given post from the bookmarks.
1177 * The post to unbookmark
1179 public void unbookmarkPost(Post post) {
1180 database.unbookmarkPost(post);
1184 * Creates a new reply.
1187 * The Sone that creates the reply
1189 * The post that this reply refers to
1191 * The text of the reply
1192 * @return The created reply
1194 public PostReply createReply(Sone sone, Post post, String text) {
1195 checkNotNull(text, "text must not be null");
1196 checkArgument(text.trim().length() > 0, "text must not be empty");
1197 if (!sone.isLocal()) {
1198 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1201 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1202 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1203 final PostReply reply = postReplyBuilder.build();
1204 database.storePostReply(reply);
1205 eventBus.post(new NewPostReplyFoundEvent(reply));
1206 sone.addReply(reply);
1207 touchConfiguration();
1208 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1213 * Deletes the given reply.
1216 * The reply to delete
1218 public void deleteReply(PostReply reply) {
1219 Sone sone = reply.getSone();
1220 if (!sone.isLocal()) {
1221 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1224 database.removePostReply(reply);
1225 markReplyKnown(reply);
1226 sone.removeReply(reply);
1227 touchConfiguration();
1231 * Marks the given reply as known, if it is currently not a known reply
1232 * (according to {@link Reply#isKnown()}).
1235 * The reply to mark as known
1237 public void markReplyKnown(PostReply reply) {
1238 boolean previouslyKnown = reply.isKnown();
1239 reply.setKnown(true);
1240 eventBus.post(new MarkPostReplyKnownEvent(reply));
1241 if (!previouslyKnown) {
1242 touchConfiguration();
1247 * Creates a new album for the given Sone.
1250 * The Sone to create the album for
1252 * The parent of the album (may be {@code null} to create a
1254 * @return The new album
1256 public Album createAlbum(Sone sone, Album parent) {
1257 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1258 database.storeAlbum(album);
1259 parent.addAlbum(album);
1264 * Deletes the given album. The owner of the album has to be a local Sone,
1265 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1268 * The album to remove
1270 public void deleteAlbum(Album album) {
1271 checkNotNull(album, "album must not be null");
1272 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1273 if (!album.isEmpty()) {
1276 album.getParent().removeAlbum(album);
1277 database.removeAlbum(album);
1278 touchConfiguration();
1282 * Creates a new image.
1285 * The Sone creating the image
1287 * The album the image will be inserted into
1288 * @param temporaryImage
1289 * The temporary image to create the image from
1290 * @return The newly created image
1292 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1293 checkNotNull(sone, "sone must not be null");
1294 checkNotNull(album, "album must not be null");
1295 checkNotNull(temporaryImage, "temporaryImage must not be null");
1296 checkArgument(sone.isLocal(), "sone must be a local Sone");
1297 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1298 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1299 album.addImage(image);
1300 database.storeImage(image);
1301 imageInserter.insertImage(temporaryImage, image);
1306 * Deletes the given image. This method will also delete a matching
1309 * @see #deleteTemporaryImage(String)
1311 * The image to delete
1313 public void deleteImage(Image image) {
1314 checkNotNull(image, "image must not be null");
1315 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1316 deleteTemporaryImage(image.getId());
1317 image.getAlbum().removeImage(image);
1318 database.removeImage(image);
1319 touchConfiguration();
1323 * Creates a new temporary image.
1326 * The MIME type of the temporary image
1328 * The encoded data of the image
1329 * @return The temporary image
1331 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1332 TemporaryImage temporaryImage = new TemporaryImage();
1333 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1334 synchronized (temporaryImages) {
1335 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1337 return temporaryImage;
1341 * Deletes the temporary image with the given ID.
1344 * The ID of the temporary image to delete
1346 public void deleteTemporaryImage(String imageId) {
1347 checkNotNull(imageId, "imageId must not be null");
1348 synchronized (temporaryImages) {
1349 temporaryImages.remove(imageId);
1351 Image image = getImage(imageId, false);
1352 if (image != null) {
1353 imageInserter.cancelImageInsert(image);
1358 * Notifies the core that the configuration, either of the core or of a
1359 * single local Sone, has changed, and that the configuration should be
1362 public void touchConfiguration() {
1363 lastConfigurationUpdate = System.currentTimeMillis();
1374 public void serviceStart() {
1375 loadConfiguration();
1376 updateChecker.start();
1377 identityManager.start();
1378 webOfTrustUpdater.init();
1379 webOfTrustUpdater.start();
1387 public void serviceRun() {
1388 long lastSaved = System.currentTimeMillis();
1389 while (!shouldStop()) {
1391 long now = System.currentTimeMillis();
1392 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1393 for (Sone localSone : getLocalSones()) {
1394 saveSone(localSone);
1396 saveConfiguration();
1406 public void serviceStop() {
1407 localElementTicker.shutdownNow();
1408 synchronized (soneInserters) {
1409 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1410 soneInserter.getValue().stop();
1411 saveSone(soneInserter.getKey());
1414 synchronized (soneRescuers) {
1415 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1419 saveConfiguration();
1421 webOfTrustUpdater.stop();
1422 updateChecker.stop();
1423 soneDownloader.stop();
1424 soneDownloaders.shutdown();
1425 identityManager.stop();
1433 * Saves the given Sone. This will persist all local settings for the given
1434 * Sone, such as the friends list and similar, private options.
1439 private synchronized void saveSone(Sone sone) {
1440 if (!sone.isLocal()) {
1441 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1444 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1445 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1449 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1451 /* save Sone into configuration. */
1452 String sonePrefix = "Sone/" + sone.getId();
1453 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1454 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1457 Profile profile = sone.getProfile();
1458 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1459 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1460 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1461 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1462 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1463 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1464 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1466 /* save profile fields. */
1467 int fieldCounter = 0;
1468 for (Field profileField : profile.getFields()) {
1469 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1470 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1471 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1473 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1476 int postCounter = 0;
1477 for (Post post : sone.getPosts()) {
1478 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1479 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1480 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1481 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1482 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1484 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1487 int replyCounter = 0;
1488 for (PostReply reply : sone.getReplies()) {
1489 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1490 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1491 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1492 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1493 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1495 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1497 /* save post likes. */
1498 int postLikeCounter = 0;
1499 for (String postId : sone.getLikedPostIds()) {
1500 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1502 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1504 /* save reply likes. */
1505 int replyLikeCounter = 0;
1506 for (String replyId : sone.getLikedReplyIds()) {
1507 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1509 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1511 /* save albums. first, collect in a flat structure, top-level first. */
1512 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1514 int albumCounter = 0;
1515 for (Album album : albums) {
1516 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1517 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1518 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1519 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1520 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1522 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1525 int imageCounter = 0;
1526 for (Album album : albums) {
1527 for (Image image : album.getImages()) {
1528 if (!image.isInserted()) {
1531 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1532 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1533 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1534 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1535 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1536 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1537 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1538 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1539 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1542 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1545 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1546 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1547 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1548 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1549 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1550 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1552 configuration.save();
1554 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1556 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1557 } catch (ConfigurationException ce1) {
1558 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1563 * Saves the current options.
1565 private void saveConfiguration() {
1566 synchronized (configuration) {
1567 if (storingConfiguration) {
1568 logger.log(Level.FINE, "Already storing configuration…");
1571 storingConfiguration = true;
1574 /* store the options first. */
1576 preferences.saveTo(configuration);
1578 /* save known Sones. */
1579 int soneCounter = 0;
1580 synchronized (knownSones) {
1581 for (String knownSoneId : knownSones) {
1582 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1584 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1587 /* save Sone following times. */
1589 synchronized (soneFollowingTimes) {
1590 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1591 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1592 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1595 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1598 /* save known posts. */
1602 configuration.save();
1604 } catch (ConfigurationException ce1) {
1605 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1606 } catch (DatabaseException de1) {
1607 logger.log(Level.SEVERE, "Could not save database!", de1);
1609 synchronized (configuration) {
1610 storingConfiguration = false;
1616 * Loads the configuration.
1618 private void loadConfiguration() {
1619 new PreferencesLoader(preferences).loadFrom(configuration);
1621 /* load known Sones. */
1622 int soneCounter = 0;
1624 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1625 if (knownSoneId == null) {
1628 synchronized (knownSones) {
1629 knownSones.add(knownSoneId);
1633 /* load Sone following times. */
1636 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1637 if (soneId == null) {
1640 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1641 synchronized (soneFollowingTimes) {
1642 soneFollowingTimes.put(soneId, time);
1649 * Notifies the core that a new {@link OwnIdentity} was added.
1651 * @param ownIdentityAddedEvent
1655 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1656 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1657 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1658 if (ownIdentity.hasContext("Sone")) {
1659 addLocalSone(ownIdentity);
1664 * Notifies the core that an {@link OwnIdentity} was removed.
1666 * @param ownIdentityRemovedEvent
1670 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1671 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1672 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1673 trustedIdentities.removeAll(ownIdentity);
1677 * Notifies the core that a new {@link Identity} was added.
1679 * @param identityAddedEvent
1683 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1684 Identity identity = identityAddedEvent.identity();
1685 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1686 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1687 addRemoteSone(identity);
1691 * Notifies the core that an {@link Identity} was updated.
1693 * @param identityUpdatedEvent
1697 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1698 Identity identity = identityUpdatedEvent.identity();
1699 final Sone sone = getRemoteSone(identity.getId());
1700 if (sone.isLocal()) {
1703 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1704 soneDownloader.addSone(sone);
1705 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1709 * Notifies the core that an {@link Identity} was removed.
1711 * @param identityRemovedEvent
1715 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1716 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1717 Identity identity = identityRemovedEvent.identity();
1718 trustedIdentities.remove(ownIdentity, identity);
1719 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1720 if (trustedIdentity.getKey().equals(ownIdentity)) {
1723 if (trustedIdentity.getValue().contains(identity)) {
1727 Optional<Sone> sone = getSone(identity.getId());
1728 if (!sone.isPresent()) {
1729 /* TODO - we don’t have the Sone anymore. should this happen? */
1732 database.removeSone(sone.get());
1733 eventBus.post(new SoneRemovedEvent(sone.get()));
1737 * Deletes the temporary image.
1739 * @param imageInsertFinishedEvent
1743 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1744 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1745 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1746 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1747 touchConfiguration();
1751 class MarkPostKnown implements Runnable {
1753 private final Post post;
1755 public MarkPostKnown(Post post) {
1761 markPostKnown(post);
1767 class MarkReplyKnown implements Runnable {
1769 private final PostReply postReply;
1771 public MarkReplyKnown(PostReply postReply) {
1772 this.postReply = postReply;
1777 markReplyKnown(postReply);