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;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
46 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
47 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
48 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
49 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
52 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
53 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
54 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
55 import net.pterodactylus.sone.core.event.PostRemovedEvent;
56 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneLockedEvent;
58 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
60 import net.pterodactylus.sone.data.Album;
61 import net.pterodactylus.sone.data.Client;
62 import net.pterodactylus.sone.data.Image;
63 import net.pterodactylus.sone.data.Post;
64 import net.pterodactylus.sone.data.PostReply;
65 import net.pterodactylus.sone.data.Profile;
66 import net.pterodactylus.sone.data.Profile.Field;
67 import net.pterodactylus.sone.data.Reply;
68 import net.pterodactylus.sone.data.Sone;
69 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
70 import net.pterodactylus.sone.data.Sone.SoneStatus;
71 import net.pterodactylus.sone.data.TemporaryImage;
72 import net.pterodactylus.sone.database.AlbumBuilder;
73 import net.pterodactylus.sone.database.Database;
74 import net.pterodactylus.sone.database.DatabaseException;
75 import net.pterodactylus.sone.database.ImageBuilder;
76 import net.pterodactylus.sone.database.PostBuilder;
77 import net.pterodactylus.sone.database.PostProvider;
78 import net.pterodactylus.sone.database.PostReplyBuilder;
79 import net.pterodactylus.sone.database.PostReplyProvider;
80 import net.pterodactylus.sone.database.SoneBuilder;
81 import net.pterodactylus.sone.database.SoneProvider;
82 import net.pterodactylus.sone.fcp.FcpInterface;
83 import net.pterodactylus.sone.freenet.wot.Identity;
84 import net.pterodactylus.sone.freenet.wot.IdentityManager;
85 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
91 import net.pterodactylus.sone.main.SonePlugin;
92 import net.pterodactylus.util.config.Configuration;
93 import net.pterodactylus.util.config.ConfigurationException;
94 import net.pterodactylus.util.logging.Logging;
95 import net.pterodactylus.util.number.Numbers;
96 import net.pterodactylus.util.service.AbstractService;
97 import net.pterodactylus.util.thread.NamedThreadFactory;
99 import com.google.common.annotations.VisibleForTesting;
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 = Logging.getLogger(Core.class);
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 FCP interface. */
158 private volatile FcpInterface fcpInterface;
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /** All known Sones. */
176 private final Set<String> knownSones = new HashSet<String>();
178 /** The post database. */
179 private final Database database;
181 /** All bookmarked posts. */
182 /* synchronize access on itself. */
183 private final Set<String> bookmarkedPosts = new HashSet<String>();
185 /** Trusted identities, sorted by own identities. */
186 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
188 /** All temporary images. */
189 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
191 /** Ticker for threads that mark own elements as known. */
192 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
194 /** The time the configuration was last touched. */
195 private volatile long lastConfigurationUpdate;
198 * Creates a new core.
200 * @param configuration
201 * The configuration of the core
202 * @param freenetInterface
203 * The freenet interface
204 * @param identityManager
205 * The identity manager
206 * @param webOfTrustUpdater
207 * The WebOfTrust updater
214 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
216 this.configuration = configuration;
217 this.freenetInterface = freenetInterface;
218 this.identityManager = identityManager;
219 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
220 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
221 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
222 this.webOfTrustUpdater = webOfTrustUpdater;
223 this.eventBus = eventBus;
224 this.database = database;
225 preferences = new Preferences(eventBus);
229 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
231 this.configuration = configuration;
232 this.freenetInterface = freenetInterface;
233 this.identityManager = identityManager;
234 this.soneDownloader = soneDownloader;
235 this.imageInserter = imageInserter;
236 this.updateChecker = updateChecker;
237 this.webOfTrustUpdater = webOfTrustUpdater;
238 this.eventBus = eventBus;
239 this.database = database;
240 preferences = new Preferences(eventBus);
248 * Returns the time Sone was started.
250 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
252 public long getStartupTime() {
257 * Returns the options used by the core.
259 * @return The options of the core
261 public Preferences getPreferences() {
266 * Returns the identity manager used by the core.
268 * @return The identity manager
270 public IdentityManager getIdentityManager() {
271 return identityManager;
275 * Returns the update checker.
277 * @return The update checker
279 public UpdateChecker getUpdateChecker() {
280 return updateChecker;
284 * Sets the FCP interface to use.
286 * @param fcpInterface
287 * The FCP interface to use
289 public void setFcpInterface(FcpInterface fcpInterface) {
290 this.fcpInterface = fcpInterface;
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 * Returns the Sone with the given ID, regardless whether it’s local or
344 * The ID of the Sone to get
345 * @return The Sone with the given ID, or {@code null} if there is no such
349 public Optional<Sone> getSone(String id) {
350 return database.getSone(id);
357 public Collection<Sone> getLocalSones() {
358 return database.getLocalSones();
362 * Returns the local Sone with the given ID, optionally creating a new Sone.
366 * @return The Sone with the given ID, or {@code null}
368 public Sone getLocalSone(String id) {
369 Optional<Sone> sone = database.getSone(id);
370 if (sone.isPresent() && sone.get().isLocal()) {
380 public Collection<Sone> getRemoteSones() {
381 return database.getRemoteSones();
385 * Returns the remote Sone with the given ID.
389 * The ID of the remote Sone to get
390 * @return The Sone with the given ID
392 public Sone getRemoteSone(String id) {
393 return database.getSone(id).orNull();
397 * Returns whether the given Sone has been modified.
400 * The Sone to check for modifications
401 * @return {@code true} if a modification has been detected in the Sone,
402 * {@code false} otherwise
404 public boolean isModifiedSone(Sone sone) {
405 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
409 * Returns the time when the given was first followed by any local Sone.
412 * The Sone to get the time for
413 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
414 * been followed, or {@link Long#MAX_VALUE}
416 public long getSoneFollowingTime(Sone sone) {
417 synchronized (soneFollowingTimes) {
418 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
423 * Returns a post builder.
425 * @return A new post builder
427 public PostBuilder postBuilder() {
428 return database.newPostBuilder();
435 public Optional<Post> getPost(String postId) {
436 return database.getPost(postId);
443 public Collection<Post> getPosts(String soneId) {
444 return database.getPosts(soneId);
451 public Collection<Post> getDirectedPosts(final String recipientId) {
452 checkNotNull(recipientId, "recipient must not be null");
453 return database.getDirectedPosts(recipientId);
457 * Returns a post reply builder.
459 * @return A new post reply builder
461 public PostReplyBuilder postReplyBuilder() {
462 return database.newPostReplyBuilder();
469 public Optional<PostReply> getPostReply(String replyId) {
470 return database.getPostReply(replyId);
477 public List<PostReply> getReplies(final String postId) {
478 return database.getReplies(postId);
482 * Returns all Sones that have liked the given post.
485 * The post to get the liking Sones for
486 * @return The Sones that like the given post
488 public Set<Sone> getLikes(Post post) {
489 Set<Sone> sones = new HashSet<Sone>();
490 for (Sone sone : getSones()) {
491 if (sone.getLikedPostIds().contains(post.getId())) {
499 * Returns all Sones that have liked the given reply.
502 * The reply to get the liking Sones for
503 * @return The Sones that like the given reply
505 public Set<Sone> getLikes(PostReply reply) {
506 Set<Sone> sones = new HashSet<Sone>();
507 for (Sone sone : getSones()) {
508 if (sone.getLikedReplyIds().contains(reply.getId())) {
516 * Returns whether the given post is bookmarked.
520 * @return {@code true} if the given post is bookmarked, {@code false}
523 public boolean isBookmarked(Post post) {
524 return isPostBookmarked(post.getId());
528 * Returns whether the post with the given ID is bookmarked.
531 * The ID of the post to check
532 * @return {@code true} if the post with the given ID is bookmarked,
533 * {@code false} otherwise
535 public boolean isPostBookmarked(String id) {
536 synchronized (bookmarkedPosts) {
537 return bookmarkedPosts.contains(id);
542 * Returns all currently known bookmarked posts.
544 * @return All bookmarked posts
546 public Set<Post> getBookmarkedPosts() {
547 Set<Post> posts = new HashSet<Post>();
548 synchronized (bookmarkedPosts) {
549 for (String bookmarkedPostId : bookmarkedPosts) {
550 Optional<Post> post = getPost(bookmarkedPostId);
551 if (post.isPresent()) {
552 posts.add(post.get());
559 public AlbumBuilder albumBuilder() {
560 return database.newAlbumBuilder();
564 * Returns the album with the given ID, optionally creating a new album if
565 * an album with the given ID can not be found.
568 * The ID of the album
569 * @return The album with the given ID, or {@code null} if no album with the
572 public Album getAlbum(String albumId) {
573 return database.getAlbum(albumId).orNull();
576 public ImageBuilder imageBuilder() {
577 return database.newImageBuilder();
581 * Returns the image with the given ID, creating it if necessary.
584 * The ID of the image
585 * @return The image with the given ID
587 public Image getImage(String imageId) {
588 return getImage(imageId, true);
592 * Returns the image with the given ID, optionally creating it if it does
596 * The ID of the image
598 * {@code true} to create an image if none exists with the given
600 * @return The image with the given ID, or {@code null} if none exists and
603 public Image getImage(String imageId, boolean create) {
604 Optional<Image> image = database.getImage(imageId);
605 if (image.isPresent()) {
611 Image newImage = database.newImageBuilder().withId(imageId).build();
612 database.storeImage(newImage);
617 * Returns the temporary image with the given ID.
620 * The ID of the temporary image
621 * @return The temporary image, or {@code null} if there is no temporary
622 * image with the given ID
624 public TemporaryImage getTemporaryImage(String imageId) {
625 synchronized (temporaryImages) {
626 return temporaryImages.get(imageId);
635 * Locks the given Sone. A locked Sone will not be inserted by
636 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
642 public void lockSone(Sone sone) {
643 synchronized (lockedSones) {
644 if (lockedSones.add(sone)) {
645 eventBus.post(new SoneLockedEvent(sone));
651 * Unlocks the given Sone.
653 * @see #lockSone(Sone)
657 public void unlockSone(Sone sone) {
658 synchronized (lockedSones) {
659 if (lockedSones.remove(sone)) {
660 eventBus.post(new SoneUnlockedEvent(sone));
666 * Adds a local Sone from the given own identity.
669 * The own identity to create a Sone from
670 * @return The added (or already existing) Sone
672 public Sone addLocalSone(OwnIdentity ownIdentity) {
673 if (ownIdentity == null) {
674 logger.log(Level.WARNING, "Given OwnIdentity is null!");
677 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
678 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
679 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
680 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
682 /* TODO - load posts ’n stuff */
683 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
684 eventBus.register(soneInserter);
685 synchronized (soneInserters) {
686 soneInserters.put(sone, soneInserter);
689 sone.setStatus(SoneStatus.idle);
690 soneInserter.start();
695 * Creates a new Sone for the given own identity.
698 * The own identity to create a Sone for
699 * @return The created Sone
701 public Sone createSone(OwnIdentity ownIdentity) {
702 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
703 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
706 Sone sone = addLocalSone(ownIdentity);
708 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
709 touchConfiguration();
714 * Adds the Sone of the given identity.
717 * The identity whose Sone to add
718 * @return The added or already existing Sone
720 public Sone addRemoteSone(Identity identity) {
721 if (identity == null) {
722 logger.log(Level.WARNING, "Given Identity is null!");
725 final Long latestEdition = tryParse(fromNullable(
726 identity.getProperty("Sone.LatestEdition")).or("0"));
727 Optional<Sone> existingSone = getSone(identity.getId());
728 if (existingSone.isPresent() && existingSone.get().isLocal()) {
729 return existingSone.get();
731 boolean newSone = !existingSone.isPresent();
732 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
733 sone.setLatestEdition(latestEdition);
735 synchronized (knownSones) {
736 newSone = !knownSones.contains(sone.getId());
738 sone.setKnown(!newSone);
740 eventBus.post(new NewSoneFoundEvent(sone));
741 for (Sone localSone : getLocalSones()) {
742 if (localSone.getOptions().isAutoFollow()) {
743 followSone(localSone, sone.getId());
748 database.storeSone(sone);
749 soneDownloader.addSone(sone);
750 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
755 * Lets the given local Sone follow the Sone with the given ID.
758 * The local Sone that should follow another Sone
760 * The ID of the Sone to follow
762 public void followSone(Sone sone, String soneId) {
763 checkNotNull(sone, "sone must not be null");
764 checkNotNull(soneId, "soneId must not be null");
765 sone.addFriend(soneId);
766 synchronized (soneFollowingTimes) {
767 if (!soneFollowingTimes.containsKey(soneId)) {
768 long now = System.currentTimeMillis();
769 soneFollowingTimes.put(soneId, now);
770 Optional<Sone> followedSone = getSone(soneId);
771 if (!followedSone.isPresent()) {
774 for (Post post : followedSone.get().getPosts()) {
775 if (post.getTime() < now) {
779 for (PostReply reply : followedSone.get().getReplies()) {
780 if (reply.getTime() < now) {
781 markReplyKnown(reply);
786 touchConfiguration();
790 * Lets the given local Sone unfollow the Sone with the given ID.
793 * The local Sone that should unfollow another Sone
795 * The ID of the Sone being unfollowed
797 public void unfollowSone(Sone sone, String soneId) {
798 checkNotNull(sone, "sone must not be null");
799 checkNotNull(soneId, "soneId must not be null");
800 sone.removeFriend(soneId);
801 boolean unfollowedSoneStillFollowed = false;
802 for (Sone localSone : getLocalSones()) {
803 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
805 if (!unfollowedSoneStillFollowed) {
806 synchronized (soneFollowingTimes) {
807 soneFollowingTimes.remove(soneId);
810 touchConfiguration();
814 * Sets the trust value of the given origin Sone for the target Sone.
821 * The trust value (from {@code -100} to {@code 100})
823 public void setTrust(Sone origin, Sone target, int trustValue) {
824 checkNotNull(origin, "origin must not be null");
825 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
826 checkNotNull(target, "target must not be null");
827 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
828 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
832 * Removes any trust assignment for the given target Sone.
839 public void removeTrust(Sone origin, Sone target) {
840 checkNotNull(origin, "origin must not be null");
841 checkNotNull(target, "target must not be null");
842 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
843 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
847 * Assigns the configured positive trust value for the given target.
854 public void trustSone(Sone origin, Sone target) {
855 setTrust(origin, target, preferences.getPositiveTrust());
859 * Assigns the configured negative trust value for the given target.
866 public void distrustSone(Sone origin, Sone target) {
867 setTrust(origin, target, preferences.getNegativeTrust());
871 * Removes the trust assignment for the given target.
878 public void untrustSone(Sone origin, Sone target) {
879 removeTrust(origin, target);
883 * Updates the stored Sone with the given Sone.
888 public void updateSone(Sone sone) {
889 updateSone(sone, false);
893 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
894 * {@code true}, an older Sone than the current Sone can be given to restore
899 * @param soneRescueMode
900 * {@code true} if the stored Sone should be updated regardless
901 * of the age of the given Sone
903 public void updateSone(final Sone sone, boolean soneRescueMode) {
904 Optional<Sone> storedSone = getSone(sone.getId());
905 if (storedSone.isPresent()) {
906 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
907 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
910 /* find removed posts. */
911 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
912 soneChangeDetector.onNewPosts(new PostProcessor() {
914 public void processPost(Post post) {
915 if (post.getTime() < getSoneFollowingTime(sone)) {
917 } else if (!post.isKnown()) {
918 eventBus.post(new NewPostFoundEvent(post));
922 soneChangeDetector.onRemovedPosts(new PostProcessor() {
924 public void processPost(Post post) {
925 eventBus.post(new PostRemovedEvent(post));
928 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
930 public void processPostReply(PostReply postReply) {
931 if (postReply.getTime() < getSoneFollowingTime(sone)) {
932 postReply.setKnown(true);
933 } else if (!postReply.isKnown()) {
934 eventBus.post(new NewPostReplyFoundEvent(postReply));
938 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
940 public void processPostReply(PostReply postReply) {
941 eventBus.post(new PostReplyRemovedEvent(postReply));
944 soneChangeDetector.detectChanges(sone);
945 database.storeSone(sone);
946 sone.setOptions(storedSone.get().getOptions());
947 sone.setKnown(storedSone.get().isKnown());
948 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
949 if (sone.isLocal()) {
950 touchConfiguration();
956 * Deletes the given Sone. This will remove the Sone from the
957 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
958 * remove the context from its identity.
963 public void deleteSone(Sone sone) {
964 if (!(sone.getIdentity() instanceof OwnIdentity)) {
965 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
968 if (!getLocalSones().contains(sone)) {
969 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
972 // FIXME – implement in database
973 // sones.remove(sone.getId());
974 SoneInserter soneInserter = soneInserters.remove(sone);
976 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
977 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
979 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
980 } catch (ConfigurationException ce1) {
981 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
986 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
987 * known} before, a {@link MarkSoneKnownEvent} is fired.
990 * The Sone to mark as known
992 public void markSoneKnown(Sone sone) {
993 if (!sone.isKnown()) {
995 synchronized (knownSones) {
996 knownSones.add(sone.getId());
998 eventBus.post(new MarkSoneKnownEvent(sone));
999 touchConfiguration();
1004 * Loads and updates the given Sone from the configuration. If any error is
1005 * encountered, loading is aborted and the given Sone is not changed.
1008 * The Sone to load and update
1010 public void loadSone(Sone sone) {
1011 if (!sone.isLocal()) {
1012 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1015 logger.info(String.format("Loading local Sone: %s", sone));
1018 String sonePrefix = "Sone/" + sone.getId();
1019 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1020 if (soneTime == null) {
1021 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1024 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1027 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1028 Profile profile = configurationSoneParser.parseProfile();
1031 Collection<Post> posts;
1033 posts = configurationSoneParser.parsePosts(database);
1034 } catch (InvalidPostFound ipf) {
1035 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1040 Collection<PostReply> replies;
1042 replies = configurationSoneParser.parsePostReplies(database);
1043 } catch (InvalidPostReplyFound iprf) {
1044 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1048 /* load post likes. */
1049 Set<String> likedPostIds =
1050 configurationSoneParser.parseLikedPostIds();
1052 /* load reply likes. */
1053 Set<String> likedReplyIds =
1054 configurationSoneParser.parseLikedPostReplyIds();
1057 Set<String> friends = configurationSoneParser.parseFriends();
1060 List<Album> topLevelAlbums;
1063 configurationSoneParser.parseTopLevelAlbums(database);
1064 } catch (InvalidAlbumFound iaf) {
1065 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1067 } catch (InvalidParentAlbumFound ipaf) {
1068 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1069 ipaf.getAlbumParentId()));
1075 configurationSoneParser.parseImages(database);
1076 } catch (InvalidImageFound iif) {
1077 logger.log(WARNING, "Invalid image found, aborting load!");
1079 } catch (InvalidParentAlbumFound ipaf) {
1080 logger.log(Level.WARNING,
1081 format("Invalid album image (%s) encountered, aborting load!",
1082 ipaf.getAlbumParentId()));
1087 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1088 if (avatarId != null) {
1089 final Map<String, Image> images =
1090 configurationSoneParser.getImages();
1091 profile.setAvatar(images.get(avatarId));
1095 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1096 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1097 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1098 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1099 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1100 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1102 /* if we’re still here, Sone was loaded successfully. */
1103 synchronized (sone) {
1104 sone.setTime(soneTime);
1105 sone.setProfile(profile);
1106 sone.setPosts(posts);
1107 sone.setReplies(replies);
1108 sone.setLikePostIds(likedPostIds);
1109 sone.setLikeReplyIds(likedReplyIds);
1110 for (String friendId : friends) {
1111 followSone(sone, friendId);
1113 for (Album album : sone.getRootAlbum().getAlbums()) {
1114 sone.getRootAlbum().removeAlbum(album);
1116 for (Album album : topLevelAlbums) {
1117 sone.getRootAlbum().addAlbum(album);
1119 database.storeSone(sone);
1120 synchronized (soneInserters) {
1121 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1124 synchronized (knownSones) {
1125 for (String friend : friends) {
1126 knownSones.add(friend);
1129 for (Post post : posts) {
1130 post.setKnown(true);
1132 for (PostReply reply : replies) {
1133 reply.setKnown(true);
1136 logger.info(String.format("Sone loaded successfully: %s", sone));
1140 * Creates a new post.
1143 * The Sone that creates the post
1145 * The recipient Sone, or {@code null} if this post does not have
1148 * The text of the post
1149 * @return The created post
1151 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1152 return createPost(sone, recipient, System.currentTimeMillis(), text);
1156 * Creates a new post.
1159 * The Sone that creates the post
1161 * The recipient Sone, or {@code null} if this post does not have
1164 * The time of the post
1166 * The text of the post
1167 * @return The created post
1169 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1170 checkNotNull(text, "text must not be null");
1171 checkArgument(text.trim().length() > 0, "text must not be empty");
1172 if (!sone.isLocal()) {
1173 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1176 PostBuilder postBuilder = database.newPostBuilder();
1177 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1178 if (recipient.isPresent()) {
1179 postBuilder.to(recipient.get().getId());
1181 final Post post = postBuilder.build();
1182 database.storePost(post);
1183 eventBus.post(new NewPostFoundEvent(post));
1185 touchConfiguration();
1186 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1191 * Deletes the given post.
1194 * The post to delete
1196 public void deletePost(Post post) {
1197 if (!post.getSone().isLocal()) {
1198 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1201 database.removePost(post);
1202 eventBus.post(new PostRemovedEvent(post));
1203 markPostKnown(post);
1204 touchConfiguration();
1208 * Marks the given post as known, if it is currently not a known post
1209 * (according to {@link Post#isKnown()}).
1212 * The post to mark as known
1214 public void markPostKnown(Post post) {
1215 post.setKnown(true);
1216 eventBus.post(new MarkPostKnownEvent(post));
1217 touchConfiguration();
1218 for (PostReply reply : getReplies(post.getId())) {
1219 markReplyKnown(reply);
1224 * Bookmarks the post with the given ID.
1227 * The ID of the post to bookmark
1229 public void bookmarkPost(String id) {
1230 synchronized (bookmarkedPosts) {
1231 bookmarkedPosts.add(id);
1236 * Removes the given post from the bookmarks.
1239 * The post to unbookmark
1241 public void unbookmark(Post post) {
1242 unbookmarkPost(post.getId());
1246 * Removes the post with the given ID from the bookmarks.
1249 * The ID of the post to unbookmark
1251 public void unbookmarkPost(String id) {
1252 synchronized (bookmarkedPosts) {
1253 bookmarkedPosts.remove(id);
1258 * Creates a new reply.
1261 * The Sone that creates the reply
1263 * The post that this reply refers to
1265 * The text of the reply
1266 * @return The created reply
1268 public PostReply createReply(Sone sone, Post post, String text) {
1269 checkNotNull(text, "text must not be null");
1270 checkArgument(text.trim().length() > 0, "text must not be empty");
1271 if (!sone.isLocal()) {
1272 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1275 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1276 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1277 final PostReply reply = postReplyBuilder.build();
1278 database.storePostReply(reply);
1279 eventBus.post(new NewPostReplyFoundEvent(reply));
1280 sone.addReply(reply);
1281 touchConfiguration();
1282 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1287 * Deletes the given reply.
1290 * The reply to delete
1292 public void deleteReply(PostReply reply) {
1293 Sone sone = reply.getSone();
1294 if (!sone.isLocal()) {
1295 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1298 database.removePostReply(reply);
1299 markReplyKnown(reply);
1300 sone.removeReply(reply);
1301 touchConfiguration();
1305 * Marks the given reply as known, if it is currently not a known reply
1306 * (according to {@link Reply#isKnown()}).
1309 * The reply to mark as known
1311 public void markReplyKnown(PostReply reply) {
1312 boolean previouslyKnown = reply.isKnown();
1313 reply.setKnown(true);
1314 eventBus.post(new MarkPostReplyKnownEvent(reply));
1315 if (!previouslyKnown) {
1316 touchConfiguration();
1321 * Creates a new album for the given Sone.
1324 * The Sone to create the album for
1326 * The parent of the album (may be {@code null} to create a
1328 * @return The new album
1330 public Album createAlbum(Sone sone, Album parent) {
1331 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1332 database.storeAlbum(album);
1333 parent.addAlbum(album);
1338 * Deletes the given album. The owner of the album has to be a local Sone,
1339 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1342 * The album to remove
1344 public void deleteAlbum(Album album) {
1345 checkNotNull(album, "album must not be null");
1346 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1347 if (!album.isEmpty()) {
1350 album.getParent().removeAlbum(album);
1351 database.removeAlbum(album);
1352 touchConfiguration();
1356 * Creates a new image.
1359 * The Sone creating the image
1361 * The album the image will be inserted into
1362 * @param temporaryImage
1363 * The temporary image to create the image from
1364 * @return The newly created image
1366 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1367 checkNotNull(sone, "sone must not be null");
1368 checkNotNull(album, "album must not be null");
1369 checkNotNull(temporaryImage, "temporaryImage must not be null");
1370 checkArgument(sone.isLocal(), "sone must be a local Sone");
1371 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1372 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1373 album.addImage(image);
1374 database.storeImage(image);
1375 imageInserter.insertImage(temporaryImage, image);
1380 * Deletes the given image. This method will also delete a matching
1383 * @see #deleteTemporaryImage(String)
1385 * The image to delete
1387 public void deleteImage(Image image) {
1388 checkNotNull(image, "image must not be null");
1389 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1390 deleteTemporaryImage(image.getId());
1391 image.getAlbum().removeImage(image);
1392 database.removeImage(image);
1393 touchConfiguration();
1397 * Creates a new temporary image.
1400 * The MIME type of the temporary image
1402 * The encoded data of the image
1403 * @return The temporary image
1405 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1406 TemporaryImage temporaryImage = new TemporaryImage();
1407 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1408 synchronized (temporaryImages) {
1409 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1411 return temporaryImage;
1415 * Deletes the temporary image with the given ID.
1418 * The ID of the temporary image to delete
1420 public void deleteTemporaryImage(String imageId) {
1421 checkNotNull(imageId, "imageId must not be null");
1422 synchronized (temporaryImages) {
1423 temporaryImages.remove(imageId);
1425 Image image = getImage(imageId, false);
1426 if (image != null) {
1427 imageInserter.cancelImageInsert(image);
1432 * Notifies the core that the configuration, either of the core or of a
1433 * single local Sone, has changed, and that the configuration should be
1436 public void touchConfiguration() {
1437 lastConfigurationUpdate = System.currentTimeMillis();
1448 public void serviceStart() {
1449 loadConfiguration();
1450 updateChecker.start();
1451 identityManager.start();
1452 webOfTrustUpdater.init();
1453 webOfTrustUpdater.start();
1461 public void serviceRun() {
1462 long lastSaved = System.currentTimeMillis();
1463 while (!shouldStop()) {
1465 long now = System.currentTimeMillis();
1466 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1467 for (Sone localSone : getLocalSones()) {
1468 saveSone(localSone);
1470 saveConfiguration();
1480 public void serviceStop() {
1481 localElementTicker.shutdownNow();
1482 synchronized (soneInserters) {
1483 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1484 soneInserter.getValue().stop();
1485 saveSone(soneInserter.getKey());
1488 saveConfiguration();
1490 webOfTrustUpdater.stop();
1491 updateChecker.stop();
1492 soneDownloader.stop();
1493 soneDownloaders.shutdown();
1494 identityManager.stop();
1502 * Saves the given Sone. This will persist all local settings for the given
1503 * Sone, such as the friends list and similar, private options.
1508 private synchronized void saveSone(Sone sone) {
1509 if (!sone.isLocal()) {
1510 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1513 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1514 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1518 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1520 /* save Sone into configuration. */
1521 String sonePrefix = "Sone/" + sone.getId();
1522 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1523 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1526 Profile profile = sone.getProfile();
1527 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1528 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1529 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1530 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1531 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1532 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1533 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1535 /* save profile fields. */
1536 int fieldCounter = 0;
1537 for (Field profileField : profile.getFields()) {
1538 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1539 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1540 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1542 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1545 int postCounter = 0;
1546 for (Post post : sone.getPosts()) {
1547 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1548 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1549 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1550 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1551 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1553 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1556 int replyCounter = 0;
1557 for (PostReply reply : sone.getReplies()) {
1558 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1559 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1560 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1561 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1562 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1564 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1566 /* save post likes. */
1567 int postLikeCounter = 0;
1568 for (String postId : sone.getLikedPostIds()) {
1569 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1571 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1573 /* save reply likes. */
1574 int replyLikeCounter = 0;
1575 for (String replyId : sone.getLikedReplyIds()) {
1576 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1578 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1581 int friendCounter = 0;
1582 for (String friendId : sone.getFriends()) {
1583 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1585 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1587 /* save albums. first, collect in a flat structure, top-level first. */
1588 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1590 int albumCounter = 0;
1591 for (Album album : albums) {
1592 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1593 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1594 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1595 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1596 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1597 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1599 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1602 int imageCounter = 0;
1603 for (Album album : albums) {
1604 for (Image image : album.getImages()) {
1605 if (!image.isInserted()) {
1608 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1609 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1610 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1611 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1612 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1613 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1614 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1615 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1616 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1619 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1622 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1623 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1624 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1625 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1626 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1627 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1629 configuration.save();
1631 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1633 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1634 } catch (ConfigurationException ce1) {
1635 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1640 * Saves the current options.
1642 private void saveConfiguration() {
1643 synchronized (configuration) {
1644 if (storingConfiguration) {
1645 logger.log(Level.FINE, "Already storing configuration…");
1648 storingConfiguration = true;
1651 /* store the options first. */
1653 preferences.saveTo(configuration);
1655 /* save known Sones. */
1656 int soneCounter = 0;
1657 synchronized (knownSones) {
1658 for (String knownSoneId : knownSones) {
1659 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1661 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1664 /* save Sone following times. */
1666 synchronized (soneFollowingTimes) {
1667 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1668 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1669 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1672 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1675 /* save known posts. */
1678 /* save bookmarked posts. */
1679 int bookmarkedPostCounter = 0;
1680 synchronized (bookmarkedPosts) {
1681 for (String bookmarkedPostId : bookmarkedPosts) {
1682 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1685 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1688 configuration.save();
1690 } catch (ConfigurationException ce1) {
1691 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1692 } catch (DatabaseException de1) {
1693 logger.log(Level.SEVERE, "Could not save database!", de1);
1695 synchronized (configuration) {
1696 storingConfiguration = false;
1702 * Loads the configuration.
1704 private void loadConfiguration() {
1705 new PreferencesLoader(preferences).loadFrom(configuration);
1707 /* load known Sones. */
1708 int soneCounter = 0;
1710 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1711 if (knownSoneId == null) {
1714 synchronized (knownSones) {
1715 knownSones.add(knownSoneId);
1719 /* load Sone following times. */
1722 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1723 if (soneId == null) {
1726 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1727 synchronized (soneFollowingTimes) {
1728 soneFollowingTimes.put(soneId, time);
1733 /* load bookmarked posts. */
1734 int bookmarkedPostCounter = 0;
1736 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1737 if (bookmarkedPostId == null) {
1740 synchronized (bookmarkedPosts) {
1741 bookmarkedPosts.add(bookmarkedPostId);
1748 * Notifies the core that a new {@link OwnIdentity} was added.
1750 * @param ownIdentityAddedEvent
1754 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1755 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1756 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1757 if (ownIdentity.hasContext("Sone")) {
1758 addLocalSone(ownIdentity);
1763 * Notifies the core that an {@link OwnIdentity} was removed.
1765 * @param ownIdentityRemovedEvent
1769 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1770 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1771 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1772 trustedIdentities.removeAll(ownIdentity);
1776 * Notifies the core that a new {@link Identity} was added.
1778 * @param identityAddedEvent
1782 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1783 Identity identity = identityAddedEvent.identity();
1784 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1785 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1786 addRemoteSone(identity);
1790 * Notifies the core that an {@link Identity} was updated.
1792 * @param identityUpdatedEvent
1796 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1797 Identity identity = identityUpdatedEvent.identity();
1798 final Sone sone = getRemoteSone(identity.getId());
1799 if (sone.isLocal()) {
1802 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1803 soneDownloader.addSone(sone);
1804 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1808 * Notifies the core that an {@link Identity} was removed.
1810 * @param identityRemovedEvent
1814 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1815 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1816 Identity identity = identityRemovedEvent.identity();
1817 trustedIdentities.remove(ownIdentity, identity);
1818 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1819 if (trustedIdentity.getKey().equals(ownIdentity)) {
1822 if (trustedIdentity.getValue().contains(identity)) {
1826 Optional<Sone> sone = getSone(identity.getId());
1827 if (!sone.isPresent()) {
1828 /* TODO - we don’t have the Sone anymore. should this happen? */
1831 database.removePosts(sone.get());
1832 for (Post post : sone.get().getPosts()) {
1833 eventBus.post(new PostRemovedEvent(post));
1835 database.removePostReplies(sone.get());
1836 for (PostReply reply : sone.get().getReplies()) {
1837 eventBus.post(new PostReplyRemovedEvent(reply));
1839 // TODO – implement in database
1840 // sones.remove(identity.getId());
1841 eventBus.post(new SoneRemovedEvent(sone.get()));
1845 * Deletes the temporary image.
1847 * @param imageInsertFinishedEvent
1851 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1852 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1853 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1854 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1855 touchConfiguration();
1859 class MarkPostKnown implements Runnable {
1861 private final Post post;
1863 public MarkPostKnown(Post post) {
1869 markPostKnown(post);
1875 class MarkReplyKnown implements Runnable {
1877 private final PostReply postReply;
1879 public MarkReplyKnown(PostReply postReply) {
1880 this.postReply = postReply;
1885 markReplyKnown(postReply);