2 * Sone - Core.java - Copyright © 2010–2019 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.atomic.*;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
44 import javax.annotation.Nonnull;
45 import javax.annotation.Nullable;
47 import com.codahale.metrics.*;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
51 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
52 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
53 import net.pterodactylus.sone.core.event.*;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.database.AlbumBuilder;
67 import net.pterodactylus.sone.database.Database;
68 import net.pterodactylus.sone.database.DatabaseException;
69 import net.pterodactylus.sone.database.ImageBuilder;
70 import net.pterodactylus.sone.database.PostBuilder;
71 import net.pterodactylus.sone.database.PostProvider;
72 import net.pterodactylus.sone.database.PostReplyBuilder;
73 import net.pterodactylus.sone.database.PostReplyProvider;
74 import net.pterodactylus.sone.database.SoneBuilder;
75 import net.pterodactylus.sone.database.SoneProvider;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.util.config.Configuration;
86 import net.pterodactylus.util.config.ConfigurationException;
87 import net.pterodactylus.util.service.AbstractService;
88 import net.pterodactylus.util.thread.NamedThreadFactory;
90 import com.google.common.annotations.VisibleForTesting;
91 import com.google.common.collect.FluentIterable;
92 import com.google.common.collect.HashMultimap;
93 import com.google.common.collect.Multimap;
94 import com.google.common.collect.Multimaps;
95 import com.google.common.eventbus.EventBus;
96 import com.google.common.eventbus.Subscribe;
97 import com.google.inject.Inject;
98 import com.google.inject.Singleton;
99 import kotlin.jvm.functions.Function1;
105 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
108 private static final Logger logger = getLogger(Core.class.getName());
110 /** The start time. */
111 private final long startupTime = System.currentTimeMillis();
113 private final AtomicBoolean debug = new AtomicBoolean(false);
115 /** The preferences. */
116 private final Preferences preferences;
118 /** The event bus. */
119 private final EventBus eventBus;
121 /** The configuration. */
122 private final Configuration configuration;
124 /** Whether we’re currently saving the configuration. */
125 private boolean storingConfiguration = false;
127 /** The identity manager. */
128 private final IdentityManager identityManager;
130 /** Interface to freenet. */
131 private final FreenetInterface freenetInterface;
133 /** The Sone downloader. */
134 private final SoneDownloader soneDownloader;
136 /** The image inserter. */
137 private final ImageInserter imageInserter;
139 /** Sone downloader thread-pool. */
140 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
142 /** The update checker. */
143 private final UpdateChecker updateChecker;
145 /** The trust updater. */
146 private final WebOfTrustUpdater webOfTrustUpdater;
148 /** Locked local Sones. */
149 /* synchronize on itself. */
150 private final Set<Sone> lockedSones = new HashSet<>();
152 /** Sone inserters. */
153 /* synchronize access on this on sones. */
154 private final Map<Sone, SoneInserter> soneInserters = new HashMap<>();
156 /** Sone rescuers. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<>();
160 /** All known Sones. */
161 private final Set<String> knownSones = new HashSet<>();
163 /** The post database. */
164 private final Database database;
166 /** Trusted identities, sorted by own identities. */
167 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
169 /** All temporary images. */
170 private final Map<String, TemporaryImage> temporaryImages = new HashMap<>();
172 /** Ticker for threads that mark own elements as known. */
173 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
175 /** The time the configuration was last touched. */
176 private volatile long lastConfigurationUpdate;
178 private final MetricRegistry metricRegistry;
181 * Creates a new core.
183 * @param configuration
184 * The configuration of the core
185 * @param freenetInterface
186 * The freenet interface
187 * @param identityManager
188 * The identity manager
189 * @param webOfTrustUpdater
190 * The WebOfTrust updater
197 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database, MetricRegistry metricRegistry) {
199 this.configuration = configuration;
200 this.freenetInterface = freenetInterface;
201 this.identityManager = identityManager;
202 this.soneDownloader = soneDownloader;
203 this.imageInserter = imageInserter;
204 this.updateChecker = updateChecker;
205 this.webOfTrustUpdater = webOfTrustUpdater;
206 this.eventBus = eventBus;
207 this.database = database;
208 this.metricRegistry = metricRegistry;
209 preferences = new Preferences(eventBus);
217 * Returns the time Sone was started.
219 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
221 public long getStartupTime() {
226 public boolean getDebug() {
230 public void setDebug() {
232 eventBus.post(new DebugActivatedEvent());
236 * Returns the options used by the core.
238 * @return The options of the core
240 public Preferences getPreferences() {
245 * Returns the identity manager used by the core.
247 * @return The identity manager
249 public IdentityManager getIdentityManager() {
250 return identityManager;
254 * Returns the update checker.
256 * @return The update checker
258 public UpdateChecker getUpdateChecker() {
259 return updateChecker;
263 * Returns the Sone rescuer for the given local Sone.
266 * The local Sone to get the rescuer for
267 * @return The Sone rescuer for the given Sone
269 public SoneRescuer getSoneRescuer(Sone sone) {
270 checkNotNull(sone, "sone must not be null");
271 checkArgument(sone.isLocal(), "sone must be local");
272 synchronized (soneRescuers) {
273 SoneRescuer soneRescuer = soneRescuers.get(sone);
274 if (soneRescuer == null) {
275 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
276 soneRescuers.put(sone, soneRescuer);
284 * Returns whether the given Sone is currently locked.
288 * @return {@code true} if the Sone is locked, {@code false} if it is not
290 public boolean isLocked(Sone sone) {
291 synchronized (lockedSones) {
292 return lockedSones.contains(sone);
296 public SoneBuilder soneBuilder() {
297 return database.newSoneBuilder();
305 public Collection<Sone> getSones() {
306 return database.getSones();
311 public Function1<String, Sone> getSoneLoader() {
312 return database.getSoneLoader();
316 * Returns the Sone with the given ID, regardless whether it’s local or
320 * The ID of the Sone to get
321 * @return The Sone with the given ID, or {@code null} if there is no such
326 public Sone getSone(@Nonnull String id) {
327 return database.getSone(id);
334 public Collection<Sone> getLocalSones() {
335 return database.getLocalSones();
339 * Returns the local Sone with the given ID, optionally creating a new Sone.
343 * @return The Sone with the given ID, or {@code null}
345 public Sone getLocalSone(String id) {
346 Sone sone = database.getSone(id);
347 if ((sone != null) && sone.isLocal()) {
357 public Collection<Sone> getRemoteSones() {
358 return database.getRemoteSones();
362 * Returns the remote Sone with the given ID.
366 * The ID of the remote Sone to get
367 * @return The Sone with the given ID
369 public Sone getRemoteSone(String id) {
370 return database.getSone(id);
374 * Returns whether the given Sone has been modified.
377 * The Sone to check for modifications
378 * @return {@code true} if a modification has been detected in the Sone,
379 * {@code false} otherwise
381 public boolean isModifiedSone(Sone sone) {
382 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
386 * Returns a post builder.
388 * @return A new post builder
390 public PostBuilder postBuilder() {
391 return database.newPostBuilder();
396 public Post getPost(@Nonnull String postId) {
397 return database.getPost(postId);
404 public Collection<Post> getPosts(String soneId) {
405 return database.getPosts(soneId);
412 public Collection<Post> getDirectedPosts(final String recipientId) {
413 checkNotNull(recipientId, "recipient must not be null");
414 return database.getDirectedPosts(recipientId);
418 * Returns a post reply builder.
420 * @return A new post reply builder
422 public PostReplyBuilder postReplyBuilder() {
423 return database.newPostReplyBuilder();
431 public PostReply getPostReply(String replyId) {
432 return database.getPostReply(replyId);
439 public List<PostReply> getReplies(final String postId) {
440 return database.getReplies(postId);
444 * Returns all Sones that have liked the given post.
447 * The post to get the liking Sones for
448 * @return The Sones that like the given post
450 public Set<Sone> getLikes(Post post) {
451 Set<Sone> sones = new HashSet<>();
452 for (Sone sone : getSones()) {
453 if (sone.getLikedPostIds().contains(post.getId())) {
461 * Returns all Sones that have liked the given reply.
464 * The reply to get the liking Sones for
465 * @return The Sones that like the given reply
467 public Set<Sone> getLikes(PostReply reply) {
468 Set<Sone> sones = new HashSet<>();
469 for (Sone sone : getSones()) {
470 if (sone.getLikedReplyIds().contains(reply.getId())) {
478 * Returns whether the given post is bookmarked.
482 * @return {@code true} if the given post is bookmarked, {@code false}
485 public boolean isBookmarked(Post post) {
486 return database.isPostBookmarked(post);
490 * Returns all currently known bookmarked posts.
492 * @return All bookmarked posts
494 public Set<Post> getBookmarkedPosts() {
495 return database.getBookmarkedPosts();
498 public AlbumBuilder albumBuilder() {
499 return database.newAlbumBuilder();
503 * Returns the album with the given ID, optionally creating a new album if
504 * an album with the given ID can not be found.
507 * The ID of the album
508 * @return The album with the given ID, or {@code null} if no album with the
512 public Album getAlbum(@Nonnull String albumId) {
513 return database.getAlbum(albumId);
516 public ImageBuilder imageBuilder() {
517 return database.newImageBuilder();
521 * Returns the image with the given ID, creating it if necessary.
524 * The ID of the image
525 * @return The image with the given ID
528 public Image getImage(String imageId) {
529 return getImage(imageId, true);
533 * Returns the image with the given ID, optionally creating it if it does
537 * The ID of the image
539 * {@code true} to create an image if none exists with the given
541 * @return The image with the given ID, or {@code null} if none exists and
545 public Image getImage(String imageId, boolean create) {
546 Image image = database.getImage(imageId);
553 Image newImage = database.newImageBuilder().withId(imageId).build();
554 database.storeImage(newImage);
559 * Returns the temporary image with the given ID.
562 * The ID of the temporary image
563 * @return The temporary image, or {@code null} if there is no temporary
564 * image with the given ID
566 public TemporaryImage getTemporaryImage(String imageId) {
567 synchronized (temporaryImages) {
568 return temporaryImages.get(imageId);
577 * Locks the given Sone. A locked Sone will not be inserted by
578 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
584 public void lockSone(Sone sone) {
585 synchronized (lockedSones) {
586 if (lockedSones.add(sone)) {
587 eventBus.post(new SoneLockedEvent(sone));
593 * Unlocks the given Sone.
595 * @see #lockSone(Sone)
599 public void unlockSone(Sone sone) {
600 synchronized (lockedSones) {
601 if (lockedSones.remove(sone)) {
602 eventBus.post(new SoneUnlockedEvent(sone));
608 * Adds a local Sone from the given own identity.
611 * The own identity to create a Sone from
612 * @return The added (or already existing) Sone
614 public Sone addLocalSone(OwnIdentity ownIdentity) {
615 if (ownIdentity == null) {
616 logger.log(Level.WARNING, "Given OwnIdentity is null!");
619 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
620 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
621 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
622 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
623 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
625 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, metricRegistry, ownIdentity.getId());
626 soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
627 eventBus.register(soneInserter);
628 synchronized (soneInserters) {
629 soneInserters.put(sone, soneInserter);
632 database.storeSone(sone);
633 sone.setStatus(SoneStatus.idle);
634 soneInserter.start();
639 * Creates a new Sone for the given own identity.
642 * The own identity to create a Sone for
643 * @return The created Sone
645 public Sone createSone(OwnIdentity ownIdentity) {
646 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
647 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
650 Sone sone = addLocalSone(ownIdentity);
652 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
653 touchConfiguration();
658 * Adds the Sone of the given identity.
661 * The identity whose Sone to add
662 * @return The added or already existing Sone
664 public Sone addRemoteSone(Identity identity) {
665 if (identity == null) {
666 logger.log(Level.WARNING, "Given Identity is null!");
669 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
670 long latestEdition = fromNullable(tryParse(property)).or(0L);
671 Sone existingSone = getSone(identity.getId());
672 if ((existingSone != null )&& existingSone.isLocal()) {
675 boolean newSone = existingSone == null;
676 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
677 sone.setLatestEdition(latestEdition);
679 synchronized (knownSones) {
680 newSone = !knownSones.contains(sone.getId());
682 sone.setKnown(!newSone);
684 eventBus.post(new NewSoneFoundEvent(sone));
685 for (Sone localSone : getLocalSones()) {
686 if (localSone.getOptions().isAutoFollow()) {
687 followSone(localSone, sone.getId());
692 database.storeSone(sone);
693 soneDownloader.addSone(sone);
694 soneDownloaders.execute(soneDownloader.fetchSoneAsUskAction(sone));
699 * Lets the given local Sone follow the Sone with the given ID.
702 * The local Sone that should follow another Sone
704 * The ID of the Sone to follow
706 public void followSone(Sone sone, String soneId) {
707 checkNotNull(sone, "sone must not be null");
708 checkNotNull(soneId, "soneId must not be null");
709 database.addFriend(sone, soneId);
710 @SuppressWarnings("ConstantConditions") // we just followed, this can’t be null.
711 long now = database.getFollowingTime(soneId);
712 Sone followedSone = getSone(soneId);
713 if (followedSone == null) {
716 for (Post post : followedSone.getPosts()) {
717 if (post.getTime() < now) {
721 for (PostReply reply : followedSone.getReplies()) {
722 if (reply.getTime() < now) {
723 markReplyKnown(reply);
726 touchConfiguration();
730 * Lets the given local Sone unfollow the Sone with the given ID.
733 * The local Sone that should unfollow another Sone
735 * The ID of the Sone being unfollowed
737 public void unfollowSone(Sone sone, String soneId) {
738 checkNotNull(sone, "sone must not be null");
739 checkNotNull(soneId, "soneId must not be null");
740 database.removeFriend(sone, soneId);
741 touchConfiguration();
745 * Sets the trust value of the given origin Sone for the target Sone.
752 * The trust value (from {@code -100} to {@code 100})
754 public void setTrust(Sone origin, Sone target, int trustValue) {
755 checkNotNull(origin, "origin must not be null");
756 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
757 checkNotNull(target, "target must not be null");
758 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
759 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
763 * Removes any trust assignment for the given target Sone.
770 public void removeTrust(Sone origin, Sone target) {
771 checkNotNull(origin, "origin must not be null");
772 checkNotNull(target, "target must not be null");
773 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
774 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
778 * Assigns the configured positive trust value for the given target.
785 public void trustSone(Sone origin, Sone target) {
786 setTrust(origin, target, preferences.getPositiveTrust());
790 * Assigns the configured negative trust value for the given target.
797 public void distrustSone(Sone origin, Sone target) {
798 setTrust(origin, target, preferences.getNegativeTrust());
802 * Removes the trust assignment for the given target.
809 public void untrustSone(Sone origin, Sone target) {
810 removeTrust(origin, target);
814 * Updates the stored Sone with the given Sone.
819 public void updateSone(Sone sone) {
820 updateSone(sone, false);
824 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
825 * {@code true}, an older Sone than the current Sone can be given to restore
830 * @param soneRescueMode
831 * {@code true} if the stored Sone should be updated regardless
832 * of the age of the given Sone
834 public void updateSone(final Sone sone, boolean soneRescueMode) {
835 Sone storedSone = getSone(sone.getId());
836 if (storedSone != null) {
837 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
838 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
841 List<Object> events =
842 collectEventsForChangesInSone(storedSone, sone);
843 database.storeSone(sone);
844 for (Object event : events) {
845 eventBus.post(event);
847 sone.setOptions(storedSone.getOptions());
848 sone.setKnown(storedSone.isKnown());
849 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
850 if (sone.isLocal()) {
851 touchConfiguration();
856 private List<Object> collectEventsForChangesInSone(Sone oldSone, Sone newSone) {
857 List<Object> events = new ArrayList<>();
858 SoneComparison soneComparison = new SoneComparison(oldSone, newSone);
859 for (Post newPost : soneComparison.getNewPosts()) {
860 if (newPost.getSone().equals(newSone)) {
861 newPost.setKnown(true);
862 } else if (newPost.getTime() < database.getFollowingTime(newSone.getId())) {
863 newPost.setKnown(true);
864 } else if (!newPost.isKnown()) {
865 events.add(new NewPostFoundEvent(newPost));
868 for (Post post : soneComparison.getRemovedPosts()) {
869 events.add(new PostRemovedEvent(post));
871 for (PostReply postReply : soneComparison.getNewPostReplies()) {
872 if (postReply.getSone().equals(newSone)) {
873 postReply.setKnown(true);
874 } else if (postReply.getTime() < database.getFollowingTime(newSone.getId())) {
875 postReply.setKnown(true);
876 } else if (!postReply.isKnown()) {
877 events.add(new NewPostReplyFoundEvent(postReply));
880 for (PostReply postReply : soneComparison.getRemovedPostReplies()) {
881 events.add(new PostReplyRemovedEvent(postReply));
887 * Deletes the given Sone. This will remove the Sone from the
888 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
889 * remove the context from its identity.
894 public void deleteSone(Sone sone) {
895 if (!(sone.getIdentity() instanceof OwnIdentity)) {
896 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
899 if (!getLocalSones().contains(sone)) {
900 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
903 SoneInserter soneInserter = soneInserters.remove(sone);
905 database.removeSone(sone);
906 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
907 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
909 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
910 } catch (ConfigurationException ce1) {
911 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
916 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
917 * known} before, a {@link MarkSoneKnownEvent} is fired.
920 * The Sone to mark as known
922 public void markSoneKnown(Sone sone) {
923 if (!sone.isKnown()) {
925 synchronized (knownSones) {
926 knownSones.add(sone.getId());
928 eventBus.post(new MarkSoneKnownEvent(sone));
929 touchConfiguration();
934 * Loads and updates the given Sone from the configuration. If any error is
935 * encountered, loading is aborted and the given Sone is not changed.
938 * The Sone to load and update
940 public void loadSone(Sone sone) {
941 if (!sone.isLocal()) {
942 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
945 logger.info(String.format("Loading local Sone: %s", sone));
948 String sonePrefix = "Sone/" + sone.getId();
949 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
950 if (soneTime == null) {
951 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
954 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
957 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
958 Profile profile = configurationSoneParser.parseProfile();
961 Collection<Post> posts;
963 posts = configurationSoneParser.parsePosts(database);
964 } catch (InvalidPostFound ipf) {
965 logger.log(Level.WARNING, "Invalid post found, aborting load!");
970 Collection<PostReply> replies;
972 replies = configurationSoneParser.parsePostReplies(database);
973 } catch (InvalidPostReplyFound iprf) {
974 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
978 /* load post likes. */
979 Set<String> likedPostIds =
980 configurationSoneParser.parseLikedPostIds();
982 /* load reply likes. */
983 Set<String> likedReplyIds =
984 configurationSoneParser.parseLikedPostReplyIds();
987 List<Album> topLevelAlbums;
990 configurationSoneParser.parseTopLevelAlbums(database);
991 } catch (InvalidAlbumFound iaf) {
992 logger.log(Level.WARNING, "Invalid album found, aborting load!");
994 } catch (InvalidParentAlbumFound ipaf) {
995 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
996 ipaf.getAlbumParentId()));
1002 configurationSoneParser.parseImages(database);
1003 } catch (InvalidImageFound iif) {
1004 logger.log(WARNING, "Invalid image found, aborting load!");
1006 } catch (InvalidParentAlbumFound ipaf) {
1007 logger.log(Level.WARNING,
1008 format("Invalid album image (%s) encountered, aborting load!",
1009 ipaf.getAlbumParentId()));
1014 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1015 if (avatarId != null) {
1016 final Map<String, Image> images =
1017 configurationSoneParser.getImages();
1018 profile.setAvatar(images.get(avatarId));
1022 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1023 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1024 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1025 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1026 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1027 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1028 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1030 /* if we’re still here, Sone was loaded successfully. */
1031 synchronized (sone) {
1032 sone.setTime(soneTime);
1033 sone.setProfile(profile);
1034 sone.setPosts(posts);
1035 sone.setReplies(replies);
1036 sone.setLikePostIds(likedPostIds);
1037 sone.setLikeReplyIds(likedReplyIds);
1038 for (Album album : sone.getRootAlbum().getAlbums()) {
1039 sone.getRootAlbum().removeAlbum(album);
1041 for (Album album : topLevelAlbums) {
1042 sone.getRootAlbum().addAlbum(album);
1044 synchronized (soneInserters) {
1045 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1048 for (Post post : posts) {
1049 post.setKnown(true);
1051 for (PostReply reply : replies) {
1052 reply.setKnown(true);
1055 logger.info(String.format("Sone loaded successfully: %s", sone));
1059 * Creates a new post.
1062 * The Sone that creates the post
1064 * The recipient Sone, or {@code null} if this post does not have
1067 * The text of the post
1068 * @return The created post
1070 public Post createPost(Sone sone, @Nullable Sone recipient, String text) {
1071 checkNotNull(text, "text must not be null");
1072 checkArgument(text.trim().length() > 0, "text must not be empty");
1073 if (!sone.isLocal()) {
1074 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1077 PostBuilder postBuilder = database.newPostBuilder();
1078 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1079 if (recipient != null) {
1080 postBuilder.to(recipient.getId());
1082 final Post post = postBuilder.build();
1083 database.storePost(post);
1084 eventBus.post(new NewPostFoundEvent(post));
1086 touchConfiguration();
1087 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1092 * Deletes the given post.
1095 * The post to delete
1097 public void deletePost(Post post) {
1098 if (!post.getSone().isLocal()) {
1099 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1102 database.removePost(post);
1103 eventBus.post(new PostRemovedEvent(post));
1104 markPostKnown(post);
1105 touchConfiguration();
1109 * Marks the given post as known, if it is currently not a known post
1110 * (according to {@link Post#isKnown()}).
1113 * The post to mark as known
1115 public void markPostKnown(Post post) {
1116 post.setKnown(true);
1117 eventBus.post(new MarkPostKnownEvent(post));
1118 touchConfiguration();
1119 for (PostReply reply : getReplies(post.getId())) {
1120 markReplyKnown(reply);
1124 public void bookmarkPost(Post post) {
1125 database.bookmarkPost(post);
1129 * Removes the given post from the bookmarks.
1132 * The post to unbookmark
1134 public void unbookmarkPost(Post post) {
1135 database.unbookmarkPost(post);
1139 * Creates a new reply.
1142 * The Sone that creates the reply
1144 * The post that this reply refers to
1146 * The text of the reply
1147 * @return The created reply
1149 public PostReply createReply(Sone sone, Post post, String text) {
1150 checkNotNull(text, "text must not be null");
1151 checkArgument(text.trim().length() > 0, "text must not be empty");
1152 if (!sone.isLocal()) {
1153 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1156 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1157 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1158 final PostReply reply = postReplyBuilder.build();
1159 database.storePostReply(reply);
1160 eventBus.post(new NewPostReplyFoundEvent(reply));
1161 sone.addReply(reply);
1162 touchConfiguration();
1163 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1168 * Deletes the given reply.
1171 * The reply to delete
1173 public void deleteReply(PostReply reply) {
1174 Sone sone = reply.getSone();
1175 if (!sone.isLocal()) {
1176 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1179 database.removePostReply(reply);
1180 markReplyKnown(reply);
1181 sone.removeReply(reply);
1182 touchConfiguration();
1186 * Marks the given reply as known, if it is currently not a known reply
1187 * (according to {@link Reply#isKnown()}).
1190 * The reply to mark as known
1192 public void markReplyKnown(PostReply reply) {
1193 boolean previouslyKnown = reply.isKnown();
1194 reply.setKnown(true);
1195 eventBus.post(new MarkPostReplyKnownEvent(reply));
1196 if (!previouslyKnown) {
1197 touchConfiguration();
1202 * Creates a new album for the given Sone.
1205 * The Sone to create the album for
1207 * The parent of the album (may be {@code null} to create a
1209 * @return The new album
1211 public Album createAlbum(Sone sone, Album parent) {
1212 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1213 database.storeAlbum(album);
1214 parent.addAlbum(album);
1219 * Deletes the given album. The owner of the album has to be a local Sone,
1220 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1223 * The album to remove
1225 public void deleteAlbum(Album album) {
1226 checkNotNull(album, "album must not be null");
1227 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1228 if (!album.isEmpty()) {
1231 album.getParent().removeAlbum(album);
1232 database.removeAlbum(album);
1233 touchConfiguration();
1237 * Creates a new image.
1240 * The Sone creating the image
1242 * The album the image will be inserted into
1243 * @param temporaryImage
1244 * The temporary image to create the image from
1245 * @return The newly created image
1247 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1248 checkNotNull(sone, "sone must not be null");
1249 checkNotNull(album, "album must not be null");
1250 checkNotNull(temporaryImage, "temporaryImage must not be null");
1251 checkArgument(sone.isLocal(), "sone must be a local Sone");
1252 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1253 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1254 album.addImage(image);
1255 database.storeImage(image);
1256 imageInserter.insertImage(temporaryImage, image);
1261 * Deletes the given image. This method will also delete a matching
1264 * @see #deleteTemporaryImage(String)
1266 * The image to delete
1268 public void deleteImage(Image image) {
1269 checkNotNull(image, "image must not be null");
1270 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1271 deleteTemporaryImage(image.getId());
1272 image.getAlbum().removeImage(image);
1273 database.removeImage(image);
1274 touchConfiguration();
1278 * Creates a new temporary image.
1281 * The MIME type of the temporary image
1283 * The encoded data of the image
1284 * @return The temporary image
1286 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1287 TemporaryImage temporaryImage = new TemporaryImage();
1288 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1289 synchronized (temporaryImages) {
1290 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1292 return temporaryImage;
1296 * Deletes the temporary image with the given ID.
1299 * The ID of the temporary image to delete
1301 public void deleteTemporaryImage(String imageId) {
1302 checkNotNull(imageId, "imageId must not be null");
1303 synchronized (temporaryImages) {
1304 temporaryImages.remove(imageId);
1306 Image image = getImage(imageId, false);
1307 if (image != null) {
1308 imageInserter.cancelImageInsert(image);
1313 * Notifies the core that the configuration, either of the core or of a
1314 * single local Sone, has changed, and that the configuration should be
1317 public void touchConfiguration() {
1318 lastConfigurationUpdate = System.currentTimeMillis();
1329 public void serviceStart() {
1330 loadConfiguration();
1331 updateChecker.start();
1332 identityManager.start();
1333 webOfTrustUpdater.init();
1334 webOfTrustUpdater.start();
1335 database.startAsync();
1342 public void serviceRun() {
1343 long lastSaved = System.currentTimeMillis();
1344 while (!shouldStop()) {
1346 long now = System.currentTimeMillis();
1347 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1348 for (Sone localSone : getLocalSones()) {
1349 saveSone(localSone);
1351 saveConfiguration();
1361 public void serviceStop() {
1362 localElementTicker.shutdownNow();
1363 synchronized (soneInserters) {
1364 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1365 soneInserter.getValue().stop();
1366 saveSone(soneInserter.getKey());
1369 synchronized (soneRescuers) {
1370 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1374 saveConfiguration();
1375 database.stopAsync();
1376 webOfTrustUpdater.stop();
1377 updateChecker.stop();
1378 soneDownloader.stop();
1379 soneDownloaders.shutdown();
1380 identityManager.stop();
1388 * Saves the given Sone. This will persist all local settings for the given
1389 * Sone, such as the friends list and similar, private options.
1394 private synchronized void saveSone(Sone sone) {
1395 if (!sone.isLocal()) {
1396 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1399 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1400 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1404 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1406 /* save Sone into configuration. */
1407 String sonePrefix = "Sone/" + sone.getId();
1408 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1409 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1412 Profile profile = sone.getProfile();
1413 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1414 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1415 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1416 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1417 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1418 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1419 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1421 /* save profile fields. */
1422 int fieldCounter = 0;
1423 for (Field profileField : profile.getFields()) {
1424 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1425 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1426 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1428 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1431 int postCounter = 0;
1432 for (Post post : sone.getPosts()) {
1433 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1434 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1435 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1436 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1437 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1439 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1442 int replyCounter = 0;
1443 for (PostReply reply : sone.getReplies()) {
1444 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1445 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1446 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1447 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1448 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1450 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1452 /* save post likes. */
1453 int postLikeCounter = 0;
1454 for (String postId : sone.getLikedPostIds()) {
1455 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1457 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1459 /* save reply likes. */
1460 int replyLikeCounter = 0;
1461 for (String replyId : sone.getLikedReplyIds()) {
1462 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1464 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1466 /* save albums. first, collect in a flat structure, top-level first. */
1467 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1469 int albumCounter = 0;
1470 for (Album album : albums) {
1471 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1472 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1473 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1474 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1475 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1477 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1480 int imageCounter = 0;
1481 for (Album album : albums) {
1482 for (Image image : album.getImages()) {
1483 if (!image.isInserted()) {
1486 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1487 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1488 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1489 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1490 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1491 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1492 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1493 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1494 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1497 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1500 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1501 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1502 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1503 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1504 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1505 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1506 configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1508 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1510 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1511 } catch (ConfigurationException ce1) {
1512 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1517 * Saves the current options.
1519 private void saveConfiguration() {
1520 synchronized (configuration) {
1521 if (storingConfiguration) {
1522 logger.log(Level.FINE, "Already storing configuration…");
1525 storingConfiguration = true;
1528 /* store the options first. */
1530 preferences.saveTo(configuration);
1532 /* save known Sones. */
1533 int soneCounter = 0;
1534 synchronized (knownSones) {
1535 for (String knownSoneId : knownSones) {
1536 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1538 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1541 /* save known posts. */
1545 configuration.save();
1547 } catch (ConfigurationException ce1) {
1548 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1549 } catch (DatabaseException de1) {
1550 logger.log(Level.SEVERE, "Could not save database!", de1);
1552 synchronized (configuration) {
1553 storingConfiguration = false;
1559 * Loads the configuration.
1561 private void loadConfiguration() {
1562 new PreferencesLoader(preferences).loadFrom(configuration);
1564 /* load known Sones. */
1565 int soneCounter = 0;
1567 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1568 if (knownSoneId == null) {
1571 synchronized (knownSones) {
1572 knownSones.add(knownSoneId);
1578 * Notifies the core that a new {@link OwnIdentity} was added.
1580 * @param ownIdentityAddedEvent
1584 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1585 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1586 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1587 if (ownIdentity.hasContext("Sone")) {
1588 addLocalSone(ownIdentity);
1593 * Notifies the core that an {@link OwnIdentity} was removed.
1595 * @param ownIdentityRemovedEvent
1599 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1600 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1601 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1602 trustedIdentities.removeAll(ownIdentity);
1606 * Notifies the core that a new {@link Identity} was added.
1608 * @param identityAddedEvent
1612 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1613 Identity identity = identityAddedEvent.identity();
1614 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1615 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1616 addRemoteSone(identity);
1620 * Notifies the core that an {@link Identity} was updated.
1622 * @param identityUpdatedEvent
1626 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1627 Identity identity = identityUpdatedEvent.identity();
1628 final Sone sone = getRemoteSone(identity.getId());
1629 if (sone.isLocal()) {
1632 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1633 if (newLatestEdition != null) {
1634 Long parsedNewLatestEdition = tryParse(newLatestEdition);
1635 if (parsedNewLatestEdition != null) {
1636 sone.setLatestEdition(parsedNewLatestEdition);
1639 soneDownloader.addSone(sone);
1640 soneDownloaders.execute(soneDownloader.fetchSoneAsSskAction(sone));
1644 * Notifies the core that an {@link Identity} was removed.
1646 * @param identityRemovedEvent
1650 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1651 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1652 Identity identity = identityRemovedEvent.identity();
1653 trustedIdentities.remove(ownIdentity, identity);
1654 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1655 if (trustedIdentity.getKey().equals(ownIdentity)) {
1658 if (trustedIdentity.getValue().contains(identity)) {
1662 Sone sone = getSone(identity.getId());
1664 /* TODO - we don’t have the Sone anymore. should this happen? */
1667 for (PostReply postReply : sone.getReplies()) {
1668 eventBus.post(new PostReplyRemovedEvent(postReply));
1670 for (Post post : sone.getPosts()) {
1671 eventBus.post(new PostRemovedEvent(post));
1673 eventBus.post(new SoneRemovedEvent(sone));
1674 database.removeSone(sone);
1678 * Deletes the temporary image.
1680 * @param imageInsertFinishedEvent
1684 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1685 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.getImage(), imageInsertFinishedEvent.getResultingUri()));
1686 imageInsertFinishedEvent.getImage().modify().setKey(imageInsertFinishedEvent.getResultingUri().toString()).update();
1687 deleteTemporaryImage(imageInsertFinishedEvent.getImage().getId());
1688 touchConfiguration();
1692 class MarkPostKnown implements Runnable {
1694 private final Post post;
1696 public MarkPostKnown(Post post) {
1702 markPostKnown(post);
1708 class MarkReplyKnown implements Runnable {
1710 private final PostReply postReply;
1712 public MarkReplyKnown(PostReply postReply) {
1713 this.postReply = postReply;
1718 markReplyKnown(postReply);