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.Collection;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ScheduledExecutorService;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
47 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
48 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
49 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
50 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
52 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
53 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
54 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
55 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
56 import net.pterodactylus.sone.core.event.PostRemovedEvent;
57 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
58 import net.pterodactylus.sone.core.event.SoneLockedEvent;
59 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
60 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
61 import net.pterodactylus.sone.data.Album;
62 import net.pterodactylus.sone.data.Client;
63 import net.pterodactylus.sone.data.Image;
64 import net.pterodactylus.sone.data.Post;
65 import net.pterodactylus.sone.data.PostReply;
66 import net.pterodactylus.sone.data.Profile;
67 import net.pterodactylus.sone.data.Profile.Field;
68 import net.pterodactylus.sone.data.Reply;
69 import net.pterodactylus.sone.data.Sone;
70 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
71 import net.pterodactylus.sone.data.Sone.SoneStatus;
72 import net.pterodactylus.sone.data.TemporaryImage;
73 import net.pterodactylus.sone.database.AlbumBuilder;
74 import net.pterodactylus.sone.database.Database;
75 import net.pterodactylus.sone.database.DatabaseException;
76 import net.pterodactylus.sone.database.ImageBuilder;
77 import net.pterodactylus.sone.database.PostBuilder;
78 import net.pterodactylus.sone.database.PostProvider;
79 import net.pterodactylus.sone.database.PostReplyBuilder;
80 import net.pterodactylus.sone.database.PostReplyProvider;
81 import net.pterodactylus.sone.database.SoneBuilder;
82 import net.pterodactylus.sone.database.SoneProvider;
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.service.AbstractService;
95 import net.pterodactylus.util.thread.NamedThreadFactory;
97 import com.google.common.annotations.VisibleForTesting;
98 import com.google.common.base.Optional;
99 import com.google.common.collect.FluentIterable;
100 import com.google.common.collect.HashMultimap;
101 import com.google.common.collect.Multimap;
102 import com.google.common.collect.Multimaps;
103 import com.google.common.eventbus.EventBus;
104 import com.google.common.eventbus.Subscribe;
105 import com.google.inject.Inject;
106 import com.google.inject.Singleton;
111 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
114 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
117 private static final Logger logger = getLogger("Sone.Core");
119 /** The start time. */
120 private final long startupTime = System.currentTimeMillis();
122 /** The preferences. */
123 private final Preferences preferences;
125 /** The event bus. */
126 private final EventBus eventBus;
128 /** The configuration. */
129 private final Configuration configuration;
131 /** Whether we’re currently saving the configuration. */
132 private boolean storingConfiguration = false;
134 /** The identity manager. */
135 private final IdentityManager identityManager;
137 /** Interface to freenet. */
138 private final FreenetInterface freenetInterface;
140 /** The Sone downloader. */
141 private final SoneDownloader soneDownloader;
143 /** The image inserter. */
144 private final ImageInserter imageInserter;
146 /** Sone downloader thread-pool. */
147 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
149 /** The update checker. */
150 private final UpdateChecker updateChecker;
152 /** The trust updater. */
153 private final WebOfTrustUpdater webOfTrustUpdater;
155 /** The times Sones were followed. */
156 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
158 /** Locked local Sones. */
159 /* synchronize on itself. */
160 private final Set<Sone> lockedSones = new HashSet<Sone>();
162 /** Sone inserters. */
163 /* synchronize access on this on sones. */
164 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
166 /** Sone rescuers. */
167 /* synchronize access on this on sones. */
168 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
170 /** All known Sones. */
171 private final Set<String> knownSones = new HashSet<String>();
173 /** The post database. */
174 private final Database database;
176 /** Trusted identities, sorted by own identities. */
177 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
179 /** All temporary images. */
180 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
182 /** Ticker for threads that mark own elements as known. */
183 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
185 /** The time the configuration was last touched. */
186 private volatile long lastConfigurationUpdate;
189 * Creates a new core.
191 * @param configuration
192 * The configuration of the core
193 * @param freenetInterface
194 * The freenet interface
195 * @param identityManager
196 * The identity manager
197 * @param webOfTrustUpdater
198 * The WebOfTrust updater
205 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
207 this.configuration = configuration;
208 this.freenetInterface = freenetInterface;
209 this.identityManager = identityManager;
210 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
211 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
212 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
213 this.webOfTrustUpdater = webOfTrustUpdater;
214 this.eventBus = eventBus;
215 this.database = database;
216 preferences = new Preferences(eventBus);
220 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = soneDownloader;
226 this.imageInserter = imageInserter;
227 this.updateChecker = updateChecker;
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
230 this.database = database;
231 preferences = new Preferences(eventBus);
239 * Returns the time Sone was started.
241 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
243 public long getStartupTime() {
248 * Returns the options used by the core.
250 * @return The options of the core
252 public Preferences getPreferences() {
257 * Returns the identity manager used by the core.
259 * @return The identity manager
261 public IdentityManager getIdentityManager() {
262 return identityManager;
266 * Returns the update checker.
268 * @return The update checker
270 public UpdateChecker getUpdateChecker() {
271 return updateChecker;
275 * Returns the Sone rescuer for the given local Sone.
278 * The local Sone to get the rescuer for
279 * @return The Sone rescuer for the given Sone
281 public SoneRescuer getSoneRescuer(Sone sone) {
282 checkNotNull(sone, "sone must not be null");
283 checkArgument(sone.isLocal(), "sone must be local");
284 synchronized (soneRescuers) {
285 SoneRescuer soneRescuer = soneRescuers.get(sone);
286 if (soneRescuer == null) {
287 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
288 soneRescuers.put(sone, soneRescuer);
296 * Returns whether the given Sone is currently locked.
300 * @return {@code true} if the Sone is locked, {@code false} if it is not
302 public boolean isLocked(Sone sone) {
303 synchronized (lockedSones) {
304 return lockedSones.contains(sone);
308 public SoneBuilder soneBuilder() {
309 return database.newSoneBuilder();
316 public Collection<Sone> getSones() {
317 return database.getSones();
321 * Returns the Sone with the given ID, regardless whether it’s local or
325 * The ID of the Sone to get
326 * @return The Sone with the given ID, or {@code null} if there is no such
330 public Optional<Sone> getSone(String id) {
331 return database.getSone(id);
338 public Collection<Sone> getLocalSones() {
339 return database.getLocalSones();
343 * Returns the local Sone with the given ID, optionally creating a new Sone.
347 * @return The Sone with the given ID, or {@code null}
349 public Sone getLocalSone(String id) {
350 Optional<Sone> sone = database.getSone(id);
351 if (sone.isPresent() && sone.get().isLocal()) {
361 public Collection<Sone> getRemoteSones() {
362 return database.getRemoteSones();
366 * Returns the remote Sone with the given ID.
370 * The ID of the remote Sone to get
371 * @return The Sone with the given ID
373 public Sone getRemoteSone(String id) {
374 return database.getSone(id).orNull();
378 * Returns whether the given Sone has been modified.
381 * The Sone to check for modifications
382 * @return {@code true} if a modification has been detected in the Sone,
383 * {@code false} otherwise
385 public boolean isModifiedSone(Sone sone) {
386 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
390 * Returns the time when the given was first followed by any local Sone.
393 * The Sone to get the time for
394 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
395 * been followed, or {@link Long#MAX_VALUE}
397 public long getSoneFollowingTime(Sone sone) {
398 synchronized (soneFollowingTimes) {
399 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
404 * Returns a post builder.
406 * @return A new post builder
408 public PostBuilder postBuilder() {
409 return database.newPostBuilder();
416 public Optional<Post> getPost(String postId) {
417 return database.getPost(postId);
424 public Collection<Post> getPosts(String soneId) {
425 return database.getPosts(soneId);
432 public Collection<Post> getDirectedPosts(final String recipientId) {
433 checkNotNull(recipientId, "recipient must not be null");
434 return database.getDirectedPosts(recipientId);
438 * Returns a post reply builder.
440 * @return A new post reply builder
442 public PostReplyBuilder postReplyBuilder() {
443 return database.newPostReplyBuilder();
450 public Optional<PostReply> getPostReply(String replyId) {
451 return database.getPostReply(replyId);
458 public List<PostReply> getReplies(final String postId) {
459 return database.getReplies(postId);
463 * Returns all Sones that have liked the given post.
466 * The post to get the liking Sones for
467 * @return The Sones that like the given post
469 public Set<Sone> getLikes(Post post) {
470 Set<Sone> sones = new HashSet<Sone>();
471 for (Sone sone : getSones()) {
472 if (sone.getLikedPostIds().contains(post.getId())) {
480 * Returns all Sones that have liked the given reply.
483 * The reply to get the liking Sones for
484 * @return The Sones that like the given reply
486 public Set<Sone> getLikes(PostReply reply) {
487 Set<Sone> sones = new HashSet<Sone>();
488 for (Sone sone : getSones()) {
489 if (sone.getLikedReplyIds().contains(reply.getId())) {
497 * Returns whether the given post is bookmarked.
501 * @return {@code true} if the given post is bookmarked, {@code false}
504 public boolean isBookmarked(Post post) {
505 return database.isPostBookmarked(post);
509 * Returns all currently known bookmarked posts.
511 * @return All bookmarked posts
513 public Set<Post> getBookmarkedPosts() {
514 return database.getBookmarkedPosts();
517 public AlbumBuilder albumBuilder() {
518 return database.newAlbumBuilder();
522 * Returns the album with the given ID, optionally creating a new album if
523 * an album with the given ID can not be found.
526 * The ID of the album
527 * @return The album with the given ID, or {@code null} if no album with the
530 public Album getAlbum(String albumId) {
531 return database.getAlbum(albumId).orNull();
534 public ImageBuilder imageBuilder() {
535 return database.newImageBuilder();
539 * Returns the image with the given ID, creating it if necessary.
542 * The ID of the image
543 * @return The image with the given ID
545 public Image getImage(String imageId) {
546 return getImage(imageId, true);
550 * Returns the image with the given ID, optionally creating it if it does
554 * The ID of the image
556 * {@code true} to create an image if none exists with the given
558 * @return The image with the given ID, or {@code null} if none exists and
561 public Image getImage(String imageId, boolean create) {
562 Optional<Image> image = database.getImage(imageId);
563 if (image.isPresent()) {
569 Image newImage = database.newImageBuilder().withId(imageId).build();
570 database.storeImage(newImage);
575 * Returns the temporary image with the given ID.
578 * The ID of the temporary image
579 * @return The temporary image, or {@code null} if there is no temporary
580 * image with the given ID
582 public TemporaryImage getTemporaryImage(String imageId) {
583 synchronized (temporaryImages) {
584 return temporaryImages.get(imageId);
593 * Locks the given Sone. A locked Sone will not be inserted by
594 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
600 public void lockSone(Sone sone) {
601 synchronized (lockedSones) {
602 if (lockedSones.add(sone)) {
603 eventBus.post(new SoneLockedEvent(sone));
609 * Unlocks the given Sone.
611 * @see #lockSone(Sone)
615 public void unlockSone(Sone sone) {
616 synchronized (lockedSones) {
617 if (lockedSones.remove(sone)) {
618 eventBus.post(new SoneUnlockedEvent(sone));
624 * Adds a local Sone from the given own identity.
627 * The own identity to create a Sone from
628 * @return The added (or already existing) Sone
630 public Sone addLocalSone(OwnIdentity ownIdentity) {
631 if (ownIdentity == null) {
632 logger.log(Level.WARNING, "Given OwnIdentity is null!");
635 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
636 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
637 sone.setLatestEdition(fromNullable(tryParse(ownIdentity.getProperty("Sone.LatestEdition"))).or(0L));
638 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
640 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
641 eventBus.register(soneInserter);
642 synchronized (soneInserters) {
643 soneInserters.put(sone, soneInserter);
646 sone.setStatus(SoneStatus.idle);
647 soneInserter.start();
652 * Creates a new Sone for the given own identity.
655 * The own identity to create a Sone for
656 * @return The created Sone
658 public Sone createSone(OwnIdentity ownIdentity) {
659 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
660 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
663 Sone sone = addLocalSone(ownIdentity);
665 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
666 touchConfiguration();
671 * Adds the Sone of the given identity.
674 * The identity whose Sone to add
675 * @return The added or already existing Sone
677 public Sone addRemoteSone(Identity identity) {
678 if (identity == null) {
679 logger.log(Level.WARNING, "Given Identity is null!");
682 final Long latestEdition = tryParse(fromNullable(
683 identity.getProperty("Sone.LatestEdition")).or("0"));
684 Optional<Sone> existingSone = getSone(identity.getId());
685 if (existingSone.isPresent() && existingSone.get().isLocal()) {
686 return existingSone.get();
688 boolean newSone = !existingSone.isPresent();
689 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
690 sone.setLatestEdition(latestEdition);
692 synchronized (knownSones) {
693 newSone = !knownSones.contains(sone.getId());
695 sone.setKnown(!newSone);
697 eventBus.post(new NewSoneFoundEvent(sone));
698 for (Sone localSone : getLocalSones()) {
699 if (localSone.getOptions().isAutoFollow()) {
700 followSone(localSone, sone.getId());
705 database.storeSone(sone);
706 soneDownloader.addSone(sone);
707 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
712 * Lets the given local Sone follow the Sone with the given ID.
715 * The local Sone that should follow another Sone
717 * The ID of the Sone to follow
719 public void followSone(Sone sone, String soneId) {
720 checkNotNull(sone, "sone must not be null");
721 checkNotNull(soneId, "soneId must not be null");
722 sone.addFriend(soneId);
723 synchronized (soneFollowingTimes) {
724 if (!soneFollowingTimes.containsKey(soneId)) {
725 long now = System.currentTimeMillis();
726 soneFollowingTimes.put(soneId, now);
727 Optional<Sone> followedSone = getSone(soneId);
728 if (!followedSone.isPresent()) {
731 for (Post post : followedSone.get().getPosts()) {
732 if (post.getTime() < now) {
736 for (PostReply reply : followedSone.get().getReplies()) {
737 if (reply.getTime() < now) {
738 markReplyKnown(reply);
743 touchConfiguration();
747 * Lets the given local Sone unfollow the Sone with the given ID.
750 * The local Sone that should unfollow another Sone
752 * The ID of the Sone being unfollowed
754 public void unfollowSone(Sone sone, String soneId) {
755 checkNotNull(sone, "sone must not be null");
756 checkNotNull(soneId, "soneId must not be null");
757 sone.removeFriend(soneId);
758 boolean unfollowedSoneStillFollowed = false;
759 for (Sone localSone : getLocalSones()) {
760 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
762 if (!unfollowedSoneStillFollowed) {
763 synchronized (soneFollowingTimes) {
764 soneFollowingTimes.remove(soneId);
767 touchConfiguration();
771 * Sets the trust value of the given origin Sone for the target Sone.
778 * The trust value (from {@code -100} to {@code 100})
780 public void setTrust(Sone origin, Sone target, int trustValue) {
781 checkNotNull(origin, "origin must not be null");
782 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
783 checkNotNull(target, "target must not be null");
784 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
785 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
789 * Removes any trust assignment for the given target Sone.
796 public void removeTrust(Sone origin, Sone target) {
797 checkNotNull(origin, "origin must not be null");
798 checkNotNull(target, "target must not be null");
799 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
800 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
804 * Assigns the configured positive trust value for the given target.
811 public void trustSone(Sone origin, Sone target) {
812 setTrust(origin, target, preferences.getPositiveTrust());
816 * Assigns the configured negative trust value for the given target.
823 public void distrustSone(Sone origin, Sone target) {
824 setTrust(origin, target, preferences.getNegativeTrust());
828 * Removes the trust assignment for the given target.
835 public void untrustSone(Sone origin, Sone target) {
836 removeTrust(origin, target);
840 * Updates the stored Sone with the given Sone.
845 public void updateSone(Sone sone) {
846 updateSone(sone, false);
850 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
851 * {@code true}, an older Sone than the current Sone can be given to restore
856 * @param soneRescueMode
857 * {@code true} if the stored Sone should be updated regardless
858 * of the age of the given Sone
860 public void updateSone(final Sone sone, boolean soneRescueMode) {
861 Optional<Sone> storedSone = getSone(sone.getId());
862 if (storedSone.isPresent()) {
863 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
864 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
867 /* find removed posts. */
868 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
869 soneChangeDetector.onNewPosts(new PostProcessor() {
871 public void processPost(Post post) {
872 if (post.getTime() < getSoneFollowingTime(sone)) {
874 } else if (!post.isKnown()) {
875 eventBus.post(new NewPostFoundEvent(post));
879 soneChangeDetector.onRemovedPosts(new PostProcessor() {
881 public void processPost(Post post) {
882 eventBus.post(new PostRemovedEvent(post));
885 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
887 public void processPostReply(PostReply postReply) {
888 if (postReply.getTime() < getSoneFollowingTime(sone)) {
889 postReply.setKnown(true);
890 } else if (!postReply.isKnown()) {
891 eventBus.post(new NewPostReplyFoundEvent(postReply));
895 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
897 public void processPostReply(PostReply postReply) {
898 eventBus.post(new PostReplyRemovedEvent(postReply));
901 soneChangeDetector.detectChanges(sone);
902 database.storeSone(sone);
903 sone.setOptions(storedSone.get().getOptions());
904 sone.setKnown(storedSone.get().isKnown());
905 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
906 if (sone.isLocal()) {
907 touchConfiguration();
913 * Deletes the given Sone. This will remove the Sone from the
914 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
915 * remove the context from its identity.
920 public void deleteSone(Sone sone) {
921 if (!(sone.getIdentity() instanceof OwnIdentity)) {
922 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
925 if (!getLocalSones().contains(sone)) {
926 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
929 SoneInserter soneInserter = soneInserters.remove(sone);
931 database.removeSone(sone);
932 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
933 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
935 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
936 } catch (ConfigurationException ce1) {
937 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
942 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
943 * known} before, a {@link MarkSoneKnownEvent} is fired.
946 * The Sone to mark as known
948 public void markSoneKnown(Sone sone) {
949 if (!sone.isKnown()) {
951 synchronized (knownSones) {
952 knownSones.add(sone.getId());
954 eventBus.post(new MarkSoneKnownEvent(sone));
955 touchConfiguration();
960 * Loads and updates the given Sone from the configuration. If any error is
961 * encountered, loading is aborted and the given Sone is not changed.
964 * The Sone to load and update
966 public void loadSone(Sone sone) {
967 if (!sone.isLocal()) {
968 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
971 logger.info(String.format("Loading local Sone: %s", sone));
974 String sonePrefix = "Sone/" + sone.getId();
975 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
976 if (soneTime == null) {
977 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
980 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
983 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
984 Profile profile = configurationSoneParser.parseProfile();
987 Collection<Post> posts;
989 posts = configurationSoneParser.parsePosts(database);
990 } catch (InvalidPostFound ipf) {
991 logger.log(Level.WARNING, "Invalid post found, aborting load!");
996 Collection<PostReply> replies;
998 replies = configurationSoneParser.parsePostReplies(database);
999 } catch (InvalidPostReplyFound iprf) {
1000 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1004 /* load post likes. */
1005 Set<String> likedPostIds =
1006 configurationSoneParser.parseLikedPostIds();
1008 /* load reply likes. */
1009 Set<String> likedReplyIds =
1010 configurationSoneParser.parseLikedPostReplyIds();
1013 Set<String> friends = configurationSoneParser.parseFriends();
1016 List<Album> topLevelAlbums;
1019 configurationSoneParser.parseTopLevelAlbums(database);
1020 } catch (InvalidAlbumFound iaf) {
1021 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1023 } catch (InvalidParentAlbumFound ipaf) {
1024 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1025 ipaf.getAlbumParentId()));
1031 configurationSoneParser.parseImages(database);
1032 } catch (InvalidImageFound iif) {
1033 logger.log(WARNING, "Invalid image found, aborting load!");
1035 } catch (InvalidParentAlbumFound ipaf) {
1036 logger.log(Level.WARNING,
1037 format("Invalid album image (%s) encountered, aborting load!",
1038 ipaf.getAlbumParentId()));
1043 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1044 if (avatarId != null) {
1045 final Map<String, Image> images =
1046 configurationSoneParser.getImages();
1047 profile.setAvatar(images.get(avatarId));
1051 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1052 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1053 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1054 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1055 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1056 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1058 /* if we’re still here, Sone was loaded successfully. */
1059 synchronized (sone) {
1060 sone.setTime(soneTime);
1061 sone.setProfile(profile);
1062 sone.setPosts(posts);
1063 sone.setReplies(replies);
1064 sone.setLikePostIds(likedPostIds);
1065 sone.setLikeReplyIds(likedReplyIds);
1066 for (String friendId : friends) {
1067 followSone(sone, friendId);
1069 for (Album album : sone.getRootAlbum().getAlbums()) {
1070 sone.getRootAlbum().removeAlbum(album);
1072 for (Album album : topLevelAlbums) {
1073 sone.getRootAlbum().addAlbum(album);
1075 database.storeSone(sone);
1076 synchronized (soneInserters) {
1077 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1080 synchronized (knownSones) {
1081 for (String friend : friends) {
1082 knownSones.add(friend);
1085 for (Post post : posts) {
1086 post.setKnown(true);
1088 for (PostReply reply : replies) {
1089 reply.setKnown(true);
1092 logger.info(String.format("Sone loaded successfully: %s", sone));
1096 * Creates a new post.
1099 * The Sone that creates the post
1101 * The recipient Sone, or {@code null} if this post does not have
1104 * The text of the post
1105 * @return The created post
1107 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1108 checkNotNull(text, "text must not be null");
1109 checkArgument(text.trim().length() > 0, "text must not be empty");
1110 if (!sone.isLocal()) {
1111 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1114 PostBuilder postBuilder = database.newPostBuilder();
1115 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1116 if (recipient.isPresent()) {
1117 postBuilder.to(recipient.get().getId());
1119 final Post post = postBuilder.build();
1120 database.storePost(post);
1121 eventBus.post(new NewPostFoundEvent(post));
1123 touchConfiguration();
1124 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1129 * Deletes the given post.
1132 * The post to delete
1134 public void deletePost(Post post) {
1135 if (!post.getSone().isLocal()) {
1136 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1139 database.removePost(post);
1140 eventBus.post(new PostRemovedEvent(post));
1141 markPostKnown(post);
1142 touchConfiguration();
1146 * Marks the given post as known, if it is currently not a known post
1147 * (according to {@link Post#isKnown()}).
1150 * The post to mark as known
1152 public void markPostKnown(Post post) {
1153 post.setKnown(true);
1154 eventBus.post(new MarkPostKnownEvent(post));
1155 touchConfiguration();
1156 for (PostReply reply : getReplies(post.getId())) {
1157 markReplyKnown(reply);
1161 public void bookmarkPost(Post post) {
1162 database.bookmarkPost(post);
1166 * Removes the given post from the bookmarks.
1169 * The post to unbookmark
1171 public void unbookmarkPost(Post post) {
1172 database.unbookmarkPost(post);
1176 * Creates a new reply.
1179 * The Sone that creates the reply
1181 * The post that this reply refers to
1183 * The text of the reply
1184 * @return The created reply
1186 public PostReply createReply(Sone sone, Post post, String text) {
1187 checkNotNull(text, "text must not be null");
1188 checkArgument(text.trim().length() > 0, "text must not be empty");
1189 if (!sone.isLocal()) {
1190 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1193 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1194 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1195 final PostReply reply = postReplyBuilder.build();
1196 database.storePostReply(reply);
1197 eventBus.post(new NewPostReplyFoundEvent(reply));
1198 sone.addReply(reply);
1199 touchConfiguration();
1200 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1205 * Deletes the given reply.
1208 * The reply to delete
1210 public void deleteReply(PostReply reply) {
1211 Sone sone = reply.getSone();
1212 if (!sone.isLocal()) {
1213 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1216 database.removePostReply(reply);
1217 markReplyKnown(reply);
1218 sone.removeReply(reply);
1219 touchConfiguration();
1223 * Marks the given reply as known, if it is currently not a known reply
1224 * (according to {@link Reply#isKnown()}).
1227 * The reply to mark as known
1229 public void markReplyKnown(PostReply reply) {
1230 boolean previouslyKnown = reply.isKnown();
1231 reply.setKnown(true);
1232 eventBus.post(new MarkPostReplyKnownEvent(reply));
1233 if (!previouslyKnown) {
1234 touchConfiguration();
1239 * Creates a new album for the given Sone.
1242 * The Sone to create the album for
1244 * The parent of the album (may be {@code null} to create a
1246 * @return The new album
1248 public Album createAlbum(Sone sone, Album parent) {
1249 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1250 database.storeAlbum(album);
1251 parent.addAlbum(album);
1256 * Deletes the given album. The owner of the album has to be a local Sone,
1257 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1260 * The album to remove
1262 public void deleteAlbum(Album album) {
1263 checkNotNull(album, "album must not be null");
1264 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1265 if (!album.isEmpty()) {
1268 album.getParent().removeAlbum(album);
1269 database.removeAlbum(album);
1270 touchConfiguration();
1274 * Creates a new image.
1277 * The Sone creating the image
1279 * The album the image will be inserted into
1280 * @param temporaryImage
1281 * The temporary image to create the image from
1282 * @return The newly created image
1284 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1285 checkNotNull(sone, "sone must not be null");
1286 checkNotNull(album, "album must not be null");
1287 checkNotNull(temporaryImage, "temporaryImage must not be null");
1288 checkArgument(sone.isLocal(), "sone must be a local Sone");
1289 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1290 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1291 album.addImage(image);
1292 database.storeImage(image);
1293 imageInserter.insertImage(temporaryImage, image);
1298 * Deletes the given image. This method will also delete a matching
1301 * @see #deleteTemporaryImage(String)
1303 * The image to delete
1305 public void deleteImage(Image image) {
1306 checkNotNull(image, "image must not be null");
1307 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1308 deleteTemporaryImage(image.getId());
1309 image.getAlbum().removeImage(image);
1310 database.removeImage(image);
1311 touchConfiguration();
1315 * Creates a new temporary image.
1318 * The MIME type of the temporary image
1320 * The encoded data of the image
1321 * @return The temporary image
1323 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1324 TemporaryImage temporaryImage = new TemporaryImage();
1325 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1326 synchronized (temporaryImages) {
1327 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1329 return temporaryImage;
1333 * Deletes the temporary image with the given ID.
1336 * The ID of the temporary image to delete
1338 public void deleteTemporaryImage(String imageId) {
1339 checkNotNull(imageId, "imageId must not be null");
1340 synchronized (temporaryImages) {
1341 temporaryImages.remove(imageId);
1343 Image image = getImage(imageId, false);
1344 if (image != null) {
1345 imageInserter.cancelImageInsert(image);
1350 * Notifies the core that the configuration, either of the core or of a
1351 * single local Sone, has changed, and that the configuration should be
1354 public void touchConfiguration() {
1355 lastConfigurationUpdate = System.currentTimeMillis();
1366 public void serviceStart() {
1367 loadConfiguration();
1368 updateChecker.start();
1369 identityManager.start();
1370 webOfTrustUpdater.init();
1371 webOfTrustUpdater.start();
1379 public void serviceRun() {
1380 long lastSaved = System.currentTimeMillis();
1381 while (!shouldStop()) {
1383 long now = System.currentTimeMillis();
1384 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1385 for (Sone localSone : getLocalSones()) {
1386 saveSone(localSone);
1388 saveConfiguration();
1398 public void serviceStop() {
1399 localElementTicker.shutdownNow();
1400 synchronized (soneInserters) {
1401 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1402 soneInserter.getValue().stop();
1403 saveSone(soneInserter.getKey());
1406 saveConfiguration();
1408 webOfTrustUpdater.stop();
1409 updateChecker.stop();
1410 soneDownloader.stop();
1411 soneDownloaders.shutdown();
1412 identityManager.stop();
1420 * Saves the given Sone. This will persist all local settings for the given
1421 * Sone, such as the friends list and similar, private options.
1426 private synchronized void saveSone(Sone sone) {
1427 if (!sone.isLocal()) {
1428 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1431 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1432 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1436 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1438 /* save Sone into configuration. */
1439 String sonePrefix = "Sone/" + sone.getId();
1440 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1441 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1444 Profile profile = sone.getProfile();
1445 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1446 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1447 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1448 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1449 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1450 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1451 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1453 /* save profile fields. */
1454 int fieldCounter = 0;
1455 for (Field profileField : profile.getFields()) {
1456 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1457 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1458 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1460 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1463 int postCounter = 0;
1464 for (Post post : sone.getPosts()) {
1465 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1466 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1467 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1468 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1469 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1471 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1474 int replyCounter = 0;
1475 for (PostReply reply : sone.getReplies()) {
1476 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1477 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1478 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1479 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1480 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1482 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1484 /* save post likes. */
1485 int postLikeCounter = 0;
1486 for (String postId : sone.getLikedPostIds()) {
1487 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1489 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1491 /* save reply likes. */
1492 int replyLikeCounter = 0;
1493 for (String replyId : sone.getLikedReplyIds()) {
1494 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1496 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1499 int friendCounter = 0;
1500 for (String friendId : sone.getFriends()) {
1501 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1503 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1505 /* save albums. first, collect in a flat structure, top-level first. */
1506 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1508 int albumCounter = 0;
1509 for (Album album : albums) {
1510 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1511 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1512 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1513 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1514 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1515 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1517 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1520 int imageCounter = 0;
1521 for (Album album : albums) {
1522 for (Image image : album.getImages()) {
1523 if (!image.isInserted()) {
1526 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1527 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1528 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1529 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1530 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1531 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1532 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1533 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1534 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1537 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1540 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1541 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1542 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1543 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1544 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1545 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1547 configuration.save();
1549 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1551 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1552 } catch (ConfigurationException ce1) {
1553 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1558 * Saves the current options.
1560 private void saveConfiguration() {
1561 synchronized (configuration) {
1562 if (storingConfiguration) {
1563 logger.log(Level.FINE, "Already storing configuration…");
1566 storingConfiguration = true;
1569 /* store the options first. */
1571 preferences.saveTo(configuration);
1573 /* save known Sones. */
1574 int soneCounter = 0;
1575 synchronized (knownSones) {
1576 for (String knownSoneId : knownSones) {
1577 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1579 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1582 /* save Sone following times. */
1584 synchronized (soneFollowingTimes) {
1585 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1586 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1587 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1590 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1593 /* save known posts. */
1597 configuration.save();
1599 } catch (ConfigurationException ce1) {
1600 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1601 } catch (DatabaseException de1) {
1602 logger.log(Level.SEVERE, "Could not save database!", de1);
1604 synchronized (configuration) {
1605 storingConfiguration = false;
1611 * Loads the configuration.
1613 private void loadConfiguration() {
1614 new PreferencesLoader(preferences).loadFrom(configuration);
1616 /* load known Sones. */
1617 int soneCounter = 0;
1619 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1620 if (knownSoneId == null) {
1623 synchronized (knownSones) {
1624 knownSones.add(knownSoneId);
1628 /* load Sone following times. */
1631 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1632 if (soneId == null) {
1635 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1636 synchronized (soneFollowingTimes) {
1637 soneFollowingTimes.put(soneId, time);
1644 * Notifies the core that a new {@link OwnIdentity} was added.
1646 * @param ownIdentityAddedEvent
1650 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1651 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1652 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1653 if (ownIdentity.hasContext("Sone")) {
1654 addLocalSone(ownIdentity);
1659 * Notifies the core that an {@link OwnIdentity} was removed.
1661 * @param ownIdentityRemovedEvent
1665 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1666 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1667 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1668 trustedIdentities.removeAll(ownIdentity);
1672 * Notifies the core that a new {@link Identity} was added.
1674 * @param identityAddedEvent
1678 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1679 Identity identity = identityAddedEvent.identity();
1680 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1681 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1682 addRemoteSone(identity);
1686 * Notifies the core that an {@link Identity} was updated.
1688 * @param identityUpdatedEvent
1692 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1693 Identity identity = identityUpdatedEvent.identity();
1694 final Sone sone = getRemoteSone(identity.getId());
1695 if (sone.isLocal()) {
1698 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1699 soneDownloader.addSone(sone);
1700 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1704 * Notifies the core that an {@link Identity} was removed.
1706 * @param identityRemovedEvent
1710 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1711 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1712 Identity identity = identityRemovedEvent.identity();
1713 trustedIdentities.remove(ownIdentity, identity);
1714 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1715 if (trustedIdentity.getKey().equals(ownIdentity)) {
1718 if (trustedIdentity.getValue().contains(identity)) {
1722 Optional<Sone> sone = getSone(identity.getId());
1723 if (!sone.isPresent()) {
1724 /* TODO - we don’t have the Sone anymore. should this happen? */
1727 database.removeSone(sone.get());
1728 eventBus.post(new SoneRemovedEvent(sone.get()));
1732 * Deletes the temporary image.
1734 * @param imageInsertFinishedEvent
1738 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1739 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1740 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1741 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1742 touchConfiguration();
1746 class MarkPostKnown implements Runnable {
1748 private final Post post;
1750 public MarkPostKnown(Post post) {
1756 markPostKnown(post);
1762 class MarkReplyKnown implements Runnable {
1764 private final PostReply postReply;
1766 public MarkReplyKnown(PostReply postReply) {
1767 this.postReply = postReply;
1772 markReplyKnown(postReply);