2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.EnumSet;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
35 import java.util.Map.Entry;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
50 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
51 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
52 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
54 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
55 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
56 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
57 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
58 import net.pterodactylus.sone.core.event.PostRemovedEvent;
59 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
60 import net.pterodactylus.sone.core.event.SoneLockedEvent;
61 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
63 import net.pterodactylus.sone.data.Album;
64 import net.pterodactylus.sone.data.Client;
65 import net.pterodactylus.sone.data.Image;
66 import net.pterodactylus.sone.data.Post;
67 import net.pterodactylus.sone.data.PostReply;
68 import net.pterodactylus.sone.data.Profile;
69 import net.pterodactylus.sone.data.Profile.Field;
70 import net.pterodactylus.sone.data.Reply;
71 import net.pterodactylus.sone.data.Sone;
72 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
73 import net.pterodactylus.sone.data.Sone.SoneStatus;
74 import net.pterodactylus.sone.data.TemporaryImage;
75 import net.pterodactylus.sone.database.AlbumBuilder;
76 import net.pterodactylus.sone.database.AlbumProvider;
77 import net.pterodactylus.sone.database.Database;
78 import net.pterodactylus.sone.database.DatabaseException;
79 import net.pterodactylus.sone.database.ImageBuilder;
80 import net.pterodactylus.sone.database.PostBuilder;
81 import net.pterodactylus.sone.database.PostProvider;
82 import net.pterodactylus.sone.database.PostReplyBuilder;
83 import net.pterodactylus.sone.database.PostReplyProvider;
84 import net.pterodactylus.sone.database.SoneBuilder;
85 import net.pterodactylus.sone.database.SoneProvider;
86 import net.pterodactylus.sone.freenet.wot.Identity;
87 import net.pterodactylus.sone.freenet.wot.IdentityManager;
88 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
94 import net.pterodactylus.sone.main.SonePlugin;
95 import net.pterodactylus.util.config.Configuration;
96 import net.pterodactylus.util.config.ConfigurationException;
97 import net.pterodactylus.util.service.AbstractService;
98 import net.pterodactylus.util.thread.NamedThreadFactory;
100 import com.google.common.annotations.VisibleForTesting;
101 import com.google.common.base.Function;
102 import com.google.common.base.Optional;
103 import com.google.common.base.Predicate;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
111 import com.google.inject.Singleton;
116 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
119 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider, AlbumProvider {
122 private static final Logger logger = getLogger(Core.class.getName());
124 /** The start time. */
125 private final long startupTime = System.currentTimeMillis();
127 /** The preferences. */
128 private final Preferences preferences;
130 /** The event bus. */
131 private final EventBus eventBus;
133 /** The configuration. */
134 private final Configuration configuration;
136 /** Whether we’re currently saving the configuration. */
137 private boolean storingConfiguration = false;
139 /** The identity manager. */
140 private final IdentityManager identityManager;
142 /** Interface to freenet. */
143 private final FreenetInterface freenetInterface;
145 /** The Sone downloader. */
146 private final SoneDownloader soneDownloader;
148 /** The image inserter. */
149 private final ImageInserter imageInserter;
151 /** Sone downloader thread-pool. */
152 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154 /** The update checker. */
155 private final UpdateChecker updateChecker;
157 /** The trust updater. */
158 private final WebOfTrustUpdater webOfTrustUpdater;
160 private final Set<CompatibilityMode> compatibilityModes = EnumSet.noneOf(CompatibilityMode.class);
162 /** The times Sones were followed. */
163 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
165 /** Locked local Sones. */
166 /* synchronize on itself. */
167 private final Set<Sone> lockedSones = new HashSet<Sone>();
169 /** Sone inserters. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
173 /** Sone rescuers. */
174 /* synchronize access on this on sones. */
175 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
177 /** All known Sones. */
178 private final Set<String> knownSones = new HashSet<String>();
180 /** The post database. */
181 private final Database database;
183 /** Trusted identities, sorted by own identities. */
184 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
186 /** All temporary images. */
187 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
189 /** Ticker for threads that mark own elements as known. */
190 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
192 /** The time the configuration was last touched. */
193 private volatile long lastConfigurationUpdate;
196 * Creates a new core.
198 * @param configuration
199 * The configuration of the core
200 * @param freenetInterface
201 * The freenet interface
202 * @param identityManager
203 * The identity manager
204 * @param webOfTrustUpdater
205 * The WebOfTrust updater
212 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
214 this.configuration = configuration;
215 this.freenetInterface = freenetInterface;
216 this.identityManager = identityManager;
217 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
218 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
219 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
220 this.webOfTrustUpdater = webOfTrustUpdater;
221 this.eventBus = eventBus;
222 this.database = database;
223 preferences = new Preferences(eventBus);
227 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
229 this.configuration = configuration;
230 this.freenetInterface = freenetInterface;
231 this.identityManager = identityManager;
232 this.soneDownloader = soneDownloader;
233 this.imageInserter = imageInserter;
234 this.updateChecker = updateChecker;
235 this.webOfTrustUpdater = webOfTrustUpdater;
236 this.eventBus = eventBus;
237 this.database = database;
238 preferences = new Preferences(eventBus);
246 * Returns the time Sone was started.
248 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
250 public long getStartupTime() {
255 * Returns the options used by the core.
257 * @return The options of the core
259 public Preferences getPreferences() {
264 * Returns the identity manager used by the core.
266 * @return The identity manager
268 public IdentityManager getIdentityManager() {
269 return identityManager;
273 * Returns the update checker.
275 * @return The update checker
277 public UpdateChecker getUpdateChecker() {
278 return updateChecker;
281 public boolean isCompatibilityMode(CompatibilityMode compatibilityMode) {
282 return compatibilityModes.contains(compatibilityMode);
285 public void setCompatibilityMode(CompatibilityMode compatibilityMode) {
286 compatibilityModes.add(compatibilityMode);
289 public void clearCompatibilityMod(CompatibilityMode compatibilityMode) {
290 compatibilityModes.remove(compatibilityMode);
294 * Returns the Sone rescuer for the given local Sone.
297 * The local Sone to get the rescuer for
298 * @return The Sone rescuer for the given Sone
300 public SoneRescuer getSoneRescuer(Sone sone) {
301 checkNotNull(sone, "sone must not be null");
302 checkArgument(sone.isLocal(), "sone must be local");
303 synchronized (soneRescuers) {
304 SoneRescuer soneRescuer = soneRescuers.get(sone);
305 if (soneRescuer == null) {
306 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
307 soneRescuers.put(sone, soneRescuer);
315 * Returns whether the given Sone is currently locked.
319 * @return {@code true} if the Sone is locked, {@code false} if it is not
321 public boolean isLocked(Sone sone) {
322 synchronized (lockedSones) {
323 return lockedSones.contains(sone);
327 public SoneBuilder soneBuilder() {
328 return database.newSoneBuilder();
335 public Collection<Sone> getSones() {
336 return database.getSones();
340 public Function<String, Optional<Sone>> soneLoader() {
341 return database.soneLoader();
345 * Returns the Sone with the given ID, regardless whether it’s local or
349 * The ID of the Sone to get
350 * @return The Sone with the given ID, or {@code null} if there is no such
354 public Optional<Sone> getSone(String id) {
355 return database.getSone(id);
362 public Collection<Sone> getLocalSones() {
363 return database.getLocalSones();
367 * Returns the local Sone with the given ID, optionally creating a new Sone.
371 * @return The Sone with the given ID, or {@code null}
373 public Sone getLocalSone(String id) {
374 Optional<Sone> sone = database.getSone(id);
375 if (sone.isPresent() && sone.get().isLocal()) {
385 public Collection<Sone> getRemoteSones() {
386 return database.getRemoteSones();
390 * Returns the remote Sone with the given ID.
394 * The ID of the remote Sone to get
395 * @return The Sone with the given ID
397 public Sone getRemoteSone(String id) {
398 return database.getSone(id).orNull();
402 * Returns whether the given Sone has been modified.
405 * The Sone to check for modifications
406 * @return {@code true} if a modification has been detected in the Sone,
407 * {@code false} otherwise
409 public boolean isModifiedSone(Sone sone) {
410 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
414 * Returns the time when the given was first followed by any local Sone.
417 * The Sone to get the time for
418 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
419 * been followed, or {@link Long#MAX_VALUE}
421 public long getSoneFollowingTime(Sone sone) {
422 synchronized (soneFollowingTimes) {
423 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
428 * Returns a post builder.
430 * @return A new post builder
432 public PostBuilder postBuilder() {
433 return database.newPostBuilder();
440 public Optional<Post> getPost(final String postId) {
441 Optional<Post> post = database.getPost(postId);
442 if (post.isPresent() || !isCompatibilityMode(CompatibilityMode.oldElementIds)) {
445 return FluentIterable.from(getSones()).transformAndConcat(Sone.toAllPosts).filter(new Predicate<Post>() {
447 public boolean apply(Post input) {
448 return (input != null) && input.getInternalId().equals(postId);
457 public Collection<Post> getPosts(String soneId) {
458 return database.getPosts(soneId);
465 public Collection<Post> getDirectedPosts(final String recipientId) {
466 checkNotNull(recipientId, "recipient must not be null");
467 return database.getDirectedPosts(recipientId);
471 * Returns a post reply builder.
473 * @return A new post reply builder
475 public PostReplyBuilder postReplyBuilder() {
476 return database.newPostReplyBuilder();
483 public Optional<PostReply> getPostReply(String replyId) {
484 return database.getPostReply(replyId);
491 public List<PostReply> getReplies(final String postId) {
492 return database.getReplies(postId);
496 * Returns all Sones that have liked the given post.
499 * The post to get the liking Sones for
500 * @return The Sones that like the given post
502 public Set<Sone> getLikes(Post post) {
503 Set<Sone> sones = new HashSet<Sone>();
504 for (Sone sone : getSones()) {
505 if (sone.getLikedPostIds().contains(post.getId())) {
513 * Returns all Sones that have liked the given reply.
516 * The reply to get the liking Sones for
517 * @return The Sones that like the given reply
519 public Set<Sone> getLikes(PostReply reply) {
520 Set<Sone> sones = new HashSet<Sone>();
521 for (Sone sone : getSones()) {
522 if (sone.getLikedReplyIds().contains(reply.getId())) {
530 * Returns whether the given post is bookmarked.
534 * @return {@code true} if the given post is bookmarked, {@code false}
537 public boolean isBookmarked(Post post) {
538 return database.isPostBookmarked(post);
542 * Returns all currently known bookmarked posts.
544 * @return All bookmarked posts
546 public Set<Post> getBookmarkedPosts() {
547 return database.getBookmarkedPosts();
550 public AlbumBuilder albumBuilder() {
551 return database.newAlbumBuilder();
555 * Returns the album with the given ID, optionally creating a new album if
556 * an album with the given ID can not be found.
559 * The ID of the album
560 * @return The album with the given ID, or {@code null} if no album with the
563 public Optional<Album> getAlbum(String albumId) {
564 return database.getAlbum(albumId);
567 public ImageBuilder imageBuilder() {
568 return database.newImageBuilder();
572 * Returns the image with the given ID, creating it if necessary.
575 * The ID of the image
576 * @return The image with the given ID
578 public Image getImage(String imageId) {
579 return getImage(imageId, true);
583 * Returns the image with the given ID, optionally creating it if it does
587 * The ID of the image
589 * {@code true} to create an image if none exists with the given
591 * @return The image with the given ID, or {@code null} if none exists and
594 public Image getImage(String imageId, boolean create) {
595 Optional<Image> image = database.getImage(imageId);
596 if (image.isPresent()) {
602 Image newImage = database.newImageBuilder().withId(imageId).build();
603 database.storeImage(newImage);
608 * Returns the temporary image with the given ID.
611 * The ID of the temporary image
612 * @return The temporary image, or {@code null} if there is no temporary
613 * image with the given ID
615 public TemporaryImage getTemporaryImage(String imageId) {
616 synchronized (temporaryImages) {
617 return temporaryImages.get(imageId);
626 * Locks the given Sone. A locked Sone will not be inserted by
627 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
633 public void lockSone(Sone sone) {
634 synchronized (lockedSones) {
635 if (lockedSones.add(sone)) {
636 eventBus.post(new SoneLockedEvent(sone));
642 * Unlocks the given Sone.
644 * @see #lockSone(Sone)
648 public void unlockSone(Sone sone) {
649 synchronized (lockedSones) {
650 if (lockedSones.remove(sone)) {
651 eventBus.post(new SoneUnlockedEvent(sone));
657 * Adds a local Sone from the given own identity.
660 * The own identity to create a Sone from
661 * @return The added (or already existing) Sone
663 public Sone addLocalSone(OwnIdentity ownIdentity) {
664 if (ownIdentity == null) {
665 logger.log(Level.WARNING, "Given OwnIdentity is null!");
668 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
669 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
670 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
671 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
672 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
674 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
675 eventBus.register(soneInserter);
676 synchronized (soneInserters) {
677 soneInserters.put(sone, soneInserter);
680 database.storeSone(sone);
681 sone.setStatus(SoneStatus.idle);
682 soneInserter.start();
687 * Creates a new Sone for the given own identity.
690 * The own identity to create a Sone for
691 * @return The created Sone
693 public Sone createSone(OwnIdentity ownIdentity) {
694 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
695 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
698 Sone sone = addLocalSone(ownIdentity);
700 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
701 touchConfiguration();
706 * Adds the Sone of the given identity.
709 * The identity whose Sone to add
710 * @return The added or already existing Sone
712 public Sone addRemoteSone(Identity identity) {
713 if (identity == null) {
714 logger.log(Level.WARNING, "Given Identity is null!");
717 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
718 long latestEdition = fromNullable(tryParse(property)).or(0L);
719 Optional<Sone> existingSone = getSone(identity.getId());
720 if (existingSone.isPresent() && existingSone.get().isLocal()) {
721 return existingSone.get();
723 boolean newSone = !existingSone.isPresent();
724 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
725 sone.setLatestEdition(latestEdition);
727 synchronized (knownSones) {
728 newSone = !knownSones.contains(sone.getId());
730 sone.setKnown(!newSone);
732 eventBus.post(new NewSoneFoundEvent(sone));
733 for (Sone localSone : getLocalSones()) {
734 if (localSone.getOptions().isAutoFollow()) {
735 followSone(localSone, sone.getId());
740 database.storeSone(sone);
741 soneDownloader.addSone(sone);
742 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
747 * Lets the given local Sone follow the Sone with the given ID.
750 * The local Sone that should follow another Sone
752 * The ID of the Sone to follow
754 public void followSone(Sone sone, String soneId) {
755 checkNotNull(sone, "sone must not be null");
756 checkNotNull(soneId, "soneId must not be null");
757 database.addFriend(sone, soneId);
758 synchronized (soneFollowingTimes) {
759 if (!soneFollowingTimes.containsKey(soneId)) {
760 long now = System.currentTimeMillis();
761 soneFollowingTimes.put(soneId, now);
762 Optional<Sone> followedSone = getSone(soneId);
763 if (!followedSone.isPresent()) {
766 for (Post post : followedSone.get().getPosts()) {
767 if (post.getTime() < now) {
771 for (PostReply reply : followedSone.get().getReplies()) {
772 if (reply.getTime() < now) {
773 markReplyKnown(reply);
778 touchConfiguration();
782 * Lets the given local Sone unfollow the Sone with the given ID.
785 * The local Sone that should unfollow another Sone
787 * The ID of the Sone being unfollowed
789 public void unfollowSone(Sone sone, String soneId) {
790 checkNotNull(sone, "sone must not be null");
791 checkNotNull(soneId, "soneId must not be null");
792 database.removeFriend(sone, soneId);
793 boolean unfollowedSoneStillFollowed = false;
794 for (Sone localSone : getLocalSones()) {
795 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
797 if (!unfollowedSoneStillFollowed) {
798 synchronized (soneFollowingTimes) {
799 soneFollowingTimes.remove(soneId);
802 touchConfiguration();
806 * Sets the trust value of the given origin Sone for the target Sone.
813 * The trust value (from {@code -100} to {@code 100})
815 public void setTrust(Sone origin, Sone target, int trustValue) {
816 checkNotNull(origin, "origin must not be null");
817 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
818 checkNotNull(target, "target must not be null");
819 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
820 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
824 * Removes any trust assignment for the given target Sone.
831 public void removeTrust(Sone origin, Sone target) {
832 checkNotNull(origin, "origin must not be null");
833 checkNotNull(target, "target must not be null");
834 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
835 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
839 * Assigns the configured positive trust value for the given target.
846 public void trustSone(Sone origin, Sone target) {
847 setTrust(origin, target, preferences.getPositiveTrust());
851 * Assigns the configured negative trust value for the given target.
858 public void distrustSone(Sone origin, Sone target) {
859 setTrust(origin, target, preferences.getNegativeTrust());
863 * Removes the trust assignment for the given target.
870 public void untrustSone(Sone origin, Sone target) {
871 removeTrust(origin, target);
875 * Updates the stored Sone with the given Sone.
880 public void updateSone(Sone sone) {
881 updateSone(sone, false);
885 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
886 * {@code true}, an older Sone than the current Sone can be given to restore
891 * @param soneRescueMode
892 * {@code true} if the stored Sone should be updated regardless
893 * of the age of the given Sone
895 public void updateSone(final Sone sone, boolean soneRescueMode) {
896 Optional<Sone> storedSone = getSone(sone.getId());
897 if (storedSone.isPresent()) {
898 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
899 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
902 List<Object> events =
903 collectEventsForChangesInSone(storedSone.get(), sone);
904 database.storeSone(sone);
905 for (Object event : events) {
906 eventBus.post(event);
908 sone.setOptions(storedSone.get().getOptions());
909 sone.setKnown(storedSone.get().isKnown());
910 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
911 if (sone.isLocal()) {
912 touchConfiguration();
917 private List<Object> collectEventsForChangesInSone(Sone oldSone,
918 final Sone newSone) {
919 final List<Object> events = new ArrayList<Object>();
920 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
922 soneChangeDetector.onNewPosts(new PostProcessor() {
924 public void processPost(Post post) {
925 if (post.getTime() < getSoneFollowingTime(newSone)) {
927 } else if (!post.isKnown()) {
928 events.add(new NewPostFoundEvent(post));
932 soneChangeDetector.onRemovedPosts(new PostProcessor() {
934 public void processPost(Post post) {
935 events.add(new PostRemovedEvent(post));
938 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
940 public void processPostReply(PostReply postReply) {
941 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
942 postReply.setKnown(true);
943 } else if (!postReply.isKnown()) {
944 events.add(new NewPostReplyFoundEvent(postReply));
948 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
950 public void processPostReply(PostReply postReply) {
951 events.add(new PostReplyRemovedEvent(postReply));
954 soneChangeDetector.detectChanges(newSone);
959 * Deletes the given Sone. This will remove the Sone from the
960 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
961 * remove the context from its identity.
966 public void deleteSone(Sone sone) {
967 if (!(sone.getIdentity() instanceof OwnIdentity)) {
968 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
971 if (!getLocalSones().contains(sone)) {
972 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
975 SoneInserter soneInserter = soneInserters.remove(sone);
977 database.removeSone(sone);
978 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
979 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
981 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
982 } catch (ConfigurationException ce1) {
983 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
988 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
989 * known} before, a {@link MarkSoneKnownEvent} is fired.
992 * The Sone to mark as known
994 public void markSoneKnown(Sone sone) {
995 if (!sone.isKnown()) {
997 synchronized (knownSones) {
998 knownSones.add(sone.getId());
1000 eventBus.post(new MarkSoneKnownEvent(sone));
1001 touchConfiguration();
1006 * Loads and updates the given Sone from the configuration. If any error is
1007 * encountered, loading is aborted and the given Sone is not changed.
1010 * The Sone to load and update
1012 public void loadSone(Sone sone) {
1013 if (!sone.isLocal()) {
1014 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1017 logger.info(String.format("Loading local Sone: %s", sone));
1020 String sonePrefix = "Sone/" + sone.getId();
1021 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1022 if (soneTime == null) {
1023 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1026 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1029 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1030 Profile profile = configurationSoneParser.parseProfile();
1033 Collection<Post> posts;
1035 posts = configurationSoneParser.parsePosts(database);
1036 } catch (InvalidPostFound ipf) {
1037 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1042 Collection<PostReply> replies;
1044 replies = configurationSoneParser.parsePostReplies(database);
1045 } catch (InvalidPostReplyFound iprf) {
1046 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1050 /* load post likes. */
1051 Set<String> likedPostIds =
1052 configurationSoneParser.parseLikedPostIds();
1054 /* load reply likes. */
1055 Set<String> likedReplyIds =
1056 configurationSoneParser.parseLikedPostReplyIds();
1059 List<Album> topLevelAlbums;
1062 configurationSoneParser.parseTopLevelAlbums(database);
1063 } catch (InvalidAlbumFound iaf) {
1064 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1066 } catch (InvalidParentAlbumFound ipaf) {
1067 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1068 ipaf.getAlbumParentId()));
1074 configurationSoneParser.parseImages(database);
1075 } catch (InvalidImageFound iif) {
1076 logger.log(WARNING, "Invalid image found, aborting load!");
1078 } catch (InvalidParentAlbumFound ipaf) {
1079 logger.log(Level.WARNING,
1080 format("Invalid album image (%s) encountered, aborting load!",
1081 ipaf.getAlbumParentId()));
1086 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1087 if (avatarId != null) {
1088 final Map<String, Image> images =
1089 configurationSoneParser.getImages();
1090 profile.setAvatar(images.get(avatarId));
1094 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1095 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1096 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1097 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1098 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1099 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1101 /* if we’re still here, Sone was loaded successfully. */
1102 synchronized (sone) {
1103 sone.setTime(soneTime);
1104 sone.setProfile(profile);
1105 sone.setPosts(posts);
1106 sone.setReplies(replies);
1107 sone.setLikePostIds(likedPostIds);
1108 sone.setLikeReplyIds(likedReplyIds);
1109 for (Album album : sone.getRootAlbum().getAlbums()) {
1110 sone.getRootAlbum().removeAlbum(album);
1112 for (Album album : topLevelAlbums) {
1113 sone.getRootAlbum().addAlbum(album);
1115 synchronized (soneInserters) {
1116 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1119 for (Post post : posts) {
1120 post.setKnown(true);
1122 for (PostReply reply : replies) {
1123 reply.setKnown(true);
1126 logger.info(String.format("Sone loaded successfully: %s", sone));
1130 * Creates a new post.
1133 * The Sone that creates the post
1135 * The recipient Sone, or {@code null} if this post does not have
1138 * The text of the post
1139 * @return The created post
1141 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1142 checkNotNull(text, "text must not be null");
1143 checkArgument(text.trim().length() > 0, "text must not be empty");
1144 if (!sone.isLocal()) {
1145 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1148 PostBuilder postBuilder = database.newPostBuilder();
1149 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1150 if (recipient.isPresent()) {
1151 postBuilder.to(recipient.get().getId());
1153 final Post post = postBuilder.build();
1154 database.storePost(post);
1155 eventBus.post(new NewPostFoundEvent(post));
1157 touchConfiguration();
1158 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1163 * Deletes the given post.
1166 * The post to delete
1168 public void deletePost(Post post) {
1169 if (!post.getSone().isLocal()) {
1170 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1173 database.removePost(post);
1174 eventBus.post(new PostRemovedEvent(post));
1175 markPostKnown(post);
1176 touchConfiguration();
1180 * Marks the given post as known, if it is currently not a known post
1181 * (according to {@link Post#isKnown()}).
1184 * The post to mark as known
1186 public void markPostKnown(Post post) {
1187 post.setKnown(true);
1188 eventBus.post(new MarkPostKnownEvent(post));
1189 touchConfiguration();
1190 for (PostReply reply : getReplies(post.getId())) {
1191 markReplyKnown(reply);
1195 public void bookmarkPost(Post post) {
1196 database.bookmarkPost(post);
1200 * Removes the given post from the bookmarks.
1203 * The post to unbookmark
1205 public void unbookmarkPost(Post post) {
1206 database.unbookmarkPost(post);
1210 * Creates a new reply.
1213 * The Sone that creates the reply
1215 * The post that this reply refers to
1217 * The text of the reply
1218 * @return The created reply
1220 public PostReply createReply(Sone sone, Post post, String text) {
1221 checkNotNull(text, "text must not be null");
1222 checkArgument(text.trim().length() > 0, "text must not be empty");
1223 if (!sone.isLocal()) {
1224 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1227 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1228 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1229 final PostReply reply = postReplyBuilder.build();
1230 database.storePostReply(reply);
1231 eventBus.post(new NewPostReplyFoundEvent(reply));
1232 sone.addReply(reply);
1233 touchConfiguration();
1234 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1239 * Deletes the given reply.
1242 * The reply to delete
1244 public void deleteReply(PostReply reply) {
1245 Sone sone = reply.getSone();
1246 if (!sone.isLocal()) {
1247 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1250 database.removePostReply(reply);
1251 markReplyKnown(reply);
1252 sone.removeReply(reply);
1253 touchConfiguration();
1257 * Marks the given reply as known, if it is currently not a known reply
1258 * (according to {@link Reply#isKnown()}).
1261 * The reply to mark as known
1263 public void markReplyKnown(PostReply reply) {
1264 boolean previouslyKnown = reply.isKnown();
1265 reply.setKnown(true);
1266 eventBus.post(new MarkPostReplyKnownEvent(reply));
1267 if (!previouslyKnown) {
1268 touchConfiguration();
1273 * Creates a new album for the given Sone.
1276 * The Sone to create the album for
1278 * The parent of the album (may be {@code null} to create a
1280 * @return The new album
1282 public Album createAlbum(Sone sone, Album parent) {
1283 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1284 database.storeAlbum(album);
1285 parent.addAlbum(album);
1290 * Deletes the given album. The owner of the album has to be a local Sone,
1291 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1294 * The album to remove
1296 public void deleteAlbum(Album album) {
1297 checkNotNull(album, "album must not be null");
1298 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1299 if (!album.isEmpty()) {
1302 album.getParent().removeAlbum(album);
1303 database.removeAlbum(album);
1304 touchConfiguration();
1308 * Creates a new image.
1311 * The Sone creating the image
1313 * The album the image will be inserted into
1314 * @param temporaryImage
1315 * The temporary image to create the image from
1316 * @return The newly created image
1318 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1319 checkNotNull(sone, "sone must not be null");
1320 checkNotNull(album, "album must not be null");
1321 checkNotNull(temporaryImage, "temporaryImage must not be null");
1322 checkArgument(sone.isLocal(), "sone must be a local Sone");
1323 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1324 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1325 album.addImage(image);
1326 database.storeImage(image);
1327 imageInserter.insertImage(temporaryImage, image);
1332 * Deletes the given image. This method will also delete a matching
1335 * @see #deleteTemporaryImage(String)
1337 * The image to delete
1339 public void deleteImage(Image image) {
1340 checkNotNull(image, "image must not be null");
1341 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1342 deleteTemporaryImage(image.getId());
1343 image.getAlbum().removeImage(image);
1344 database.removeImage(image);
1345 touchConfiguration();
1349 * Creates a new temporary image.
1352 * The MIME type of the temporary image
1354 * The encoded data of the image
1355 * @return The temporary image
1357 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1358 TemporaryImage temporaryImage = new TemporaryImage();
1359 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1360 synchronized (temporaryImages) {
1361 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1363 return temporaryImage;
1367 * Deletes the temporary image with the given ID.
1370 * The ID of the temporary image to delete
1372 public void deleteTemporaryImage(String imageId) {
1373 checkNotNull(imageId, "imageId must not be null");
1374 synchronized (temporaryImages) {
1375 temporaryImages.remove(imageId);
1377 Image image = getImage(imageId, false);
1378 if (image != null) {
1379 imageInserter.cancelImageInsert(image);
1384 * Notifies the core that the configuration, either of the core or of a
1385 * single local Sone, has changed, and that the configuration should be
1388 public void touchConfiguration() {
1389 lastConfigurationUpdate = System.currentTimeMillis();
1400 public void serviceStart() {
1401 loadConfiguration();
1402 updateChecker.start();
1403 identityManager.start();
1404 webOfTrustUpdater.init();
1405 webOfTrustUpdater.start();
1413 public void serviceRun() {
1414 long lastSaved = System.currentTimeMillis();
1415 while (!shouldStop()) {
1417 long now = System.currentTimeMillis();
1418 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1419 for (Sone localSone : getLocalSones()) {
1420 saveSone(localSone);
1422 saveConfiguration();
1432 public void serviceStop() {
1433 localElementTicker.shutdownNow();
1434 synchronized (soneInserters) {
1435 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1436 soneInserter.getValue().stop();
1437 saveSone(soneInserter.getKey());
1440 synchronized (soneRescuers) {
1441 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1445 saveConfiguration();
1447 webOfTrustUpdater.stop();
1448 updateChecker.stop();
1449 soneDownloader.stop();
1450 soneDownloaders.shutdown();
1451 identityManager.stop();
1459 * Saves the given Sone. This will persist all local settings for the given
1460 * Sone, such as the friends list and similar, private options.
1465 private synchronized void saveSone(Sone sone) {
1466 if (!sone.isLocal()) {
1467 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1470 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1471 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1475 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1477 /* save Sone into configuration. */
1478 String sonePrefix = "Sone/" + sone.getId();
1479 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1480 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1483 Profile profile = sone.getProfile();
1484 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1485 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1486 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1487 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1488 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1489 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1490 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1492 /* save profile fields. */
1493 int fieldCounter = 0;
1494 for (Field profileField : profile.getFields()) {
1495 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1496 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1497 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1499 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1502 int postCounter = 0;
1503 for (Post post : sone.getPosts()) {
1504 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1505 configuration.getStringValue(postPrefix + "/ID").setValue(post.getInternalId());
1506 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1507 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1508 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1510 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1513 int replyCounter = 0;
1514 for (PostReply reply : sone.getReplies()) {
1515 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1516 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getInternalId());
1517 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1518 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1519 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1521 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1523 /* save post likes. */
1524 int postLikeCounter = 0;
1525 for (String postId : sone.getLikedPostIds()) {
1526 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1528 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1530 /* save reply likes. */
1531 int replyLikeCounter = 0;
1532 for (String replyId : sone.getLikedReplyIds()) {
1533 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1535 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1537 /* save albums. first, collect in a flat structure, top-level first. */
1538 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1540 int albumCounter = 0;
1541 for (Album album : albums) {
1542 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1543 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getInternalId());
1544 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1545 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1546 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1547 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1549 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1552 int imageCounter = 0;
1553 for (Album album : albums) {
1554 for (Image image : album.getImages()) {
1555 if (!image.isInserted()) {
1558 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1559 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getInternalId());
1560 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getInternalId());
1561 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1562 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1563 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1564 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1565 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1566 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1569 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1572 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1573 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1574 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1575 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1576 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1577 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1579 configuration.save();
1581 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1583 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1584 } catch (ConfigurationException ce1) {
1585 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1590 * Saves the current options.
1592 private void saveConfiguration() {
1593 synchronized (configuration) {
1594 if (storingConfiguration) {
1595 logger.log(Level.FINE, "Already storing configuration…");
1598 storingConfiguration = true;
1601 /* store the options first. */
1603 preferences.saveTo(configuration);
1605 /* save known Sones. */
1606 int soneCounter = 0;
1607 synchronized (knownSones) {
1608 for (String knownSoneId : knownSones) {
1609 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1611 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1614 /* save Sone following times. */
1616 synchronized (soneFollowingTimes) {
1617 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1618 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1619 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1622 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1625 /* save compatibility modes. */
1626 configuration.getBooleanValue("CompatibilityModes/OldElementIds").setValue(compatibilityModes.contains(CompatibilityMode.oldElementIds));
1628 /* save known posts. */
1632 configuration.save();
1634 } catch (ConfigurationException ce1) {
1635 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1636 } catch (DatabaseException de1) {
1637 logger.log(Level.SEVERE, "Could not save database!", de1);
1639 synchronized (configuration) {
1640 storingConfiguration = false;
1646 * Loads the configuration.
1648 private void loadConfiguration() {
1649 new PreferencesLoader(preferences).loadFrom(configuration);
1651 /* load known Sones. */
1652 int soneCounter = 0;
1654 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1655 if (knownSoneId == null) {
1658 synchronized (knownSones) {
1659 knownSones.add(knownSoneId);
1663 /* load Sone following times. */
1666 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1667 if (soneId == null) {
1670 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1671 synchronized (soneFollowingTimes) {
1672 soneFollowingTimes.put(soneId, time);
1677 /* load compatibility modes. */
1678 if (configuration.getBooleanValue("CompatibilityModes/OldElementIds").getValue(false)) {
1679 setCompatibilityMode(CompatibilityMode.oldElementIds);
1684 * Notifies the core that a new {@link OwnIdentity} was added.
1686 * @param ownIdentityAddedEvent
1690 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1691 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1692 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1693 if (ownIdentity.hasContext("Sone")) {
1694 addLocalSone(ownIdentity);
1699 * Notifies the core that an {@link OwnIdentity} was removed.
1701 * @param ownIdentityRemovedEvent
1705 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1706 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1707 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1708 trustedIdentities.removeAll(ownIdentity);
1712 * Notifies the core that a new {@link Identity} was added.
1714 * @param identityAddedEvent
1718 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1719 Identity identity = identityAddedEvent.identity();
1720 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1721 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1722 addRemoteSone(identity);
1726 * Notifies the core that an {@link Identity} was updated.
1728 * @param identityUpdatedEvent
1732 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1733 Identity identity = identityUpdatedEvent.identity();
1734 final Sone sone = getRemoteSone(identity.getId());
1735 if (sone.isLocal()) {
1738 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1739 soneDownloader.addSone(sone);
1740 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1744 * Notifies the core that an {@link Identity} was removed.
1746 * @param identityRemovedEvent
1750 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1751 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1752 Identity identity = identityRemovedEvent.identity();
1753 trustedIdentities.remove(ownIdentity, identity);
1754 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1755 if (trustedIdentity.getKey().equals(ownIdentity)) {
1758 if (trustedIdentity.getValue().contains(identity)) {
1762 Optional<Sone> sone = getSone(identity.getId());
1763 if (!sone.isPresent()) {
1764 /* TODO - we don’t have the Sone anymore. should this happen? */
1767 database.removeSone(sone.get());
1768 eventBus.post(new SoneRemovedEvent(sone.get()));
1772 * Deletes the temporary image.
1774 * @param imageInsertFinishedEvent
1778 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1779 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1780 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1781 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1782 touchConfiguration();
1786 class MarkPostKnown implements Runnable {
1788 private final Post post;
1790 public MarkPostKnown(Post post) {
1796 markPostKnown(post);
1802 class MarkReplyKnown implements Runnable {
1804 private final PostReply postReply;
1806 public MarkReplyKnown(PostReply postReply) {
1807 this.postReply = postReply;
1812 markReplyKnown(postReply);