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.base.Stopwatch;
92 import com.google.common.collect.FluentIterable;
93 import com.google.common.collect.HashMultimap;
94 import com.google.common.collect.Multimap;
95 import com.google.common.collect.Multimaps;
96 import com.google.common.eventbus.EventBus;
97 import com.google.common.eventbus.Subscribe;
98 import com.google.inject.Inject;
99 import com.google.inject.Singleton;
100 import kotlin.jvm.functions.Function1;
106 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
109 private static final Logger logger = getLogger(Core.class.getName());
111 /** The start time. */
112 private final long startupTime = System.currentTimeMillis();
114 private final AtomicBoolean debug = new AtomicBoolean(false);
116 /** The preferences. */
117 private final Preferences preferences;
119 /** The event bus. */
120 private final EventBus eventBus;
122 /** The configuration. */
123 private final Configuration configuration;
125 /** Whether we’re currently saving the configuration. */
126 private boolean storingConfiguration = false;
128 /** The identity manager. */
129 private final IdentityManager identityManager;
131 /** Interface to freenet. */
132 private final FreenetInterface freenetInterface;
134 /** The Sone downloader. */
135 private final SoneDownloader soneDownloader;
137 /** The image inserter. */
138 private final ImageInserter imageInserter;
140 /** Sone downloader thread-pool. */
141 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
143 /** The update checker. */
144 private final UpdateChecker updateChecker;
146 /** The trust updater. */
147 private final WebOfTrustUpdater webOfTrustUpdater;
149 /** Locked local Sones. */
150 /* synchronize on itself. */
151 private final Set<Sone> lockedSones = new HashSet<>();
153 /** Sone inserters. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneInserter> soneInserters = new HashMap<>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<>();
161 /** All known Sones. */
162 private final Set<String> knownSones = new HashSet<>();
164 /** The post database. */
165 private final Database database;
167 /** Trusted identities, sorted by own identities. */
168 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
170 /** All temporary images. */
171 private final Map<String, TemporaryImage> temporaryImages = new HashMap<>();
173 /** Ticker for threads that mark own elements as known. */
174 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
176 /** The time the configuration was last touched. */
177 private volatile long lastConfigurationUpdate;
179 private final MetricRegistry metricRegistry;
180 private final Histogram configurationSaveTimeHistogram;
183 * Creates a new core.
185 * @param configuration
186 * The configuration of the core
187 * @param freenetInterface
188 * The freenet interface
189 * @param identityManager
190 * The identity manager
191 * @param webOfTrustUpdater
192 * The WebOfTrust updater
199 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database, MetricRegistry metricRegistry) {
201 this.configuration = configuration;
202 this.freenetInterface = freenetInterface;
203 this.identityManager = identityManager;
204 this.soneDownloader = soneDownloader;
205 this.imageInserter = imageInserter;
206 this.updateChecker = updateChecker;
207 this.webOfTrustUpdater = webOfTrustUpdater;
208 this.eventBus = eventBus;
209 this.database = database;
210 this.metricRegistry = metricRegistry;
211 preferences = new Preferences(eventBus);
212 this.configurationSaveTimeHistogram = metricRegistry.histogram("configuration.save.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
220 * Returns the time Sone was started.
222 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
224 public long getStartupTime() {
229 public boolean getDebug() {
233 public void setDebug() {
235 eventBus.post(new DebugActivatedEvent());
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Returns the Sone rescuer for the given local Sone.
269 * The local Sone to get the rescuer for
270 * @return The Sone rescuer for the given Sone
272 public SoneRescuer getSoneRescuer(Sone sone) {
273 checkNotNull(sone, "sone must not be null");
274 checkArgument(sone.isLocal(), "sone must be local");
275 synchronized (soneRescuers) {
276 SoneRescuer soneRescuer = soneRescuers.get(sone);
277 if (soneRescuer == null) {
278 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
279 soneRescuers.put(sone, soneRescuer);
287 * Returns whether the given Sone is currently locked.
291 * @return {@code true} if the Sone is locked, {@code false} if it is not
293 public boolean isLocked(Sone sone) {
294 synchronized (lockedSones) {
295 return lockedSones.contains(sone);
299 public SoneBuilder soneBuilder() {
300 return database.newSoneBuilder();
308 public Collection<Sone> getSones() {
309 return database.getSones();
314 public Function1<String, Sone> getSoneLoader() {
315 return database.getSoneLoader();
319 * Returns the Sone with the given ID, regardless whether it’s local or
323 * The ID of the Sone to get
324 * @return The Sone with the given ID, or {@code null} if there is no such
329 public Sone getSone(@Nonnull String id) {
330 return database.getSone(id);
337 public Collection<Sone> getLocalSones() {
338 return database.getLocalSones();
342 * Returns the local Sone with the given ID, optionally creating a new Sone.
346 * @return The Sone with the given ID, or {@code null}
348 public Sone getLocalSone(String id) {
349 Sone sone = database.getSone(id);
350 if ((sone != null) && sone.isLocal()) {
360 public Collection<Sone> getRemoteSones() {
361 return database.getRemoteSones();
365 * Returns the remote Sone with the given ID.
369 * The ID of the remote Sone to get
370 * @return The Sone with the given ID
372 public Sone getRemoteSone(String id) {
373 return database.getSone(id);
377 * Returns whether the given Sone has been modified.
380 * The Sone to check for modifications
381 * @return {@code true} if a modification has been detected in the Sone,
382 * {@code false} otherwise
384 public boolean isModifiedSone(Sone sone) {
385 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
389 * Returns a post builder.
391 * @return A new post builder
393 public PostBuilder postBuilder() {
394 return database.newPostBuilder();
399 public Post getPost(@Nonnull String postId) {
400 return database.getPost(postId);
407 public Collection<Post> getPosts(String soneId) {
408 return database.getPosts(soneId);
415 public Collection<Post> getDirectedPosts(final String recipientId) {
416 checkNotNull(recipientId, "recipient must not be null");
417 return database.getDirectedPosts(recipientId);
421 * Returns a post reply builder.
423 * @return A new post reply builder
425 public PostReplyBuilder postReplyBuilder() {
426 return database.newPostReplyBuilder();
434 public PostReply getPostReply(String replyId) {
435 return database.getPostReply(replyId);
442 public List<PostReply> getReplies(final String postId) {
443 return database.getReplies(postId);
447 * Returns all Sones that have liked the given post.
450 * The post to get the liking Sones for
451 * @return The Sones that like the given post
453 public Set<Sone> getLikes(Post post) {
454 Set<Sone> sones = new HashSet<>();
455 for (Sone sone : getSones()) {
456 if (sone.getLikedPostIds().contains(post.getId())) {
464 * Returns all Sones that have liked the given reply.
467 * The reply to get the liking Sones for
468 * @return The Sones that like the given reply
470 public Set<Sone> getLikes(PostReply reply) {
471 Set<Sone> sones = new HashSet<>();
472 for (Sone sone : getSones()) {
473 if (sone.getLikedReplyIds().contains(reply.getId())) {
481 * Returns whether the given post is bookmarked.
485 * @return {@code true} if the given post is bookmarked, {@code false}
488 public boolean isBookmarked(Post post) {
489 return database.isPostBookmarked(post);
493 * Returns all currently known bookmarked posts.
495 * @return All bookmarked posts
497 public Set<Post> getBookmarkedPosts() {
498 return database.getBookmarkedPosts();
501 public AlbumBuilder albumBuilder() {
502 return database.newAlbumBuilder();
506 * Returns the album with the given ID, optionally creating a new album if
507 * an album with the given ID can not be found.
510 * The ID of the album
511 * @return The album with the given ID, or {@code null} if no album with the
515 public Album getAlbum(@Nonnull String albumId) {
516 return database.getAlbum(albumId);
519 public ImageBuilder imageBuilder() {
520 return database.newImageBuilder();
524 * Returns the image with the given ID, creating it if necessary.
527 * The ID of the image
528 * @return The image with the given ID
531 public Image getImage(String imageId) {
532 return getImage(imageId, true);
536 * Returns the image with the given ID, optionally creating it if it does
540 * The ID of the image
542 * {@code true} to create an image if none exists with the given
544 * @return The image with the given ID, or {@code null} if none exists and
548 public Image getImage(String imageId, boolean create) {
549 Image image = database.getImage(imageId);
556 Image newImage = database.newImageBuilder().withId(imageId).build();
557 database.storeImage(newImage);
562 * Returns the temporary image with the given ID.
565 * The ID of the temporary image
566 * @return The temporary image, or {@code null} if there is no temporary
567 * image with the given ID
569 public TemporaryImage getTemporaryImage(String imageId) {
570 synchronized (temporaryImages) {
571 return temporaryImages.get(imageId);
580 * Locks the given Sone. A locked Sone will not be inserted by
581 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
587 public void lockSone(Sone sone) {
588 synchronized (lockedSones) {
589 if (lockedSones.add(sone)) {
590 eventBus.post(new SoneLockedEvent(sone));
596 * Unlocks the given Sone.
598 * @see #lockSone(Sone)
602 public void unlockSone(Sone sone) {
603 synchronized (lockedSones) {
604 if (lockedSones.remove(sone)) {
605 eventBus.post(new SoneUnlockedEvent(sone));
611 * Adds a local Sone from the given own identity.
614 * The own identity to create a Sone from
615 * @return The added (or already existing) Sone
617 public Sone addLocalSone(OwnIdentity ownIdentity) {
618 if (ownIdentity == null) {
619 logger.log(Level.WARNING, "Given OwnIdentity is null!");
622 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
623 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
624 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
625 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
626 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
628 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, metricRegistry, ownIdentity.getId());
629 soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
630 eventBus.register(soneInserter);
631 synchronized (soneInserters) {
632 soneInserters.put(sone, soneInserter);
635 database.storeSone(sone);
636 sone.setStatus(SoneStatus.idle);
637 if (sone.getPosts().isEmpty() && sone.getReplies().isEmpty()) {
641 soneInserter.start();
646 * Creates a new Sone for the given own identity.
649 * The own identity to create a Sone for
650 * @return The created Sone
652 public Sone createSone(OwnIdentity ownIdentity) {
653 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
654 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
657 Sone sone = addLocalSone(ownIdentity);
659 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
660 touchConfiguration();
665 * Adds the Sone of the given identity.
668 * The identity whose Sone to add
669 * @return The added or already existing Sone
671 public Sone addRemoteSone(Identity identity) {
672 if (identity == null) {
673 logger.log(Level.WARNING, "Given Identity is null!");
676 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
677 long latestEdition = fromNullable(tryParse(property)).or(0L);
678 Sone existingSone = getSone(identity.getId());
679 if ((existingSone != null )&& existingSone.isLocal()) {
682 boolean newSone = existingSone == null;
683 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
684 sone.setLatestEdition(latestEdition);
686 synchronized (knownSones) {
687 newSone = !knownSones.contains(sone.getId());
689 sone.setKnown(!newSone);
691 eventBus.post(new NewSoneFoundEvent(sone));
692 for (Sone localSone : getLocalSones()) {
693 if (localSone.getOptions().isAutoFollow()) {
694 followSone(localSone, sone.getId());
699 database.storeSone(sone);
700 soneDownloader.addSone(sone);
701 soneDownloaders.execute(soneDownloader.fetchSoneAsUskAction(sone));
706 * Lets the given local Sone follow the Sone with the given ID.
709 * The local Sone that should follow another Sone
711 * The ID of the Sone to follow
713 public void followSone(Sone sone, String soneId) {
714 checkNotNull(sone, "sone must not be null");
715 checkNotNull(soneId, "soneId must not be null");
716 database.addFriend(sone, soneId);
717 @SuppressWarnings("ConstantConditions") // we just followed, this can’t be null.
718 long now = database.getFollowingTime(soneId);
719 Sone followedSone = getSone(soneId);
720 if (followedSone == null) {
723 for (Post post : followedSone.getPosts()) {
724 if (post.getTime() < now) {
728 for (PostReply reply : followedSone.getReplies()) {
729 if (reply.getTime() < now) {
730 markReplyKnown(reply);
733 touchConfiguration();
737 * Lets the given local Sone unfollow the Sone with the given ID.
740 * The local Sone that should unfollow another Sone
742 * The ID of the Sone being unfollowed
744 public void unfollowSone(Sone sone, String soneId) {
745 checkNotNull(sone, "sone must not be null");
746 checkNotNull(soneId, "soneId must not be null");
747 database.removeFriend(sone, soneId);
748 touchConfiguration();
752 * Sets the trust value of the given origin Sone for the target Sone.
759 * The trust value (from {@code -100} to {@code 100})
761 public void setTrust(Sone origin, Sone target, int trustValue) {
762 checkNotNull(origin, "origin must not be null");
763 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
764 checkNotNull(target, "target must not be null");
765 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
766 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
770 * Removes any trust assignment for the given target Sone.
777 public void removeTrust(Sone origin, Sone target) {
778 checkNotNull(origin, "origin must not be null");
779 checkNotNull(target, "target must not be null");
780 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
781 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
785 * Assigns the configured positive trust value for the given target.
792 public void trustSone(Sone origin, Sone target) {
793 setTrust(origin, target, preferences.getPositiveTrust());
797 * Assigns the configured negative trust value for the given target.
804 public void distrustSone(Sone origin, Sone target) {
805 setTrust(origin, target, preferences.getNegativeTrust());
809 * Removes the trust assignment for the given target.
816 public void untrustSone(Sone origin, Sone target) {
817 removeTrust(origin, target);
821 * Updates the stored Sone with the given Sone.
826 public void updateSone(Sone sone) {
827 updateSone(sone, false);
831 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
832 * {@code true}, an older Sone than the current Sone can be given to restore
837 * @param soneRescueMode
838 * {@code true} if the stored Sone should be updated regardless
839 * of the age of the given Sone
841 public void updateSone(final Sone sone, boolean soneRescueMode) {
842 Sone storedSone = getSone(sone.getId());
843 if (storedSone != null) {
844 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
845 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
848 List<Object> events =
849 collectEventsForChangesInSone(storedSone, sone);
850 database.storeSone(sone);
851 for (Object event : events) {
852 eventBus.post(event);
854 sone.setOptions(storedSone.getOptions());
855 sone.setKnown(storedSone.isKnown());
856 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
857 if (sone.isLocal()) {
858 touchConfiguration();
863 private List<Object> collectEventsForChangesInSone(Sone oldSone, Sone newSone) {
864 List<Object> events = new ArrayList<>();
865 SoneComparison soneComparison = new SoneComparison(oldSone, newSone);
866 for (Post newPost : soneComparison.getNewPosts()) {
867 if (newPost.getSone().equals(newSone)) {
868 newPost.setKnown(true);
869 } else if (newPost.getTime() < database.getFollowingTime(newSone.getId())) {
870 newPost.setKnown(true);
871 } else if (!newPost.isKnown()) {
872 events.add(new NewPostFoundEvent(newPost));
875 for (Post post : soneComparison.getRemovedPosts()) {
876 events.add(new PostRemovedEvent(post));
878 for (PostReply postReply : soneComparison.getNewPostReplies()) {
879 if (postReply.getSone().equals(newSone)) {
880 postReply.setKnown(true);
881 } else if (postReply.getTime() < database.getFollowingTime(newSone.getId())) {
882 postReply.setKnown(true);
883 } else if (!postReply.isKnown()) {
884 events.add(new NewPostReplyFoundEvent(postReply));
887 for (PostReply postReply : soneComparison.getRemovedPostReplies()) {
888 events.add(new PostReplyRemovedEvent(postReply));
894 * Deletes the given Sone. This will remove the Sone from the
895 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
896 * remove the context from its identity.
901 public void deleteSone(Sone sone) {
902 if (!(sone.getIdentity() instanceof OwnIdentity)) {
903 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
906 if (!getLocalSones().contains(sone)) {
907 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
910 SoneInserter soneInserter = soneInserters.remove(sone);
912 database.removeSone(sone);
913 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
914 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
916 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
917 } catch (ConfigurationException ce1) {
918 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
923 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
924 * known} before, a {@link MarkSoneKnownEvent} is fired.
927 * The Sone to mark as known
929 public void markSoneKnown(Sone sone) {
930 if (!sone.isKnown()) {
932 synchronized (knownSones) {
933 knownSones.add(sone.getId());
935 eventBus.post(new MarkSoneKnownEvent(sone));
936 touchConfiguration();
941 * Loads and updates the given Sone from the configuration. If any error is
942 * encountered, loading is aborted and the given Sone is not changed.
945 * The Sone to load and update
947 public void loadSone(Sone sone) {
948 if (!sone.isLocal()) {
949 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
952 logger.info(String.format("Loading local Sone: %s", sone));
955 String sonePrefix = "Sone/" + sone.getId();
956 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
957 if (soneTime == null) {
958 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
961 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
964 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
965 Profile profile = configurationSoneParser.parseProfile();
968 Collection<Post> posts;
970 posts = configurationSoneParser.parsePosts(database);
971 } catch (InvalidPostFound ipf) {
972 logger.log(Level.WARNING, "Invalid post found, aborting load!");
977 Collection<PostReply> replies;
979 replies = configurationSoneParser.parsePostReplies(database);
980 } catch (InvalidPostReplyFound iprf) {
981 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
985 /* load post likes. */
986 Set<String> likedPostIds =
987 configurationSoneParser.parseLikedPostIds();
989 /* load reply likes. */
990 Set<String> likedReplyIds =
991 configurationSoneParser.parseLikedPostReplyIds();
994 List<Album> topLevelAlbums;
997 configurationSoneParser.parseTopLevelAlbums(database);
998 } catch (InvalidAlbumFound iaf) {
999 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1001 } catch (InvalidParentAlbumFound ipaf) {
1002 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1003 ipaf.getAlbumParentId()));
1009 configurationSoneParser.parseImages(database);
1010 } catch (InvalidImageFound iif) {
1011 logger.log(WARNING, "Invalid image found, aborting load!");
1013 } catch (InvalidParentAlbumFound ipaf) {
1014 logger.log(Level.WARNING,
1015 format("Invalid album image (%s) encountered, aborting load!",
1016 ipaf.getAlbumParentId()));
1021 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1022 if (avatarId != null) {
1023 final Map<String, Image> images =
1024 configurationSoneParser.getImages();
1025 profile.setAvatar(images.get(avatarId));
1029 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1030 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1031 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1032 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1033 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1034 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1035 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1037 /* if we’re still here, Sone was loaded successfully. */
1038 synchronized (sone) {
1039 sone.setTime(soneTime);
1040 sone.setProfile(profile);
1041 sone.setPosts(posts);
1042 sone.setReplies(replies);
1043 sone.setLikePostIds(likedPostIds);
1044 sone.setLikeReplyIds(likedReplyIds);
1045 for (Album album : sone.getRootAlbum().getAlbums()) {
1046 sone.getRootAlbum().removeAlbum(album);
1048 for (Album album : topLevelAlbums) {
1049 sone.getRootAlbum().addAlbum(album);
1051 synchronized (soneInserters) {
1052 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1055 for (Post post : posts) {
1056 post.setKnown(true);
1058 for (PostReply reply : replies) {
1059 reply.setKnown(true);
1062 logger.info(String.format("Sone loaded successfully: %s", sone));
1066 * Creates a new post.
1069 * The Sone that creates the post
1071 * The recipient Sone, or {@code null} if this post does not have
1074 * The text of the post
1075 * @return The created post
1077 public Post createPost(Sone sone, @Nullable Sone recipient, String text) {
1078 checkNotNull(text, "text must not be null");
1079 checkArgument(text.trim().length() > 0, "text must not be empty");
1080 if (!sone.isLocal()) {
1081 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1084 PostBuilder postBuilder = database.newPostBuilder();
1085 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1086 if (recipient != null) {
1087 postBuilder.to(recipient.getId());
1089 final Post post = postBuilder.build();
1090 database.storePost(post);
1091 eventBus.post(new NewPostFoundEvent(post));
1093 touchConfiguration();
1094 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1099 * Deletes the given post.
1102 * The post to delete
1104 public void deletePost(Post post) {
1105 if (!post.getSone().isLocal()) {
1106 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1109 database.removePost(post);
1110 eventBus.post(new PostRemovedEvent(post));
1111 markPostKnown(post);
1112 touchConfiguration();
1116 * Marks the given post as known, if it is currently not a known post
1117 * (according to {@link Post#isKnown()}).
1120 * The post to mark as known
1122 public void markPostKnown(Post post) {
1123 post.setKnown(true);
1124 eventBus.post(new MarkPostKnownEvent(post));
1125 touchConfiguration();
1126 for (PostReply reply : getReplies(post.getId())) {
1127 markReplyKnown(reply);
1131 public void bookmarkPost(Post post) {
1132 database.bookmarkPost(post);
1136 * Removes the given post from the bookmarks.
1139 * The post to unbookmark
1141 public void unbookmarkPost(Post post) {
1142 database.unbookmarkPost(post);
1146 * Creates a new reply.
1149 * The Sone that creates the reply
1151 * The post that this reply refers to
1153 * The text of the reply
1154 * @return The created reply
1156 public PostReply createReply(Sone sone, Post post, String text) {
1157 checkNotNull(text, "text must not be null");
1158 checkArgument(text.trim().length() > 0, "text must not be empty");
1159 if (!sone.isLocal()) {
1160 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1163 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1164 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1165 final PostReply reply = postReplyBuilder.build();
1166 database.storePostReply(reply);
1167 eventBus.post(new NewPostReplyFoundEvent(reply));
1168 sone.addReply(reply);
1169 touchConfiguration();
1170 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1175 * Deletes the given reply.
1178 * The reply to delete
1180 public void deleteReply(PostReply reply) {
1181 Sone sone = reply.getSone();
1182 if (!sone.isLocal()) {
1183 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1186 database.removePostReply(reply);
1187 markReplyKnown(reply);
1188 sone.removeReply(reply);
1189 touchConfiguration();
1193 * Marks the given reply as known, if it is currently not a known reply
1194 * (according to {@link Reply#isKnown()}).
1197 * The reply to mark as known
1199 public void markReplyKnown(PostReply reply) {
1200 boolean previouslyKnown = reply.isKnown();
1201 reply.setKnown(true);
1202 eventBus.post(new MarkPostReplyKnownEvent(reply));
1203 if (!previouslyKnown) {
1204 touchConfiguration();
1209 * Creates a new album for the given Sone.
1212 * The Sone to create the album for
1214 * The parent of the album (may be {@code null} to create a
1216 * @return The new album
1218 public Album createAlbum(Sone sone, Album parent) {
1219 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1220 database.storeAlbum(album);
1221 parent.addAlbum(album);
1226 * Deletes the given album. The owner of the album has to be a local Sone,
1227 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1230 * The album to remove
1232 public void deleteAlbum(Album album) {
1233 checkNotNull(album, "album must not be null");
1234 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1235 if (!album.isEmpty()) {
1238 album.getParent().removeAlbum(album);
1239 database.removeAlbum(album);
1240 touchConfiguration();
1244 * Creates a new image.
1247 * The Sone creating the image
1249 * The album the image will be inserted into
1250 * @param temporaryImage
1251 * The temporary image to create the image from
1252 * @return The newly created image
1254 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1255 checkNotNull(sone, "sone must not be null");
1256 checkNotNull(album, "album must not be null");
1257 checkNotNull(temporaryImage, "temporaryImage must not be null");
1258 checkArgument(sone.isLocal(), "sone must be a local Sone");
1259 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1260 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1261 album.addImage(image);
1262 database.storeImage(image);
1263 imageInserter.insertImage(temporaryImage, image);
1268 * Deletes the given image. This method will also delete a matching
1271 * @see #deleteTemporaryImage(String)
1273 * The image to delete
1275 public void deleteImage(Image image) {
1276 checkNotNull(image, "image must not be null");
1277 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1278 deleteTemporaryImage(image.getId());
1279 image.getAlbum().removeImage(image);
1280 database.removeImage(image);
1281 touchConfiguration();
1285 * Creates a new temporary image.
1288 * The MIME type of the temporary image
1290 * The encoded data of the image
1291 * @return The temporary image
1293 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1294 TemporaryImage temporaryImage = new TemporaryImage();
1295 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1296 synchronized (temporaryImages) {
1297 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1299 return temporaryImage;
1303 * Deletes the temporary image with the given ID.
1306 * The ID of the temporary image to delete
1308 public void deleteTemporaryImage(String imageId) {
1309 checkNotNull(imageId, "imageId must not be null");
1310 synchronized (temporaryImages) {
1311 temporaryImages.remove(imageId);
1313 Image image = getImage(imageId, false);
1314 if (image != null) {
1315 imageInserter.cancelImageInsert(image);
1320 * Notifies the core that the configuration, either of the core or of a
1321 * single local Sone, has changed, and that the configuration should be
1324 public void touchConfiguration() {
1325 lastConfigurationUpdate = System.currentTimeMillis();
1336 public void serviceStart() {
1337 loadConfiguration();
1338 updateChecker.start();
1339 identityManager.start();
1340 webOfTrustUpdater.init();
1341 webOfTrustUpdater.start();
1342 database.startAsync();
1349 public void serviceRun() {
1350 long lastSaved = System.currentTimeMillis();
1351 while (!shouldStop()) {
1353 long now = System.currentTimeMillis();
1354 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1355 for (Sone localSone : getLocalSones()) {
1356 saveSone(localSone);
1358 saveConfiguration();
1368 public void serviceStop() {
1369 localElementTicker.shutdownNow();
1370 synchronized (soneInserters) {
1371 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1372 soneInserter.getValue().stop();
1373 saveSone(soneInserter.getKey());
1376 synchronized (soneRescuers) {
1377 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1381 saveConfiguration();
1382 database.stopAsync();
1383 webOfTrustUpdater.stop();
1384 updateChecker.stop();
1385 soneDownloader.stop();
1386 soneDownloaders.shutdown();
1387 identityManager.stop();
1395 * Saves the given Sone. This will persist all local settings for the given
1396 * Sone, such as the friends list and similar, private options.
1401 private synchronized void saveSone(Sone sone) {
1402 if (!sone.isLocal()) {
1403 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1406 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1407 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1411 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1413 /* save Sone into configuration. */
1414 String sonePrefix = "Sone/" + sone.getId();
1415 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1416 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1419 Profile profile = sone.getProfile();
1420 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1421 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1422 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1423 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1424 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1425 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1426 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1428 /* save profile fields. */
1429 int fieldCounter = 0;
1430 for (Field profileField : profile.getFields()) {
1431 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1432 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1433 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1435 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1438 int postCounter = 0;
1439 for (Post post : sone.getPosts()) {
1440 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1441 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1442 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1443 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1444 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1446 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1449 int replyCounter = 0;
1450 for (PostReply reply : sone.getReplies()) {
1451 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1452 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1453 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1454 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1455 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1457 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1459 /* save post likes. */
1460 int postLikeCounter = 0;
1461 for (String postId : sone.getLikedPostIds()) {
1462 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1464 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1466 /* save reply likes. */
1467 int replyLikeCounter = 0;
1468 for (String replyId : sone.getLikedReplyIds()) {
1469 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1471 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1473 /* save albums. first, collect in a flat structure, top-level first. */
1474 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1476 int albumCounter = 0;
1477 for (Album album : albums) {
1478 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1479 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1480 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1481 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1482 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1484 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1487 int imageCounter = 0;
1488 for (Album album : albums) {
1489 for (Image image : album.getImages()) {
1490 if (!image.isInserted()) {
1493 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1494 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1495 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1496 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1497 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1498 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1499 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1500 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1501 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1504 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1507 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1508 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1509 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1510 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1511 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1512 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1513 configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1515 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1517 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1518 } catch (ConfigurationException ce1) {
1519 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1524 * Saves the current options.
1526 private void saveConfiguration() {
1527 synchronized (configuration) {
1528 if (storingConfiguration) {
1529 logger.log(Level.FINE, "Already storing configuration…");
1532 storingConfiguration = true;
1535 /* store the options first. */
1537 preferences.saveTo(configuration);
1539 /* save known Sones. */
1540 int soneCounter = 0;
1541 synchronized (knownSones) {
1542 for (String knownSoneId : knownSones) {
1543 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1545 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1548 /* save known posts. */
1552 Stopwatch stopwatch = Stopwatch.createStarted();
1553 configuration.save();
1554 configurationSaveTimeHistogram.update(stopwatch.elapsed(TimeUnit.MICROSECONDS));
1556 } catch (ConfigurationException ce1) {
1557 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1558 } catch (DatabaseException de1) {
1559 logger.log(Level.SEVERE, "Could not save database!", de1);
1561 synchronized (configuration) {
1562 storingConfiguration = false;
1568 * Loads the configuration.
1570 private void loadConfiguration() {
1571 new PreferencesLoader(preferences).loadFrom(configuration);
1573 /* load known Sones. */
1574 int soneCounter = 0;
1576 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1577 if (knownSoneId == null) {
1580 synchronized (knownSones) {
1581 knownSones.add(knownSoneId);
1587 * Notifies the core that a new {@link OwnIdentity} was added.
1589 * @param ownIdentityAddedEvent
1593 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1594 OwnIdentity ownIdentity = ownIdentityAddedEvent.getOwnIdentity();
1595 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1596 if (ownIdentity.hasContext("Sone")) {
1597 addLocalSone(ownIdentity);
1602 * Notifies the core that an {@link OwnIdentity} was removed.
1604 * @param ownIdentityRemovedEvent
1608 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1609 OwnIdentity ownIdentity = ownIdentityRemovedEvent.getOwnIdentity();
1610 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1611 trustedIdentities.removeAll(ownIdentity);
1615 * Notifies the core that a new {@link Identity} was added.
1617 * @param identityAddedEvent
1621 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1622 Identity identity = identityAddedEvent.getIdentity();
1623 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1624 trustedIdentities.put(identityAddedEvent.getOwnIdentity(), identity);
1625 addRemoteSone(identity);
1629 * Notifies the core that an {@link Identity} was updated.
1631 * @param identityUpdatedEvent
1635 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1636 Identity identity = identityUpdatedEvent.getIdentity();
1637 final Sone sone = getRemoteSone(identity.getId());
1638 if (sone.isLocal()) {
1641 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1642 if (newLatestEdition != null) {
1643 Long parsedNewLatestEdition = tryParse(newLatestEdition);
1644 if (parsedNewLatestEdition != null) {
1645 sone.setLatestEdition(parsedNewLatestEdition);
1648 soneDownloader.addSone(sone);
1649 soneDownloaders.execute(soneDownloader.fetchSoneAsSskAction(sone));
1653 * Notifies the core that an {@link Identity} was removed.
1655 * @param identityRemovedEvent
1659 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1660 OwnIdentity ownIdentity = identityRemovedEvent.getOwnIdentity();
1661 Identity identity = identityRemovedEvent.getIdentity();
1662 trustedIdentities.remove(ownIdentity, identity);
1663 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1664 if (trustedIdentity.getKey().equals(ownIdentity)) {
1667 if (trustedIdentity.getValue().contains(identity)) {
1671 Sone sone = getSone(identity.getId());
1673 /* TODO - we don’t have the Sone anymore. should this happen? */
1676 for (PostReply postReply : sone.getReplies()) {
1677 eventBus.post(new PostReplyRemovedEvent(postReply));
1679 for (Post post : sone.getPosts()) {
1680 eventBus.post(new PostRemovedEvent(post));
1682 eventBus.post(new SoneRemovedEvent(sone));
1683 database.removeSone(sone);
1687 * Deletes the temporary image.
1689 * @param imageInsertFinishedEvent
1693 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1694 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.getImage(), imageInsertFinishedEvent.getResultingUri()));
1695 imageInsertFinishedEvent.getImage().modify().setKey(imageInsertFinishedEvent.getResultingUri().toString()).update();
1696 deleteTemporaryImage(imageInsertFinishedEvent.getImage().getId());
1697 touchConfiguration();
1701 class MarkPostKnown implements Runnable {
1703 private final Post post;
1705 public MarkPostKnown(Post post) {
1711 markPostKnown(post);
1717 class MarkReplyKnown implements Runnable {
1719 private final PostReply postReply;
1721 public MarkReplyKnown(PostReply postReply) {
1722 this.postReply = postReply;
1727 markReplyKnown(postReply);