2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.database.PostBuilder;
67 import net.pterodactylus.sone.database.PostBuilderFactory;
68 import net.pterodactylus.sone.database.PostProvider;
69 import net.pterodactylus.sone.database.PostReplyBuilder;
70 import net.pterodactylus.sone.database.PostReplyBuilderFactory;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.data.TemporaryImage;
74 import net.pterodactylus.sone.fcp.FcpInterface;
75 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
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.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
93 import com.google.common.base.Function;
94 import com.google.common.base.Optional;
95 import com.google.common.base.Predicate;
96 import com.google.common.base.Predicates;
97 import com.google.common.collect.Collections2;
98 import com.google.common.collect.FluentIterable;
99 import com.google.common.collect.Ordering;
100 import com.google.common.eventbus.EventBus;
101 import com.google.common.eventbus.Subscribe;
102 import com.google.inject.Inject;
104 import freenet.keys.FreenetURI;
109 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
111 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
114 private static final Logger logger = Logging.getLogger(Core.class);
116 /** The start time. */
117 private final long startupTime = System.currentTimeMillis();
120 private final Options options = new Options();
122 /** The preferences. */
123 private final Preferences preferences = new Preferences(options);
125 /** The event bus. */
126 private final EventBus eventBus;
128 /** The configuration. */
129 private Configuration configuration;
131 /** Whether we’re currently saving the configuration. */
132 private boolean storingConfiguration = false;
134 /** The identity manager. */
135 private final IdentityManager identityManager;
137 /** Interface to freenet. */
138 private final FreenetInterface freenetInterface;
140 /** The Sone downloader. */
141 private final SoneDownloader soneDownloader;
143 /** The image inserter. */
144 private final ImageInserter imageInserter;
146 /** Sone downloader thread-pool. */
147 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
149 /** The update checker. */
150 private final UpdateChecker updateChecker;
152 /** The trust updater. */
153 private final WebOfTrustUpdater webOfTrustUpdater;
155 /** The FCP interface. */
156 private volatile FcpInterface fcpInterface;
158 /** The times Sones were followed. */
159 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
161 /** Locked local Sones. */
162 /* synchronize on itself. */
163 private final Set<Sone> lockedSones = new HashSet<Sone>();
165 /** Sone inserters. */
166 /* synchronize access on this on sones. */
167 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
169 /** Sone rescuers. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
174 /* synchronize access on this on itself. */
175 private final Map<String, Sone> sones = new HashMap<String, Sone>();
177 /** All known Sones. */
178 private final Set<String> knownSones = new HashSet<String>();
180 /** The post builder. */
181 private final PostBuilderFactory postBuilderFactory;
184 private final Map<String, Post> posts = new HashMap<String, Post>();
186 /** All known posts. */
187 private final Set<String> knownPosts = new HashSet<String>();
189 /** The post reply builder factory. */
190 private final PostReplyBuilderFactory postReplyBuilderFactory;
193 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
195 /** All known replies. */
196 private final Set<String> knownReplies = new HashSet<String>();
198 /** All bookmarked posts. */
199 /* synchronize access on itself. */
200 private final Set<String> bookmarkedPosts = new HashSet<String>();
202 /** Trusted identities, sorted by own identities. */
203 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
205 /** All known albums. */
206 private final Map<String, Album> albums = new HashMap<String, Album>();
208 /** All known images. */
209 private final Map<String, Image> images = new HashMap<String, Image>();
211 /** All temporary images. */
212 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
214 /** Ticker for threads that mark own elements as known. */
215 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
217 /** The time the configuration was last touched. */
218 private volatile long lastConfigurationUpdate;
221 * Creates a new core.
223 * @param configuration
224 * The configuration of the core
225 * @param freenetInterface
226 * The freenet interface
227 * @param identityManager
228 * The identity manager
229 * @param webOfTrustUpdater
230 * The WebOfTrust updater
233 * @param postBuilderFactory
235 * @param postReplyBuilderFactory
236 * The post reply builder factory
239 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
241 this.configuration = configuration;
242 this.freenetInterface = freenetInterface;
243 this.identityManager = identityManager;
244 this.soneDownloader = new SoneDownloader(this, freenetInterface);
245 this.imageInserter = new ImageInserter(freenetInterface);
246 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
247 this.webOfTrustUpdater = webOfTrustUpdater;
248 this.eventBus = eventBus;
249 this.postBuilderFactory = postBuilderFactory;
250 this.postReplyBuilderFactory = postReplyBuilderFactory;
258 * Returns the time Sone was started.
260 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
262 public long getStartupTime() {
267 * Sets the configuration to use. This will automatically save the current
268 * configuration to the given configuration.
270 * @param configuration
271 * The new configuration to use
273 public void setConfiguration(Configuration configuration) {
274 this.configuration = configuration;
275 touchConfiguration();
279 * Returns the options used by the core.
281 * @return The options of the core
283 public Preferences getPreferences() {
288 * Returns the identity manager used by the core.
290 * @return The identity manager
292 public IdentityManager getIdentityManager() {
293 return identityManager;
297 * Returns the update checker.
299 * @return The update checker
301 public UpdateChecker getUpdateChecker() {
302 return updateChecker;
306 * Sets the FCP interface to use.
308 * @param fcpInterface
309 * The FCP interface to use
311 public void setFcpInterface(FcpInterface fcpInterface) {
312 this.fcpInterface = fcpInterface;
316 * Returns the Sone rescuer for the given local Sone.
319 * The local Sone to get the rescuer for
320 * @return The Sone rescuer for the given Sone
322 public SoneRescuer getSoneRescuer(Sone sone) {
323 checkNotNull(sone, "sone must not be null");
324 checkArgument(sone.isLocal(), "sone must be local");
325 synchronized (sones) {
326 SoneRescuer soneRescuer = soneRescuers.get(sone);
327 if (soneRescuer == null) {
328 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
329 soneRescuers.put(sone, soneRescuer);
337 * Returns whether the given Sone is currently locked.
341 * @return {@code true} if the Sone is locked, {@code false} if it is not
343 public boolean isLocked(Sone sone) {
344 synchronized (lockedSones) {
345 return lockedSones.contains(sone);
350 * Returns all Sones, remote and local.
354 public Set<Sone> getSones() {
355 return new HashSet<Sone>(sones.values());
359 * Returns the Sone with the given ID, regardless whether it’s local or
363 * The ID of the Sone to get
364 * @return The Sone with the given ID, or {@code null} if there is no such
368 public Optional<Sone> getSone(String id) {
369 synchronized (sones) {
370 return Optional.fromNullable(sones.get(id));
375 * Checks whether the core knows a Sone with the given ID.
379 * @return {@code true} if there is a Sone with the given ID, {@code false}
382 public boolean hasSone(String id) {
383 synchronized (sones) {
384 return sones.containsKey(id);
389 * Returns all local Sones.
391 * @return All local Sones
393 public Collection<Sone> getLocalSones() {
394 synchronized (sones) {
395 return Collections2.filter(sones.values(), new Predicate<Sone>() {
398 public boolean apply(Sone sone) {
399 return sone.isLocal();
406 * Returns the local Sone with the given ID, optionally creating a new Sone.
411 * {@code true} to create a new Sone if none exists,
412 * {@code false} to return null if none exists
413 * @return The Sone with the given ID, or {@code null}
415 public Sone getLocalSone(String id, boolean create) {
416 synchronized (sones) {
417 Sone sone = sones.get(id);
418 if ((sone == null) && create) {
419 sone = new Sone(id, true);
422 if ((sone != null) && !sone.isLocal()) {
423 sone = new Sone(id, true);
431 * Returns all remote Sones.
433 * @return All remote Sones
435 public Collection<Sone> getRemoteSones() {
436 synchronized (sones) {
437 return Collections2.filter(sones.values(), new Predicate<Sone>() {
440 public boolean apply(Sone sone) {
441 return !sone.isLocal();
448 * Returns the remote Sone with the given ID.
451 * The ID of the remote Sone to get
453 * {@code true} to always create a Sone, {@code false} to return
454 * {@code null} if no Sone with the given ID exists
455 * @return The Sone with the given ID
457 public Sone getRemoteSone(String id, boolean create) {
458 synchronized (sones) {
459 Sone sone = sones.get(id);
460 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
461 sone = new Sone(id, false);
469 * Returns whether the given Sone has been modified.
472 * The Sone to check for modifications
473 * @return {@code true} if a modification has been detected in the Sone,
474 * {@code false} otherwise
476 public boolean isModifiedSone(Sone sone) {
477 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
481 * Returns the time when the given was first followed by any local Sone.
484 * The Sone to get the time for
485 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
486 * been followed, or {@link Long#MAX_VALUE}
488 public long getSoneFollowingTime(Sone sone) {
489 synchronized (soneFollowingTimes) {
490 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
495 * Returns whether the target Sone is trusted by the origin Sone.
501 * @return {@code true} if the target Sone is trusted by the origin Sone
503 public boolean isSoneTrusted(Sone origin, Sone target) {
504 checkNotNull(origin, "origin must not be null");
505 checkNotNull(target, "target must not be null");
506 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
507 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
511 * Returns a post builder.
513 * @return A new post builder
515 public PostBuilder postBuilder() {
516 return postBuilderFactory.newPostBuilder();
523 public Optional<Post> getPost(String postId) {
524 synchronized (posts) {
525 return Optional.fromNullable(posts.get(postId));
533 public Collection<Post> getDirectedPosts(final String recipientId) {
534 checkNotNull(recipientId, "recipient must not be null");
535 synchronized (posts) {
536 return Collections2.filter(posts.values(), new Predicate<Post>() {
539 public boolean apply(Post post) {
540 return recipientId.equals(post.getRecipientId().orNull());
547 * Returns a post reply builder.
549 * @return A new post reply builder
551 public PostReplyBuilder postReplyBuilder() {
552 return postReplyBuilderFactory.newPostReplyBuilder();
559 public Optional<PostReply> getPostReply(String replyId) {
560 synchronized (replies) {
561 return Optional.fromNullable(replies.get(replyId));
569 public List<PostReply> getReplies(final Post post) {
570 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function<Sone, Iterable<PostReply>>() {
573 public Iterable<PostReply> apply(Sone sone) {
574 return sone.getReplies();
576 }).filter(new Predicate<PostReply>() {
579 public boolean apply(PostReply reply) {
580 return post.getId().equals(reply.getPostId());
586 * Returns all Sones that have liked the given post.
589 * The post to get the liking Sones for
590 * @return The Sones that like the given post
592 public Set<Sone> getLikes(Post post) {
593 Set<Sone> sones = new HashSet<Sone>();
594 for (Sone sone : getSones()) {
595 if (sone.getLikedPostIds().contains(post.getId())) {
603 * Returns all Sones that have liked the given reply.
606 * The reply to get the liking Sones for
607 * @return The Sones that like the given reply
609 public Set<Sone> getLikes(PostReply reply) {
610 Set<Sone> sones = new HashSet<Sone>();
611 for (Sone sone : getSones()) {
612 if (sone.getLikedReplyIds().contains(reply.getId())) {
620 * Returns whether the given post is bookmarked.
624 * @return {@code true} if the given post is bookmarked, {@code false}
627 public boolean isBookmarked(Post post) {
628 return isPostBookmarked(post.getId());
632 * Returns whether the post with the given ID is bookmarked.
635 * The ID of the post to check
636 * @return {@code true} if the post with the given ID is bookmarked,
637 * {@code false} otherwise
639 public boolean isPostBookmarked(String id) {
640 synchronized (bookmarkedPosts) {
641 return bookmarkedPosts.contains(id);
646 * Returns all currently known bookmarked posts.
648 * @return All bookmarked posts
650 public Set<Post> getBookmarkedPosts() {
651 Set<Post> posts = new HashSet<Post>();
652 synchronized (bookmarkedPosts) {
653 for (String bookmarkedPostId : bookmarkedPosts) {
654 Optional<Post> post = getPost(bookmarkedPostId);
655 if (!post.isPresent()) {
656 posts.add(post.get());
664 * Returns the album with the given ID, creating a new album if no album
665 * with the given ID can be found.
668 * The ID of the album
669 * @return The album with the given ID
671 public Album getAlbum(String albumId) {
672 return getAlbum(albumId, true);
676 * Returns the album with the given ID, optionally creating a new album if
677 * an album with the given ID can not be found.
680 * The ID of the album
682 * {@code true} to create a new album if none exists for the
684 * @return The album with the given ID, or {@code null} if no album with the
685 * given ID exists and {@code create} is {@code false}
687 public Album getAlbum(String albumId, boolean create) {
688 synchronized (albums) {
689 Album album = albums.get(albumId);
690 if (create && (album == null)) {
691 album = new Album(albumId);
692 albums.put(albumId, album);
699 * Returns the image with the given ID, creating it if necessary.
702 * The ID of the image
703 * @return The image with the given ID
705 public Image getImage(String imageId) {
706 return getImage(imageId, true);
710 * Returns the image with the given ID, optionally creating it if it does
714 * The ID of the image
716 * {@code true} to create an image if none exists with the given
718 * @return The image with the given ID, or {@code null} if none exists and
721 public Image getImage(String imageId, boolean create) {
722 synchronized (images) {
723 Image image = images.get(imageId);
724 if (create && (image == null)) {
725 image = new Image(imageId);
726 images.put(imageId, image);
733 * Returns the temporary image with the given ID.
736 * The ID of the temporary image
737 * @return The temporary image, or {@code null} if there is no temporary
738 * image with the given ID
740 public TemporaryImage getTemporaryImage(String imageId) {
741 synchronized (temporaryImages) {
742 return temporaryImages.get(imageId);
751 * Locks the given Sone. A locked Sone will not be inserted by
752 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
758 public void lockSone(Sone sone) {
759 synchronized (lockedSones) {
760 if (lockedSones.add(sone)) {
761 eventBus.post(new SoneLockedEvent(sone));
767 * Unlocks the given Sone.
769 * @see #lockSone(Sone)
773 public void unlockSone(Sone sone) {
774 synchronized (lockedSones) {
775 if (lockedSones.remove(sone)) {
776 eventBus.post(new SoneUnlockedEvent(sone));
782 * Adds a local Sone from the given own identity.
785 * The own identity to create a Sone from
786 * @return The added (or already existing) Sone
788 public Sone addLocalSone(OwnIdentity ownIdentity) {
789 if (ownIdentity == null) {
790 logger.log(Level.WARNING, "Given OwnIdentity is null!");
793 synchronized (sones) {
796 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
797 } catch (MalformedURLException mue1) {
798 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
801 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
802 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
804 /* TODO - load posts ’n stuff */
805 sones.put(ownIdentity.getId(), sone);
806 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
807 soneInserters.put(sone, soneInserter);
808 sone.setStatus(SoneStatus.idle);
810 soneInserter.start();
816 * Creates a new Sone for the given own identity.
819 * The own identity to create a Sone for
820 * @return The created Sone
822 public Sone createSone(OwnIdentity ownIdentity) {
823 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
824 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
827 Sone sone = addLocalSone(ownIdentity);
828 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
829 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
830 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
831 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
832 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
833 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
835 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
836 touchConfiguration();
841 * Adds the Sone of the given identity.
844 * The identity whose Sone to add
845 * @return The added or already existing Sone
847 public Sone addRemoteSone(Identity identity) {
848 if (identity == null) {
849 logger.log(Level.WARNING, "Given Identity is null!");
852 synchronized (sones) {
853 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
854 boolean newSone = sone.getRequestUri() == null;
855 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
856 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
858 synchronized (knownSones) {
859 newSone = !knownSones.contains(sone.getId());
861 sone.setKnown(!newSone);
863 eventBus.post(new NewSoneFoundEvent(sone));
864 for (Sone localSone : getLocalSones()) {
865 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
866 followSone(localSone, sone.getId());
871 soneDownloader.addSone(sone);
872 soneDownloaders.execute(new Runnable() {
875 @SuppressWarnings("synthetic-access")
877 soneDownloader.fetchSone(sone, sone.getRequestUri());
886 * Lets the given local Sone follow the Sone with the given ID.
889 * The local Sone that should follow another Sone
891 * The ID of the Sone to follow
893 public void followSone(Sone sone, String soneId) {
894 checkNotNull(sone, "sone must not be null");
895 checkNotNull(soneId, "soneId must not be null");
896 sone.addFriend(soneId);
897 synchronized (soneFollowingTimes) {
898 if (!soneFollowingTimes.containsKey(soneId)) {
899 long now = System.currentTimeMillis();
900 soneFollowingTimes.put(soneId, now);
901 Optional<Sone> followedSone = getSone(soneId);
902 if (!followedSone.isPresent()) {
905 for (Post post : followedSone.get().getPosts()) {
906 if (post.getTime() < now) {
910 for (PostReply reply : followedSone.get().getReplies()) {
911 if (reply.getTime() < now) {
912 markReplyKnown(reply);
917 touchConfiguration();
921 * Lets the given local Sone unfollow the Sone with the given ID.
924 * The local Sone that should unfollow another Sone
926 * The ID of the Sone being unfollowed
928 public void unfollowSone(Sone sone, String soneId) {
929 checkNotNull(sone, "sone must not be null");
930 checkNotNull(soneId, "soneId must not be null");
931 sone.removeFriend(soneId);
932 boolean unfollowedSoneStillFollowed = false;
933 for (Sone localSone : getLocalSones()) {
934 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
936 if (!unfollowedSoneStillFollowed) {
937 synchronized (soneFollowingTimes) {
938 soneFollowingTimes.remove(soneId);
941 touchConfiguration();
945 * Sets the trust value of the given origin Sone for the target Sone.
952 * The trust value (from {@code -100} to {@code 100})
954 public void setTrust(Sone origin, Sone target, int trustValue) {
955 checkNotNull(origin, "origin must not be null");
956 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
957 checkNotNull(target, "target must not be null");
958 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
959 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
963 * Removes any trust assignment for the given target Sone.
970 public void removeTrust(Sone origin, Sone target) {
971 checkNotNull(origin, "origin must not be null");
972 checkNotNull(target, "target must not be null");
973 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
974 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
978 * Assigns the configured positive trust value for the given target.
985 public void trustSone(Sone origin, Sone target) {
986 setTrust(origin, target, preferences.getPositiveTrust());
990 * Assigns the configured negative trust value for the given target.
997 public void distrustSone(Sone origin, Sone target) {
998 setTrust(origin, target, preferences.getNegativeTrust());
1002 * Removes the trust assignment for the given target.
1009 public void untrustSone(Sone origin, Sone target) {
1010 removeTrust(origin, target);
1014 * Updates the stored Sone with the given Sone.
1019 public void updateSone(Sone sone) {
1020 updateSone(sone, false);
1024 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1025 * {@code true}, an older Sone than the current Sone can be given to restore
1029 * The Sone to update
1030 * @param soneRescueMode
1031 * {@code true} if the stored Sone should be updated regardless
1032 * of the age of the given Sone
1034 public void updateSone(Sone sone, boolean soneRescueMode) {
1035 Optional<Sone> storedSone = getSone(sone.getId());
1036 if (storedSone.isPresent()) {
1037 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
1038 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1041 synchronized (posts) {
1042 if (!soneRescueMode) {
1043 for (Post post : storedSone.get().getPosts()) {
1044 posts.remove(post.getId());
1045 if (!sone.getPosts().contains(post)) {
1046 eventBus.post(new PostRemovedEvent(post));
1050 List<Post> storedPosts = storedSone.get().getPosts();
1051 synchronized (knownPosts) {
1052 for (Post post : sone.getPosts()) {
1053 post.setKnown(knownPosts.contains(post.getId()));
1054 if (!storedPosts.contains(post)) {
1055 if (post.getTime() < getSoneFollowingTime(sone)) {
1056 knownPosts.add(post.getId());
1057 post.setKnown(true);
1058 } else if (!knownPosts.contains(post.getId())) {
1059 eventBus.post(new NewPostFoundEvent(post));
1062 posts.put(post.getId(), post);
1066 synchronized (replies) {
1067 if (!soneRescueMode) {
1068 for (PostReply reply : storedSone.get().getReplies()) {
1069 replies.remove(reply.getId());
1070 if (!sone.getReplies().contains(reply)) {
1071 eventBus.post(new PostReplyRemovedEvent(reply));
1075 Set<PostReply> storedReplies = storedSone.get().getReplies();
1076 synchronized (knownReplies) {
1077 for (PostReply reply : sone.getReplies()) {
1078 reply.setKnown(knownReplies.contains(reply.getId()));
1079 if (!storedReplies.contains(reply)) {
1080 if (reply.getTime() < getSoneFollowingTime(sone)) {
1081 knownReplies.add(reply.getId());
1082 reply.setKnown(true);
1083 } else if (!knownReplies.contains(reply.getId())) {
1084 eventBus.post(new NewPostReplyFoundEvent(reply));
1087 replies.put(reply.getId(), reply);
1091 synchronized (albums) {
1092 synchronized (images) {
1093 for (Album album : storedSone.get().getAlbums()) {
1094 albums.remove(album.getId());
1095 for (Image image : album.getImages()) {
1096 images.remove(image.getId());
1099 for (Album album : sone.getAlbums()) {
1100 albums.put(album.getId(), album);
1101 for (Image image : album.getImages()) {
1102 images.put(image.getId(), image);
1107 synchronized (sones) {
1108 sones.put(sone.getId(), sone);
1114 * Deletes the given Sone. This will remove the Sone from the
1115 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1116 * remove the context from its identity.
1119 * The Sone to delete
1121 public void deleteSone(Sone sone) {
1122 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1123 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1126 synchronized (sones) {
1127 if (!getLocalSones().contains(sone)) {
1128 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1131 sones.remove(sone.getId());
1132 SoneInserter soneInserter = soneInserters.remove(sone);
1133 soneInserter.stop();
1135 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1136 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1138 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1139 } catch (ConfigurationException ce1) {
1140 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1145 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1146 * known} before, a {@link MarkSoneKnownEvent} is fired.
1149 * The Sone to mark as known
1151 public void markSoneKnown(Sone sone) {
1152 if (!sone.isKnown()) {
1153 sone.setKnown(true);
1154 synchronized (knownSones) {
1155 knownSones.add(sone.getId());
1157 eventBus.post(new MarkSoneKnownEvent(sone));
1158 touchConfiguration();
1163 * Loads and updates the given Sone from the configuration. If any error is
1164 * encountered, loading is aborted and the given Sone is not changed.
1167 * The Sone to load and update
1169 public void loadSone(Sone sone) {
1170 if (!sone.isLocal()) {
1171 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1175 /* initialize options. */
1176 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1177 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1178 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1179 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1180 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1181 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1184 String sonePrefix = "Sone/" + sone.getId();
1185 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1186 if (soneTime == null) {
1187 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1190 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1193 Profile profile = new Profile(sone);
1194 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1195 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1196 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1197 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1198 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1199 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1201 /* load profile fields. */
1203 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1204 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1205 if (fieldName == null) {
1208 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1209 profile.addField(fieldName).setValue(fieldValue);
1213 Set<Post> posts = new HashSet<Post>();
1215 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1216 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1217 if (postId == null) {
1220 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1221 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1222 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1223 if ((postTime == 0) || (postText == null)) {
1224 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1227 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1228 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1229 postBuilder.to(postRecipientId);
1231 posts.add(postBuilder.build());
1235 Set<PostReply> replies = new HashSet<PostReply>();
1237 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1238 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1239 if (replyId == null) {
1242 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1243 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1244 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1245 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1246 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1249 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1250 postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1251 replies.add(postReplyBuilder.build());
1254 /* load post likes. */
1255 Set<String> likedPostIds = new HashSet<String>();
1257 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1258 if (likedPostId == null) {
1261 likedPostIds.add(likedPostId);
1264 /* load reply likes. */
1265 Set<String> likedReplyIds = new HashSet<String>();
1267 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1268 if (likedReplyId == null) {
1271 likedReplyIds.add(likedReplyId);
1275 Set<String> friends = new HashSet<String>();
1277 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1278 if (friendId == null) {
1281 friends.add(friendId);
1285 List<Album> topLevelAlbums = new ArrayList<Album>();
1286 int albumCounter = 0;
1288 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1289 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1290 if (albumId == null) {
1293 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1294 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1295 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1296 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1297 if ((albumTitle == null) || (albumDescription == null)) {
1298 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1301 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1302 if (albumParentId != null) {
1303 Album parentAlbum = getAlbum(albumParentId, false);
1304 if (parentAlbum == null) {
1305 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1308 parentAlbum.addAlbum(album);
1310 if (!topLevelAlbums.contains(album)) {
1311 topLevelAlbums.add(album);
1317 int imageCounter = 0;
1319 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1320 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1321 if (imageId == null) {
1324 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1325 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1326 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1327 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1328 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1329 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1330 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1331 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1332 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1335 Album album = getAlbum(albumId, false);
1336 if (album == null) {
1337 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1340 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1341 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1342 album.addImage(image);
1346 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1347 if (avatarId != null) {
1348 profile.setAvatar(getImage(avatarId, false));
1352 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1353 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1354 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1355 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1356 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1357 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1359 /* if we’re still here, Sone was loaded successfully. */
1360 synchronized (sone) {
1361 sone.setTime(soneTime);
1362 sone.setProfile(profile);
1363 sone.setPosts(posts);
1364 sone.setReplies(replies);
1365 sone.setLikePostIds(likedPostIds);
1366 sone.setLikeReplyIds(likedReplyIds);
1367 for (String friendId : friends) {
1368 followSone(sone, friendId);
1370 sone.setAlbums(topLevelAlbums);
1371 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1373 synchronized (knownSones) {
1374 for (String friend : friends) {
1375 knownSones.add(friend);
1378 synchronized (this.posts) {
1379 for (Post post : posts) {
1380 this.posts.put(post.getId(), post);
1383 synchronized (knownPosts) {
1384 for (Post post : posts) {
1385 knownPosts.add(post.getId());
1388 synchronized (this.replies) {
1389 for (PostReply postReply : replies) {
1390 this.replies.put(postReply.getId(), postReply);
1393 synchronized (knownReplies) {
1394 for (PostReply reply : replies) {
1395 knownReplies.add(reply.getId());
1401 * Creates a new post.
1404 * The Sone that creates the post
1406 * The text of the post
1407 * @return The created post
1409 public Post createPost(Sone sone, String text) {
1410 return createPost(sone, System.currentTimeMillis(), text);
1414 * Creates a new post.
1417 * The Sone that creates the post
1419 * The time of the post
1421 * The text of the post
1422 * @return The created post
1424 public Post createPost(Sone sone, long time, String text) {
1425 return createPost(sone, null, time, text);
1429 * Creates a new post.
1432 * The Sone that creates the post
1434 * The recipient Sone, or {@code null} if this post does not have
1437 * The text of the post
1438 * @return The created post
1440 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1441 return createPost(sone, recipient, System.currentTimeMillis(), text);
1445 * Creates a new post.
1448 * The Sone that creates the post
1450 * The recipient Sone, or {@code null} if this post does not have
1453 * The time of the post
1455 * The text of the post
1456 * @return The created post
1458 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1459 checkNotNull(text, "text must not be null");
1460 checkArgument(text.trim().length() > 0, "text must not be empty");
1461 if (!sone.isLocal()) {
1462 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1465 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1466 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1467 if (recipient.isPresent()) {
1468 postBuilder.to(recipient.get().getId());
1470 final Post post = postBuilder.build();
1471 synchronized (posts) {
1472 posts.put(post.getId(), post);
1474 eventBus.post(new NewPostFoundEvent(post));
1476 touchConfiguration();
1477 localElementTicker.schedule(new Runnable() {
1484 markPostKnown(post);
1486 }, 10, TimeUnit.SECONDS);
1491 * Deletes the given post.
1494 * The post to delete
1496 public void deletePost(Post post) {
1497 if (!post.getSone().isLocal()) {
1498 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1501 post.getSone().removePost(post);
1502 synchronized (posts) {
1503 posts.remove(post.getId());
1505 eventBus.post(new PostRemovedEvent(post));
1506 markPostKnown(post);
1507 touchConfiguration();
1511 * Marks the given post as known, if it is currently not a known post
1512 * (according to {@link Post#isKnown()}).
1515 * The post to mark as known
1517 public void markPostKnown(Post post) {
1518 post.setKnown(true);
1519 synchronized (knownPosts) {
1520 eventBus.post(new MarkPostKnownEvent(post));
1521 if (knownPosts.add(post.getId())) {
1522 touchConfiguration();
1525 for (PostReply reply : getReplies(post)) {
1526 markReplyKnown(reply);
1531 * Bookmarks the given post.
1534 * The post to bookmark
1536 public void bookmark(Post post) {
1537 bookmarkPost(post.getId());
1541 * Bookmarks the post with the given ID.
1544 * The ID of the post to bookmark
1546 public void bookmarkPost(String id) {
1547 synchronized (bookmarkedPosts) {
1548 bookmarkedPosts.add(id);
1553 * Removes the given post from the bookmarks.
1556 * The post to unbookmark
1558 public void unbookmark(Post post) {
1559 unbookmarkPost(post.getId());
1563 * Removes the post with the given ID from the bookmarks.
1566 * The ID of the post to unbookmark
1568 public void unbookmarkPost(String id) {
1569 synchronized (bookmarkedPosts) {
1570 bookmarkedPosts.remove(id);
1575 * Creates a new reply.
1578 * The Sone that creates the reply
1580 * The post that this reply refers to
1582 * The text of the reply
1583 * @return The created reply
1585 public PostReply createReply(Sone sone, Post post, String text) {
1586 checkNotNull(text, "text must not be null");
1587 checkArgument(text.trim().length() > 0, "text must not be empty");
1588 if (!sone.isLocal()) {
1589 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1592 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1593 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1594 final PostReply reply = postReplyBuilder.build();
1595 synchronized (replies) {
1596 replies.put(reply.getId(), reply);
1598 synchronized (knownReplies) {
1599 eventBus.post(new NewPostReplyFoundEvent(reply));
1601 sone.addReply(reply);
1602 touchConfiguration();
1603 localElementTicker.schedule(new Runnable() {
1610 markReplyKnown(reply);
1612 }, 10, TimeUnit.SECONDS);
1617 * Deletes the given reply.
1620 * The reply to delete
1622 public void deleteReply(PostReply reply) {
1623 Sone sone = reply.getSone();
1624 if (!sone.isLocal()) {
1625 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1628 synchronized (replies) {
1629 replies.remove(reply.getId());
1631 synchronized (knownReplies) {
1632 markReplyKnown(reply);
1633 knownReplies.remove(reply.getId());
1635 sone.removeReply(reply);
1636 touchConfiguration();
1640 * Marks the given reply as known, if it is currently not a known reply
1641 * (according to {@link Reply#isKnown()}).
1644 * The reply to mark as known
1646 public void markReplyKnown(PostReply reply) {
1647 reply.setKnown(true);
1648 synchronized (knownReplies) {
1649 eventBus.post(new MarkPostReplyKnownEvent(reply));
1650 if (knownReplies.add(reply.getId())) {
1651 touchConfiguration();
1657 * Creates a new top-level album for the given Sone.
1660 * The Sone to create the album for
1661 * @return The new album
1663 public Album createAlbum(Sone sone) {
1664 return createAlbum(sone, null);
1668 * Creates a new album for the given Sone.
1671 * The Sone to create the album for
1673 * The parent of the album (may be {@code null} to create a
1675 * @return The new album
1677 public Album createAlbum(Sone sone, Album parent) {
1678 Album album = new Album();
1679 synchronized (albums) {
1680 albums.put(album.getId(), album);
1682 album.setSone(sone);
1683 if (parent != null) {
1684 parent.addAlbum(album);
1686 sone.addAlbum(album);
1692 * Deletes the given album. The owner of the album has to be a local Sone,
1693 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1696 * The album to remove
1698 public void deleteAlbum(Album album) {
1699 checkNotNull(album, "album must not be null");
1700 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1701 if (!album.isEmpty()) {
1704 if (album.getParent() == null) {
1705 album.getSone().removeAlbum(album);
1707 album.getParent().removeAlbum(album);
1709 synchronized (albums) {
1710 albums.remove(album.getId());
1712 touchConfiguration();
1716 * Creates a new image.
1719 * The Sone creating the image
1721 * The album the image will be inserted into
1722 * @param temporaryImage
1723 * The temporary image to create the image from
1724 * @return The newly created image
1726 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1727 checkNotNull(sone, "sone must not be null");
1728 checkNotNull(album, "album must not be null");
1729 checkNotNull(temporaryImage, "temporaryImage must not be null");
1730 checkArgument(sone.isLocal(), "sone must be a local Sone");
1731 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1732 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1733 album.addImage(image);
1734 synchronized (images) {
1735 images.put(image.getId(), image);
1737 imageInserter.insertImage(temporaryImage, image);
1742 * Deletes the given image. This method will also delete a matching
1745 * @see #deleteTemporaryImage(TemporaryImage)
1747 * The image to delete
1749 public void deleteImage(Image image) {
1750 checkNotNull(image, "image must not be null");
1751 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1752 deleteTemporaryImage(image.getId());
1753 image.getAlbum().removeImage(image);
1754 synchronized (images) {
1755 images.remove(image.getId());
1757 touchConfiguration();
1761 * Creates a new temporary image.
1764 * The MIME type of the temporary image
1766 * The encoded data of the image
1767 * @return The temporary image
1769 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1770 TemporaryImage temporaryImage = new TemporaryImage();
1771 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1772 synchronized (temporaryImages) {
1773 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1775 return temporaryImage;
1779 * Deletes the given temporary image.
1781 * @param temporaryImage
1782 * The temporary image to delete
1784 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1785 checkNotNull(temporaryImage, "temporaryImage must not be null");
1786 deleteTemporaryImage(temporaryImage.getId());
1790 * Deletes the temporary image with the given ID.
1793 * The ID of the temporary image to delete
1795 public void deleteTemporaryImage(String imageId) {
1796 checkNotNull(imageId, "imageId must not be null");
1797 synchronized (temporaryImages) {
1798 temporaryImages.remove(imageId);
1800 Image image = getImage(imageId, false);
1801 if (image != null) {
1802 imageInserter.cancelImageInsert(image);
1807 * Notifies the core that the configuration, either of the core or of a
1808 * single local Sone, has changed, and that the configuration should be
1811 public void touchConfiguration() {
1812 lastConfigurationUpdate = System.currentTimeMillis();
1823 public void serviceStart() {
1824 loadConfiguration();
1825 updateChecker.start();
1826 identityManager.start();
1827 webOfTrustUpdater.init();
1828 webOfTrustUpdater.start();
1835 public void serviceRun() {
1836 long lastSaved = System.currentTimeMillis();
1837 while (!shouldStop()) {
1839 long now = System.currentTimeMillis();
1840 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1841 for (Sone localSone : getLocalSones()) {
1842 saveSone(localSone);
1844 saveConfiguration();
1854 public void serviceStop() {
1855 localElementTicker.shutdownNow();
1856 synchronized (sones) {
1857 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1858 soneInserter.getValue().stop();
1859 saveSone(soneInserter.getKey());
1862 saveConfiguration();
1863 webOfTrustUpdater.stop();
1864 updateChecker.stop();
1865 soneDownloader.stop();
1866 soneDownloaders.shutdown();
1867 identityManager.stop();
1875 * Saves the given Sone. This will persist all local settings for the given
1876 * Sone, such as the friends list and similar, private options.
1881 private synchronized void saveSone(Sone sone) {
1882 if (!sone.isLocal()) {
1883 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1886 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1887 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1891 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1893 /* save Sone into configuration. */
1894 String sonePrefix = "Sone/" + sone.getId();
1895 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1896 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1899 Profile profile = sone.getProfile();
1900 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1901 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1902 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1903 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1904 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1905 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1906 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1908 /* save profile fields. */
1909 int fieldCounter = 0;
1910 for (Field profileField : profile.getFields()) {
1911 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1912 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1913 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1915 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1918 int postCounter = 0;
1919 for (Post post : sone.getPosts()) {
1920 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1921 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1922 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1923 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1924 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1926 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1929 int replyCounter = 0;
1930 for (PostReply reply : sone.getReplies()) {
1931 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1932 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1933 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1934 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1935 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1937 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1939 /* save post likes. */
1940 int postLikeCounter = 0;
1941 for (String postId : sone.getLikedPostIds()) {
1942 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1944 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1946 /* save reply likes. */
1947 int replyLikeCounter = 0;
1948 for (String replyId : sone.getLikedReplyIds()) {
1949 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1951 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1954 int friendCounter = 0;
1955 for (String friendId : sone.getFriends()) {
1956 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1958 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1960 /* save albums. first, collect in a flat structure, top-level first. */
1961 List<Album> albums = sone.getAllAlbums();
1963 int albumCounter = 0;
1964 for (Album album : albums) {
1965 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1966 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1967 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1968 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1969 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1970 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1972 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1975 int imageCounter = 0;
1976 for (Album album : albums) {
1977 for (Image image : album.getImages()) {
1978 if (!image.isInserted()) {
1981 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1982 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1983 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1984 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1985 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1986 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1987 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1988 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1989 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1992 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1995 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1996 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1997 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1998 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1999 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2000 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2002 configuration.save();
2004 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2006 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2007 } catch (ConfigurationException ce1) {
2008 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2013 * Saves the current options.
2015 private void saveConfiguration() {
2016 synchronized (configuration) {
2017 if (storingConfiguration) {
2018 logger.log(Level.FINE, "Already storing configuration…");
2021 storingConfiguration = true;
2024 /* store the options first. */
2026 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2027 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2028 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2029 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2030 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2031 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2032 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2033 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2034 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2035 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2036 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2037 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2039 /* save known Sones. */
2040 int soneCounter = 0;
2041 synchronized (knownSones) {
2042 for (String knownSoneId : knownSones) {
2043 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2045 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2048 /* save Sone following times. */
2050 synchronized (soneFollowingTimes) {
2051 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2052 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
2053 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2056 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2059 /* save known posts. */
2060 int postCounter = 0;
2061 synchronized (knownPosts) {
2062 for (String knownPostId : knownPosts) {
2063 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2065 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2068 /* save known replies. */
2069 int replyCounter = 0;
2070 synchronized (knownReplies) {
2071 for (String knownReplyId : knownReplies) {
2072 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2074 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2077 /* save bookmarked posts. */
2078 int bookmarkedPostCounter = 0;
2079 synchronized (bookmarkedPosts) {
2080 for (String bookmarkedPostId : bookmarkedPosts) {
2081 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2084 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2087 configuration.save();
2089 } catch (ConfigurationException ce1) {
2090 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2092 synchronized (configuration) {
2093 storingConfiguration = false;
2099 * Loads the configuration.
2101 private void loadConfiguration() {
2102 /* create options. */
2103 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2106 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2107 SoneInserter.setInsertionDelay(newValue);
2111 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2112 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2113 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2114 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2115 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2116 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2117 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2118 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2119 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2122 @SuppressWarnings("synthetic-access")
2123 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2124 fcpInterface.setActive(newValue);
2127 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2130 @SuppressWarnings("synthetic-access")
2131 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2132 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2137 loadConfigurationValue("InsertionDelay");
2138 loadConfigurationValue("PostsPerPage");
2139 loadConfigurationValue("ImagesPerPage");
2140 loadConfigurationValue("CharactersPerPost");
2141 loadConfigurationValue("PostCutOffLength");
2142 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2143 loadConfigurationValue("PositiveTrust");
2144 loadConfigurationValue("NegativeTrust");
2145 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2146 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2147 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2149 /* load known Sones. */
2150 int soneCounter = 0;
2152 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2153 if (knownSoneId == null) {
2156 synchronized (knownSones) {
2157 knownSones.add(knownSoneId);
2161 /* load Sone following times. */
2164 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2165 if (soneId == null) {
2168 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2169 synchronized (soneFollowingTimes) {
2170 soneFollowingTimes.put(soneId, time);
2175 /* load known posts. */
2176 int postCounter = 0;
2178 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2179 if (knownPostId == null) {
2182 synchronized (knownPosts) {
2183 knownPosts.add(knownPostId);
2187 /* load known replies. */
2188 int replyCounter = 0;
2190 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2191 if (knownReplyId == null) {
2194 synchronized (knownReplies) {
2195 knownReplies.add(knownReplyId);
2199 /* load bookmarked posts. */
2200 int bookmarkedPostCounter = 0;
2202 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2203 if (bookmarkedPostId == null) {
2206 synchronized (bookmarkedPosts) {
2207 bookmarkedPosts.add(bookmarkedPostId);
2214 * Loads an {@link Integer} configuration value for the option with the
2215 * given name, logging validation failures.
2218 * The name of the option to load
2220 private void loadConfigurationValue(String optionName) {
2222 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2223 } catch (IllegalArgumentException iae1) {
2224 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2229 * Notifies the core that a new {@link OwnIdentity} was added.
2231 * @param ownIdentityAddedEvent
2235 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2236 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2237 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2238 if (ownIdentity.hasContext("Sone")) {
2239 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2240 addLocalSone(ownIdentity);
2245 * Notifies the core that an {@link OwnIdentity} was removed.
2247 * @param ownIdentityRemovedEvent
2251 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2252 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2253 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2254 trustedIdentities.remove(ownIdentity);
2258 * Notifies the core that a new {@link Identity} was added.
2260 * @param identityAddedEvent
2264 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2265 Identity identity = identityAddedEvent.identity();
2266 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2267 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2268 addRemoteSone(identity);
2272 * Notifies the core that an {@link Identity} was updated.
2274 * @param identityUpdatedEvent
2278 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2279 final Identity identity = identityUpdatedEvent.identity();
2280 soneDownloaders.execute(new Runnable() {
2283 @SuppressWarnings("synthetic-access")
2285 Sone sone = getRemoteSone(identity.getId(), false);
2286 sone.setIdentity(identity);
2287 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2288 soneDownloader.addSone(sone);
2289 soneDownloader.fetchSone(sone);
2295 * Notifies the core that an {@link Identity} was removed.
2297 * @param identityRemovedEvent
2301 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2302 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2303 Identity identity = identityRemovedEvent.identity();
2304 trustedIdentities.get(ownIdentity).remove(identity);
2305 boolean foundIdentity = false;
2306 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2307 if (trustedIdentity.getKey().equals(ownIdentity)) {
2310 if (trustedIdentity.getValue().contains(identity)) {
2311 foundIdentity = true;
2314 if (foundIdentity) {
2315 /* some local identity still trusts this identity, don’t remove. */
2318 Optional<Sone> sone = getSone(identity.getId());
2319 if (!sone.isPresent()) {
2320 /* TODO - we don’t have the Sone anymore. should this happen? */
2323 synchronized (posts) {
2324 synchronized (knownPosts) {
2325 for (Post post : sone.get().getPosts()) {
2326 posts.remove(post.getId());
2327 eventBus.post(new PostRemovedEvent(post));
2331 synchronized (replies) {
2332 synchronized (knownReplies) {
2333 for (PostReply reply : sone.get().getReplies()) {
2334 replies.remove(reply.getId());
2335 eventBus.post(new PostReplyRemovedEvent(reply));
2339 synchronized (sones) {
2340 sones.remove(identity.getId());
2342 eventBus.post(new SoneRemovedEvent(sone.get()));
2346 * Deletes the temporary image.
2348 * @param imageInsertFinishedEvent
2352 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2353 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2354 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2355 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2356 touchConfiguration();