2 * Sone - Core.java - Copyright © 2010–2016 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.logging.Level;
41 import java.util.logging.Logger;
43 import javax.annotation.Nonnull;
44 import javax.annotation.Nullable;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
51 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
52 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
53 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
54 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
55 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
56 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
57 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
58 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
59 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
60 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
61 import net.pterodactylus.sone.core.event.PostRemovedEvent;
62 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
63 import net.pterodactylus.sone.core.event.SoneLockedEvent;
64 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
65 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
66 import net.pterodactylus.sone.data.Album;
67 import net.pterodactylus.sone.data.Client;
68 import net.pterodactylus.sone.data.Image;
69 import net.pterodactylus.sone.data.Post;
70 import net.pterodactylus.sone.data.PostReply;
71 import net.pterodactylus.sone.data.Profile;
72 import net.pterodactylus.sone.data.Profile.Field;
73 import net.pterodactylus.sone.data.Reply;
74 import net.pterodactylus.sone.data.Sone;
75 import net.pterodactylus.sone.data.Sone.SoneStatus;
76 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
77 import net.pterodactylus.sone.data.TemporaryImage;
78 import net.pterodactylus.sone.database.AlbumBuilder;
79 import net.pterodactylus.sone.database.Database;
80 import net.pterodactylus.sone.database.DatabaseException;
81 import net.pterodactylus.sone.database.ImageBuilder;
82 import net.pterodactylus.sone.database.PostBuilder;
83 import net.pterodactylus.sone.database.PostProvider;
84 import net.pterodactylus.sone.database.PostReplyBuilder;
85 import net.pterodactylus.sone.database.PostReplyProvider;
86 import net.pterodactylus.sone.database.SoneBuilder;
87 import net.pterodactylus.sone.database.SoneProvider;
88 import net.pterodactylus.sone.freenet.wot.Identity;
89 import net.pterodactylus.sone.freenet.wot.IdentityManager;
90 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
95 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
96 import net.pterodactylus.sone.main.SonePlugin;
97 import net.pterodactylus.util.config.Configuration;
98 import net.pterodactylus.util.config.ConfigurationException;
99 import net.pterodactylus.util.service.AbstractService;
100 import net.pterodactylus.util.thread.NamedThreadFactory;
102 import com.google.common.annotations.VisibleForTesting;
103 import com.google.common.base.Optional;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
111 import com.google.inject.Singleton;
112 import kotlin.jvm.functions.Function1;
118 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
121 private static final Logger logger = getLogger(Core.class.getName());
123 /** The start time. */
124 private final long startupTime = System.currentTimeMillis();
126 /** The preferences. */
127 private final Preferences preferences;
129 /** The event bus. */
130 private final EventBus eventBus;
132 /** The configuration. */
133 private final Configuration configuration;
135 /** Whether we’re currently saving the configuration. */
136 private boolean storingConfiguration = false;
138 /** The identity manager. */
139 private final IdentityManager identityManager;
141 /** Interface to freenet. */
142 private final FreenetInterface freenetInterface;
144 /** The Sone downloader. */
145 private final SoneDownloader soneDownloader;
147 /** The image inserter. */
148 private final ImageInserter imageInserter;
150 /** Sone downloader thread-pool. */
151 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
153 /** The update checker. */
154 private final UpdateChecker updateChecker;
156 /** The trust updater. */
157 private final WebOfTrustUpdater webOfTrustUpdater;
159 /** Locked local Sones. */
160 /* synchronize on itself. */
161 private final Set<Sone> lockedSones = new HashSet<Sone>();
163 /** Sone inserters. */
164 /* synchronize access on this on sones. */
165 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
167 /** Sone rescuers. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
171 /** All known Sones. */
172 private final Set<String> knownSones = new HashSet<String>();
174 /** The post database. */
175 private final Database database;
177 /** Trusted identities, sorted by own identities. */
178 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
180 /** All temporary images. */
181 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
183 /** Ticker for threads that mark own elements as known. */
184 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
186 /** The time the configuration was last touched. */
187 private volatile long lastConfigurationUpdate;
190 * Creates a new core.
192 * @param configuration
193 * The configuration of the core
194 * @param freenetInterface
195 * The freenet interface
196 * @param identityManager
197 * The identity manager
198 * @param webOfTrustUpdater
199 * The WebOfTrust updater
206 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
208 this.configuration = configuration;
209 this.freenetInterface = freenetInterface;
210 this.identityManager = identityManager;
211 this.soneDownloader = soneDownloader;
212 this.imageInserter = imageInserter;
213 this.updateChecker = updateChecker;
214 this.webOfTrustUpdater = webOfTrustUpdater;
215 this.eventBus = eventBus;
216 this.database = database;
217 preferences = new Preferences(eventBus);
225 * Returns the time Sone was started.
227 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
229 public long getStartupTime() {
234 * Returns the options used by the core.
236 * @return The options of the core
238 public Preferences getPreferences() {
243 * Returns the identity manager used by the core.
245 * @return The identity manager
247 public IdentityManager getIdentityManager() {
248 return identityManager;
252 * Returns the update checker.
254 * @return The update checker
256 public UpdateChecker getUpdateChecker() {
257 return updateChecker;
261 * Returns the Sone rescuer for the given local Sone.
264 * The local Sone to get the rescuer for
265 * @return The Sone rescuer for the given Sone
267 public SoneRescuer getSoneRescuer(Sone sone) {
268 checkNotNull(sone, "sone must not be null");
269 checkArgument(sone.isLocal(), "sone must be local");
270 synchronized (soneRescuers) {
271 SoneRescuer soneRescuer = soneRescuers.get(sone);
272 if (soneRescuer == null) {
273 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
274 soneRescuers.put(sone, soneRescuer);
282 * Returns whether the given Sone is currently locked.
286 * @return {@code true} if the Sone is locked, {@code false} if it is not
288 public boolean isLocked(Sone sone) {
289 synchronized (lockedSones) {
290 return lockedSones.contains(sone);
294 public SoneBuilder soneBuilder() {
295 return database.newSoneBuilder();
303 public Collection<Sone> getSones() {
304 return database.getSones();
309 public Function1<String, Sone> getSoneLoader() {
310 return database.getSoneLoader();
314 * Returns the Sone with the given ID, regardless whether it’s local or
318 * The ID of the Sone to get
319 * @return The Sone with the given ID, or {@code null} if there is no such
324 public Sone getSone(@Nonnull String id) {
325 return database.getSone(id);
332 public Collection<Sone> getLocalSones() {
333 return database.getLocalSones();
337 * Returns the local Sone with the given ID, optionally creating a new Sone.
341 * @return The Sone with the given ID, or {@code null}
343 public Sone getLocalSone(String id) {
344 Sone sone = database.getSone(id);
345 if ((sone != null) && sone.isLocal()) {
355 public Collection<Sone> getRemoteSones() {
356 return database.getRemoteSones();
360 * Returns the remote Sone with the given ID.
364 * The ID of the remote Sone to get
365 * @return The Sone with the given ID
367 public Sone getRemoteSone(String id) {
368 return database.getSone(id);
372 * Returns whether the given Sone has been modified.
375 * The Sone to check for modifications
376 * @return {@code true} if a modification has been detected in the Sone,
377 * {@code false} otherwise
379 public boolean isModifiedSone(Sone sone) {
380 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
384 * Returns a post builder.
386 * @return A new post builder
388 public PostBuilder postBuilder() {
389 return database.newPostBuilder();
394 public Post getPost(@Nonnull String postId) {
395 return database.getPost(postId);
402 public Collection<Post> getPosts(String soneId) {
403 return database.getPosts(soneId);
410 public Collection<Post> getDirectedPosts(final String recipientId) {
411 checkNotNull(recipientId, "recipient must not be null");
412 return database.getDirectedPosts(recipientId);
416 * Returns a post reply builder.
418 * @return A new post reply builder
420 public PostReplyBuilder postReplyBuilder() {
421 return database.newPostReplyBuilder();
429 public PostReply getPostReply(String replyId) {
430 return database.getPostReply(replyId);
437 public List<PostReply> getReplies(final String postId) {
438 return database.getReplies(postId);
442 * Returns all Sones that have liked the given post.
445 * The post to get the liking Sones for
446 * @return The Sones that like the given post
448 public Set<Sone> getLikes(Post post) {
449 Set<Sone> sones = new HashSet<Sone>();
450 for (Sone sone : getSones()) {
451 if (sone.getLikedPostIds().contains(post.getId())) {
459 * Returns all Sones that have liked the given reply.
462 * The reply to get the liking Sones for
463 * @return The Sones that like the given reply
465 public Set<Sone> getLikes(PostReply reply) {
466 Set<Sone> sones = new HashSet<Sone>();
467 for (Sone sone : getSones()) {
468 if (sone.getLikedReplyIds().contains(reply.getId())) {
476 * Returns whether the given post is bookmarked.
480 * @return {@code true} if the given post is bookmarked, {@code false}
483 public boolean isBookmarked(Post post) {
484 return database.isPostBookmarked(post);
488 * Returns all currently known bookmarked posts.
490 * @return All bookmarked posts
492 public Set<Post> getBookmarkedPosts() {
493 return database.getBookmarkedPosts();
496 public AlbumBuilder albumBuilder() {
497 return database.newAlbumBuilder();
501 * Returns the album with the given ID, optionally creating a new album if
502 * an album with the given ID can not be found.
505 * The ID of the album
506 * @return The album with the given ID, or {@code null} if no album with the
510 public Album getAlbum(@Nonnull String albumId) {
511 return database.getAlbum(albumId);
514 public ImageBuilder imageBuilder() {
515 return database.newImageBuilder();
519 * Returns the image with the given ID, creating it if necessary.
522 * The ID of the image
523 * @return The image with the given ID
526 public Image getImage(String imageId) {
527 return getImage(imageId, true);
531 * Returns the image with the given ID, optionally creating it if it does
535 * The ID of the image
537 * {@code true} to create an image if none exists with the given
539 * @return The image with the given ID, or {@code null} if none exists and
543 public Image getImage(String imageId, boolean create) {
544 Image image = database.getImage(imageId);
551 Image newImage = database.newImageBuilder().withId(imageId).build();
552 database.storeImage(newImage);
557 * Returns the temporary image with the given ID.
560 * The ID of the temporary image
561 * @return The temporary image, or {@code null} if there is no temporary
562 * image with the given ID
564 public TemporaryImage getTemporaryImage(String imageId) {
565 synchronized (temporaryImages) {
566 return temporaryImages.get(imageId);
575 * Locks the given Sone. A locked Sone will not be inserted by
576 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
582 public void lockSone(Sone sone) {
583 synchronized (lockedSones) {
584 if (lockedSones.add(sone)) {
585 eventBus.post(new SoneLockedEvent(sone));
591 * Unlocks the given Sone.
593 * @see #lockSone(Sone)
597 public void unlockSone(Sone sone) {
598 synchronized (lockedSones) {
599 if (lockedSones.remove(sone)) {
600 eventBus.post(new SoneUnlockedEvent(sone));
606 * Adds a local Sone from the given own identity.
609 * The own identity to create a Sone from
610 * @return The added (or already existing) Sone
612 public Sone addLocalSone(OwnIdentity ownIdentity) {
613 if (ownIdentity == null) {
614 logger.log(Level.WARNING, "Given OwnIdentity is null!");
617 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
618 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
619 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
620 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
621 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
623 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
624 soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
625 eventBus.register(soneInserter);
626 synchronized (soneInserters) {
627 soneInserters.put(sone, soneInserter);
630 database.storeSone(sone);
631 sone.setStatus(SoneStatus.idle);
632 soneInserter.start();
637 * Creates a new Sone for the given own identity.
640 * The own identity to create a Sone for
641 * @return The created Sone
643 public Sone createSone(OwnIdentity ownIdentity) {
644 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
645 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
648 Sone sone = addLocalSone(ownIdentity);
650 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
651 touchConfiguration();
656 * Adds the Sone of the given identity.
659 * The identity whose Sone to add
660 * @return The added or already existing Sone
662 public Sone addRemoteSone(Identity identity) {
663 if (identity == null) {
664 logger.log(Level.WARNING, "Given Identity is null!");
667 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
668 long latestEdition = fromNullable(tryParse(property)).or(0L);
669 Sone existingSone = getSone(identity.getId());
670 if ((existingSone != null )&& existingSone.isLocal()) {
673 boolean newSone = existingSone == null;
674 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
675 sone.setLatestEdition(latestEdition);
677 synchronized (knownSones) {
678 newSone = !knownSones.contains(sone.getId());
680 sone.setKnown(!newSone);
682 eventBus.post(new NewSoneFoundEvent(sone));
683 for (Sone localSone : getLocalSones()) {
684 if (localSone.getOptions().isAutoFollow()) {
685 followSone(localSone, sone.getId());
690 database.storeSone(sone);
691 soneDownloader.addSone(sone);
692 soneDownloaders.execute(soneDownloader.fetchSoneAsUskAction(sone));
697 * Lets the given local Sone follow the Sone with the given ID.
700 * The local Sone that should follow another Sone
702 * The ID of the Sone to follow
704 public void followSone(Sone sone, String soneId) {
705 checkNotNull(sone, "sone must not be null");
706 checkNotNull(soneId, "soneId must not be null");
707 database.addFriend(sone, soneId);
708 @SuppressWarnings("ConstantConditions") // we just followed, this can’t be null.
709 long now = database.getFollowingTime(soneId);
710 Sone followedSone = getSone(soneId);
711 if (followedSone == null) {
714 for (Post post : followedSone.getPosts()) {
715 if (post.getTime() < now) {
719 for (PostReply reply : followedSone.getReplies()) {
720 if (reply.getTime() < now) {
721 markReplyKnown(reply);
724 touchConfiguration();
728 * Lets the given local Sone unfollow the Sone with the given ID.
731 * The local Sone that should unfollow another Sone
733 * The ID of the Sone being unfollowed
735 public void unfollowSone(Sone sone, String soneId) {
736 checkNotNull(sone, "sone must not be null");
737 checkNotNull(soneId, "soneId must not be null");
738 database.removeFriend(sone, soneId);
739 touchConfiguration();
743 * Sets the trust value of the given origin Sone for the target Sone.
750 * The trust value (from {@code -100} to {@code 100})
752 public void setTrust(Sone origin, Sone target, int trustValue) {
753 checkNotNull(origin, "origin must not be null");
754 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
755 checkNotNull(target, "target must not be null");
756 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
757 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
761 * Removes any trust assignment for the given target Sone.
768 public void removeTrust(Sone origin, Sone target) {
769 checkNotNull(origin, "origin must not be null");
770 checkNotNull(target, "target must not be null");
771 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
772 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
776 * Assigns the configured positive trust value for the given target.
783 public void trustSone(Sone origin, Sone target) {
784 setTrust(origin, target, preferences.getPositiveTrust());
788 * Assigns the configured negative trust value for the given target.
795 public void distrustSone(Sone origin, Sone target) {
796 setTrust(origin, target, preferences.getNegativeTrust());
800 * Removes the trust assignment for the given target.
807 public void untrustSone(Sone origin, Sone target) {
808 removeTrust(origin, target);
812 * Updates the stored Sone with the given Sone.
817 public void updateSone(Sone sone) {
818 updateSone(sone, false);
822 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
823 * {@code true}, an older Sone than the current Sone can be given to restore
828 * @param soneRescueMode
829 * {@code true} if the stored Sone should be updated regardless
830 * of the age of the given Sone
832 public void updateSone(final Sone sone, boolean soneRescueMode) {
833 Sone storedSone = getSone(sone.getId());
834 if (storedSone != null) {
835 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
836 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
839 List<Object> events =
840 collectEventsForChangesInSone(storedSone, sone);
841 database.storeSone(sone);
842 for (Object event : events) {
843 eventBus.post(event);
845 sone.setOptions(storedSone.getOptions());
846 sone.setKnown(storedSone.isKnown());
847 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
848 if (sone.isLocal()) {
849 touchConfiguration();
854 private List<Object> collectEventsForChangesInSone(Sone oldSone,
855 final Sone newSone) {
856 final List<Object> events = new ArrayList<Object>();
857 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
859 soneChangeDetector.onNewPosts(new PostProcessor() {
861 public void processPost(Post post) {
862 if (post.getSone().equals(newSone)) {
864 } else if (post.getTime() < database.getFollowingTime(newSone.getId())) {
866 } else if (!post.isKnown()) {
867 events.add(new NewPostFoundEvent(post));
871 soneChangeDetector.onRemovedPosts(new PostProcessor() {
873 public void processPost(Post post) {
874 events.add(new PostRemovedEvent(post));
877 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
879 public void processPostReply(PostReply postReply) {
880 if (postReply.getSone().equals(newSone)) {
881 postReply.setKnown(true);
882 } else if (postReply.getTime() < database.getFollowingTime(newSone.getId())) {
883 postReply.setKnown(true);
884 } else if (!postReply.isKnown()) {
885 events.add(new NewPostReplyFoundEvent(postReply));
889 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
891 public void processPostReply(PostReply postReply) {
892 events.add(new PostReplyRemovedEvent(postReply));
895 soneChangeDetector.detectChanges(newSone);
900 * Deletes the given Sone. This will remove the Sone from the
901 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
902 * remove the context from its identity.
907 public void deleteSone(Sone sone) {
908 if (!(sone.getIdentity() instanceof OwnIdentity)) {
909 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
912 if (!getLocalSones().contains(sone)) {
913 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
916 SoneInserter soneInserter = soneInserters.remove(sone);
918 database.removeSone(sone);
919 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
920 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
922 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
923 } catch (ConfigurationException ce1) {
924 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
929 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
930 * known} before, a {@link MarkSoneKnownEvent} is fired.
933 * The Sone to mark as known
935 public void markSoneKnown(Sone sone) {
936 if (!sone.isKnown()) {
938 synchronized (knownSones) {
939 knownSones.add(sone.getId());
941 eventBus.post(new MarkSoneKnownEvent(sone));
942 touchConfiguration();
947 * Loads and updates the given Sone from the configuration. If any error is
948 * encountered, loading is aborted and the given Sone is not changed.
951 * The Sone to load and update
953 public void loadSone(Sone sone) {
954 if (!sone.isLocal()) {
955 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
958 logger.info(String.format("Loading local Sone: %s", sone));
961 String sonePrefix = "Sone/" + sone.getId();
962 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
963 if (soneTime == null) {
964 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
967 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
970 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
971 Profile profile = configurationSoneParser.parseProfile();
974 Collection<Post> posts;
976 posts = configurationSoneParser.parsePosts(database);
977 } catch (InvalidPostFound ipf) {
978 logger.log(Level.WARNING, "Invalid post found, aborting load!");
983 Collection<PostReply> replies;
985 replies = configurationSoneParser.parsePostReplies(database);
986 } catch (InvalidPostReplyFound iprf) {
987 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
991 /* load post likes. */
992 Set<String> likedPostIds =
993 configurationSoneParser.parseLikedPostIds();
995 /* load reply likes. */
996 Set<String> likedReplyIds =
997 configurationSoneParser.parseLikedPostReplyIds();
1000 List<Album> topLevelAlbums;
1003 configurationSoneParser.parseTopLevelAlbums(database);
1004 } catch (InvalidAlbumFound iaf) {
1005 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1007 } catch (InvalidParentAlbumFound ipaf) {
1008 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1009 ipaf.getAlbumParentId()));
1015 configurationSoneParser.parseImages(database);
1016 } catch (InvalidImageFound iif) {
1017 logger.log(WARNING, "Invalid image found, aborting load!");
1019 } catch (InvalidParentAlbumFound ipaf) {
1020 logger.log(Level.WARNING,
1021 format("Invalid album image (%s) encountered, aborting load!",
1022 ipaf.getAlbumParentId()));
1027 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1028 if (avatarId != null) {
1029 final Map<String, Image> images =
1030 configurationSoneParser.getImages();
1031 profile.setAvatar(images.get(avatarId));
1035 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1036 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1037 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1038 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1039 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1040 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1041 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1043 /* if we’re still here, Sone was loaded successfully. */
1044 synchronized (sone) {
1045 sone.setTime(soneTime);
1046 sone.setProfile(profile);
1047 sone.setPosts(posts);
1048 sone.setReplies(replies);
1049 sone.setLikePostIds(likedPostIds);
1050 sone.setLikeReplyIds(likedReplyIds);
1051 for (Album album : sone.getRootAlbum().getAlbums()) {
1052 sone.getRootAlbum().removeAlbum(album);
1054 for (Album album : topLevelAlbums) {
1055 sone.getRootAlbum().addAlbum(album);
1057 synchronized (soneInserters) {
1058 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1061 for (Post post : posts) {
1062 post.setKnown(true);
1064 for (PostReply reply : replies) {
1065 reply.setKnown(true);
1068 logger.info(String.format("Sone loaded successfully: %s", sone));
1072 * Creates a new post.
1075 * The Sone that creates the post
1077 * The recipient Sone, or {@code null} if this post does not have
1080 * The text of the post
1081 * @return The created post
1083 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1084 checkNotNull(text, "text must not be null");
1085 checkArgument(text.trim().length() > 0, "text must not be empty");
1086 if (!sone.isLocal()) {
1087 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1090 PostBuilder postBuilder = database.newPostBuilder();
1091 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1092 if (recipient.isPresent()) {
1093 postBuilder.to(recipient.get().getId());
1095 final Post post = postBuilder.build();
1096 database.storePost(post);
1097 eventBus.post(new NewPostFoundEvent(post));
1099 touchConfiguration();
1100 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1105 * Deletes the given post.
1108 * The post to delete
1110 public void deletePost(Post post) {
1111 if (!post.getSone().isLocal()) {
1112 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1115 database.removePost(post);
1116 eventBus.post(new PostRemovedEvent(post));
1117 markPostKnown(post);
1118 touchConfiguration();
1122 * Marks the given post as known, if it is currently not a known post
1123 * (according to {@link Post#isKnown()}).
1126 * The post to mark as known
1128 public void markPostKnown(Post post) {
1129 post.setKnown(true);
1130 eventBus.post(new MarkPostKnownEvent(post));
1131 touchConfiguration();
1132 for (PostReply reply : getReplies(post.getId())) {
1133 markReplyKnown(reply);
1137 public void bookmarkPost(Post post) {
1138 database.bookmarkPost(post);
1142 * Removes the given post from the bookmarks.
1145 * The post to unbookmark
1147 public void unbookmarkPost(Post post) {
1148 database.unbookmarkPost(post);
1152 * Creates a new reply.
1155 * The Sone that creates the reply
1157 * The post that this reply refers to
1159 * The text of the reply
1160 * @return The created reply
1162 public PostReply createReply(Sone sone, Post post, String text) {
1163 checkNotNull(text, "text must not be null");
1164 checkArgument(text.trim().length() > 0, "text must not be empty");
1165 if (!sone.isLocal()) {
1166 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1169 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1170 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1171 final PostReply reply = postReplyBuilder.build();
1172 database.storePostReply(reply);
1173 eventBus.post(new NewPostReplyFoundEvent(reply));
1174 sone.addReply(reply);
1175 touchConfiguration();
1176 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1181 * Deletes the given reply.
1184 * The reply to delete
1186 public void deleteReply(PostReply reply) {
1187 Sone sone = reply.getSone();
1188 if (!sone.isLocal()) {
1189 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1192 database.removePostReply(reply);
1193 markReplyKnown(reply);
1194 sone.removeReply(reply);
1195 touchConfiguration();
1199 * Marks the given reply as known, if it is currently not a known reply
1200 * (according to {@link Reply#isKnown()}).
1203 * The reply to mark as known
1205 public void markReplyKnown(PostReply reply) {
1206 boolean previouslyKnown = reply.isKnown();
1207 reply.setKnown(true);
1208 eventBus.post(new MarkPostReplyKnownEvent(reply));
1209 if (!previouslyKnown) {
1210 touchConfiguration();
1215 * Creates a new album for the given Sone.
1218 * The Sone to create the album for
1220 * The parent of the album (may be {@code null} to create a
1222 * @return The new album
1224 public Album createAlbum(Sone sone, Album parent) {
1225 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1226 database.storeAlbum(album);
1227 parent.addAlbum(album);
1232 * Deletes the given album. The owner of the album has to be a local Sone,
1233 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1236 * The album to remove
1238 public void deleteAlbum(Album album) {
1239 checkNotNull(album, "album must not be null");
1240 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1241 if (!album.isEmpty()) {
1244 album.getParent().removeAlbum(album);
1245 database.removeAlbum(album);
1246 touchConfiguration();
1250 * Creates a new image.
1253 * The Sone creating the image
1255 * The album the image will be inserted into
1256 * @param temporaryImage
1257 * The temporary image to create the image from
1258 * @return The newly created image
1260 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1261 checkNotNull(sone, "sone must not be null");
1262 checkNotNull(album, "album must not be null");
1263 checkNotNull(temporaryImage, "temporaryImage must not be null");
1264 checkArgument(sone.isLocal(), "sone must be a local Sone");
1265 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1266 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1267 album.addImage(image);
1268 database.storeImage(image);
1269 imageInserter.insertImage(temporaryImage, image);
1274 * Deletes the given image. This method will also delete a matching
1277 * @see #deleteTemporaryImage(String)
1279 * The image to delete
1281 public void deleteImage(Image image) {
1282 checkNotNull(image, "image must not be null");
1283 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1284 deleteTemporaryImage(image.getId());
1285 image.getAlbum().removeImage(image);
1286 database.removeImage(image);
1287 touchConfiguration();
1291 * Creates a new temporary image.
1294 * The MIME type of the temporary image
1296 * The encoded data of the image
1297 * @return The temporary image
1299 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1300 TemporaryImage temporaryImage = new TemporaryImage();
1301 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1302 synchronized (temporaryImages) {
1303 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1305 return temporaryImage;
1309 * Deletes the temporary image with the given ID.
1312 * The ID of the temporary image to delete
1314 public void deleteTemporaryImage(String imageId) {
1315 checkNotNull(imageId, "imageId must not be null");
1316 synchronized (temporaryImages) {
1317 temporaryImages.remove(imageId);
1319 Image image = getImage(imageId, false);
1320 if (image != null) {
1321 imageInserter.cancelImageInsert(image);
1326 * Notifies the core that the configuration, either of the core or of a
1327 * single local Sone, has changed, and that the configuration should be
1330 public void touchConfiguration() {
1331 lastConfigurationUpdate = System.currentTimeMillis();
1342 public void serviceStart() {
1343 loadConfiguration();
1344 updateChecker.start();
1345 identityManager.start();
1346 webOfTrustUpdater.init();
1347 webOfTrustUpdater.start();
1355 public void serviceRun() {
1356 long lastSaved = System.currentTimeMillis();
1357 while (!shouldStop()) {
1359 long now = System.currentTimeMillis();
1360 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1361 for (Sone localSone : getLocalSones()) {
1362 saveSone(localSone);
1364 saveConfiguration();
1374 public void serviceStop() {
1375 localElementTicker.shutdownNow();
1376 synchronized (soneInserters) {
1377 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1378 soneInserter.getValue().stop();
1379 saveSone(soneInserter.getKey());
1382 synchronized (soneRescuers) {
1383 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1387 saveConfiguration();
1389 webOfTrustUpdater.stop();
1390 updateChecker.stop();
1391 soneDownloader.stop();
1392 soneDownloaders.shutdown();
1393 identityManager.stop();
1401 * Saves the given Sone. This will persist all local settings for the given
1402 * Sone, such as the friends list and similar, private options.
1407 private synchronized void saveSone(Sone sone) {
1408 if (!sone.isLocal()) {
1409 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1412 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1413 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1417 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1419 /* save Sone into configuration. */
1420 String sonePrefix = "Sone/" + sone.getId();
1421 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1422 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1425 Profile profile = sone.getProfile();
1426 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1427 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1428 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1429 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1430 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1431 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1432 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1434 /* save profile fields. */
1435 int fieldCounter = 0;
1436 for (Field profileField : profile.getFields()) {
1437 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1438 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1439 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1441 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1444 int postCounter = 0;
1445 for (Post post : sone.getPosts()) {
1446 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1447 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1448 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1449 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1450 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1452 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1455 int replyCounter = 0;
1456 for (PostReply reply : sone.getReplies()) {
1457 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1458 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1459 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1460 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1461 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1463 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1465 /* save post likes. */
1466 int postLikeCounter = 0;
1467 for (String postId : sone.getLikedPostIds()) {
1468 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1470 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1472 /* save reply likes. */
1473 int replyLikeCounter = 0;
1474 for (String replyId : sone.getLikedReplyIds()) {
1475 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1477 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1479 /* save albums. first, collect in a flat structure, top-level first. */
1480 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1482 int albumCounter = 0;
1483 for (Album album : albums) {
1484 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1485 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1486 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1487 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1488 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1490 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1493 int imageCounter = 0;
1494 for (Album album : albums) {
1495 for (Image image : album.getImages()) {
1496 if (!image.isInserted()) {
1499 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1500 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1501 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1502 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1503 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1504 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1505 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1506 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1507 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1510 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1513 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1514 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1515 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1516 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1517 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1518 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1519 configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1521 configuration.save();
1523 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1525 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1526 } catch (ConfigurationException ce1) {
1527 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1532 * Saves the current options.
1534 private void saveConfiguration() {
1535 synchronized (configuration) {
1536 if (storingConfiguration) {
1537 logger.log(Level.FINE, "Already storing configuration…");
1540 storingConfiguration = true;
1543 /* store the options first. */
1545 preferences.saveTo(configuration);
1547 /* save known Sones. */
1548 int soneCounter = 0;
1549 synchronized (knownSones) {
1550 for (String knownSoneId : knownSones) {
1551 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1553 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1556 /* save known posts. */
1560 configuration.save();
1562 } catch (ConfigurationException ce1) {
1563 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1564 } catch (DatabaseException de1) {
1565 logger.log(Level.SEVERE, "Could not save database!", de1);
1567 synchronized (configuration) {
1568 storingConfiguration = false;
1574 * Loads the configuration.
1576 private void loadConfiguration() {
1577 new PreferencesLoader(preferences).loadFrom(configuration);
1579 /* load known Sones. */
1580 int soneCounter = 0;
1582 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1583 if (knownSoneId == null) {
1586 synchronized (knownSones) {
1587 knownSones.add(knownSoneId);
1593 * Notifies the core that a new {@link OwnIdentity} was added.
1595 * @param ownIdentityAddedEvent
1599 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1600 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1601 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1602 if (ownIdentity.hasContext("Sone")) {
1603 addLocalSone(ownIdentity);
1608 * Notifies the core that an {@link OwnIdentity} was removed.
1610 * @param ownIdentityRemovedEvent
1614 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1615 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1616 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1617 trustedIdentities.removeAll(ownIdentity);
1621 * Notifies the core that a new {@link Identity} was added.
1623 * @param identityAddedEvent
1627 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1628 Identity identity = identityAddedEvent.identity();
1629 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1630 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1631 addRemoteSone(identity);
1635 * Notifies the core that an {@link Identity} was updated.
1637 * @param identityUpdatedEvent
1641 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1642 Identity identity = identityUpdatedEvent.identity();
1643 final Sone sone = getRemoteSone(identity.getId());
1644 if (sone.isLocal()) {
1647 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1648 if (newLatestEdition != null) {
1649 Long parsedNewLatestEdition = tryParse(newLatestEdition);
1650 if (parsedNewLatestEdition != null) {
1651 sone.setLatestEdition(parsedNewLatestEdition);
1654 soneDownloader.addSone(sone);
1655 soneDownloaders.execute(soneDownloader.fetchSoneAsSskAction(sone));
1659 * Notifies the core that an {@link Identity} was removed.
1661 * @param identityRemovedEvent
1665 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1666 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1667 Identity identity = identityRemovedEvent.identity();
1668 trustedIdentities.remove(ownIdentity, identity);
1669 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1670 if (trustedIdentity.getKey().equals(ownIdentity)) {
1673 if (trustedIdentity.getValue().contains(identity)) {
1677 Sone sone = getSone(identity.getId());
1679 /* TODO - we don’t have the Sone anymore. should this happen? */
1682 for (PostReply postReply : sone.getReplies()) {
1683 eventBus.post(new PostReplyRemovedEvent(postReply));
1685 for (Post post : sone.getPosts()) {
1686 eventBus.post(new PostRemovedEvent(post));
1688 eventBus.post(new SoneRemovedEvent(sone));
1689 database.removeSone(sone);
1693 * Deletes the temporary image.
1695 * @param imageInsertFinishedEvent
1699 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1700 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1701 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1702 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1703 touchConfiguration();
1707 class MarkPostKnown implements Runnable {
1709 private final Post post;
1711 public MarkPostKnown(Post post) {
1717 markPostKnown(post);
1723 class MarkReplyKnown implements Runnable {
1725 private final PostReply postReply;
1727 public MarkReplyKnown(PostReply postReply) {
1728 this.postReply = postReply;
1733 markReplyKnown(postReply);