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 synchronized (sones) {
356 return Collections.unmodifiableCollection(sones.values());
361 * Returns the Sone with the given ID, regardless whether it’s local or
365 * The ID of the Sone to get
366 * @return The Sone with the given ID, or {@code null} if there is no such
370 public Optional<Sone> getSone(String id) {
371 synchronized (sones) {
372 return Optional.fromNullable(sones.get(id));
377 * Returns all local Sones.
379 * @return All local Sones
381 public Collection<Sone> getLocalSones() {
382 synchronized (sones) {
383 return Collections2.filter(sones.values(), new Predicate<Sone>() {
386 public boolean apply(Sone sone) {
387 return sone.isLocal();
394 * Returns the local Sone with the given ID, optionally creating a new Sone.
399 * {@code true} to create a new Sone if none exists,
400 * {@code false} to return null if none exists
401 * @return The Sone with the given ID, or {@code null}
403 public Sone getLocalSone(String id, boolean create) {
404 synchronized (sones) {
405 Sone sone = sones.get(id);
406 if ((sone == null) && create) {
407 sone = new Sone(id, true);
410 if ((sone != null) && !sone.isLocal()) {
411 sone = new Sone(id, true);
419 * Returns all remote Sones.
421 * @return All remote Sones
423 public Collection<Sone> getRemoteSones() {
424 synchronized (sones) {
425 return Collections2.filter(sones.values(), new Predicate<Sone>() {
428 public boolean apply(Sone sone) {
429 return !sone.isLocal();
436 * Returns the remote Sone with the given ID.
439 * The ID of the remote Sone to get
441 * {@code true} to always create a Sone, {@code false} to return
442 * {@code null} if no Sone with the given ID exists
443 * @return The Sone with the given ID
445 public Sone getRemoteSone(String id, boolean create) {
446 synchronized (sones) {
447 Sone sone = sones.get(id);
448 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
449 sone = new Sone(id, false);
457 * Returns whether the given Sone has been modified.
460 * The Sone to check for modifications
461 * @return {@code true} if a modification has been detected in the Sone,
462 * {@code false} otherwise
464 public boolean isModifiedSone(Sone sone) {
465 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
469 * Returns the time when the given was first followed by any local Sone.
472 * The Sone to get the time for
473 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
474 * been followed, or {@link Long#MAX_VALUE}
476 public long getSoneFollowingTime(Sone sone) {
477 synchronized (soneFollowingTimes) {
478 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
483 * Returns whether the target Sone is trusted by the origin Sone.
489 * @return {@code true} if the target Sone is trusted by the origin Sone
491 public boolean isSoneTrusted(Sone origin, Sone target) {
492 checkNotNull(origin, "origin must not be null");
493 checkNotNull(target, "target must not be null");
494 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
495 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
499 * Returns a post builder.
501 * @return A new post builder
503 public PostBuilder postBuilder() {
504 return postBuilderFactory.newPostBuilder();
511 public Optional<Post> getPost(String postId) {
512 synchronized (posts) {
513 return Optional.fromNullable(posts.get(postId));
521 public Collection<Post> getDirectedPosts(final String recipientId) {
522 checkNotNull(recipientId, "recipient must not be null");
523 synchronized (posts) {
524 return Collections2.filter(posts.values(), new Predicate<Post>() {
527 public boolean apply(Post post) {
528 return recipientId.equals(post.getRecipientId().orNull());
535 * Returns a post reply builder.
537 * @return A new post reply builder
539 public PostReplyBuilder postReplyBuilder() {
540 return postReplyBuilderFactory.newPostReplyBuilder();
547 public Optional<PostReply> getPostReply(String replyId) {
548 synchronized (replies) {
549 return Optional.fromNullable(replies.get(replyId));
557 public List<PostReply> getReplies(final Post post) {
558 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function<Sone, Iterable<PostReply>>() {
561 public Iterable<PostReply> apply(Sone sone) {
562 return sone.getReplies();
564 }).filter(new Predicate<PostReply>() {
567 public boolean apply(PostReply reply) {
568 return post.getId().equals(reply.getPostId());
574 * Returns all Sones that have liked the given post.
577 * The post to get the liking Sones for
578 * @return The Sones that like the given post
580 public Set<Sone> getLikes(Post post) {
581 Set<Sone> sones = new HashSet<Sone>();
582 for (Sone sone : getSones()) {
583 if (sone.getLikedPostIds().contains(post.getId())) {
591 * Returns all Sones that have liked the given reply.
594 * The reply to get the liking Sones for
595 * @return The Sones that like the given reply
597 public Set<Sone> getLikes(PostReply reply) {
598 Set<Sone> sones = new HashSet<Sone>();
599 for (Sone sone : getSones()) {
600 if (sone.getLikedReplyIds().contains(reply.getId())) {
608 * Returns whether the given post is bookmarked.
612 * @return {@code true} if the given post is bookmarked, {@code false}
615 public boolean isBookmarked(Post post) {
616 return isPostBookmarked(post.getId());
620 * Returns whether the post with the given ID is bookmarked.
623 * The ID of the post to check
624 * @return {@code true} if the post with the given ID is bookmarked,
625 * {@code false} otherwise
627 public boolean isPostBookmarked(String id) {
628 synchronized (bookmarkedPosts) {
629 return bookmarkedPosts.contains(id);
634 * Returns all currently known bookmarked posts.
636 * @return All bookmarked posts
638 public Set<Post> getBookmarkedPosts() {
639 Set<Post> posts = new HashSet<Post>();
640 synchronized (bookmarkedPosts) {
641 for (String bookmarkedPostId : bookmarkedPosts) {
642 Optional<Post> post = getPost(bookmarkedPostId);
643 if (!post.isPresent()) {
644 posts.add(post.get());
652 * Returns the album with the given ID, creating a new album if no album
653 * with the given ID can be found.
656 * The ID of the album
657 * @return The album with the given ID
659 public Album getAlbum(String albumId) {
660 return getAlbum(albumId, true);
664 * Returns the album with the given ID, optionally creating a new album if
665 * an album with the given ID can not be found.
668 * The ID of the album
670 * {@code true} to create a new album if none exists for the
672 * @return The album with the given ID, or {@code null} if no album with the
673 * given ID exists and {@code create} is {@code false}
675 public Album getAlbum(String albumId, boolean create) {
676 synchronized (albums) {
677 Album album = albums.get(albumId);
678 if (create && (album == null)) {
679 album = new Album(albumId);
680 albums.put(albumId, album);
687 * Returns the image with the given ID, creating it if necessary.
690 * The ID of the image
691 * @return The image with the given ID
693 public Image getImage(String imageId) {
694 return getImage(imageId, true);
698 * Returns the image with the given ID, optionally creating it if it does
702 * The ID of the image
704 * {@code true} to create an image if none exists with the given
706 * @return The image with the given ID, or {@code null} if none exists and
709 public Image getImage(String imageId, boolean create) {
710 synchronized (images) {
711 Image image = images.get(imageId);
712 if (create && (image == null)) {
713 image = new Image(imageId);
714 images.put(imageId, image);
721 * Returns the temporary image with the given ID.
724 * The ID of the temporary image
725 * @return The temporary image, or {@code null} if there is no temporary
726 * image with the given ID
728 public TemporaryImage getTemporaryImage(String imageId) {
729 synchronized (temporaryImages) {
730 return temporaryImages.get(imageId);
739 * Locks the given Sone. A locked Sone will not be inserted by
740 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
746 public void lockSone(Sone sone) {
747 synchronized (lockedSones) {
748 if (lockedSones.add(sone)) {
749 eventBus.post(new SoneLockedEvent(sone));
755 * Unlocks the given Sone.
757 * @see #lockSone(Sone)
761 public void unlockSone(Sone sone) {
762 synchronized (lockedSones) {
763 if (lockedSones.remove(sone)) {
764 eventBus.post(new SoneUnlockedEvent(sone));
770 * Adds a local Sone from the given own identity.
773 * The own identity to create a Sone from
774 * @return The added (or already existing) Sone
776 public Sone addLocalSone(OwnIdentity ownIdentity) {
777 if (ownIdentity == null) {
778 logger.log(Level.WARNING, "Given OwnIdentity is null!");
781 synchronized (sones) {
784 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
785 } catch (MalformedURLException mue1) {
786 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
789 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
790 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
792 /* TODO - load posts ’n stuff */
793 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
794 sones.put(ownIdentity.getId(), sone);
795 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
796 soneInserters.put(sone, soneInserter);
797 sone.setStatus(SoneStatus.idle);
799 soneInserter.start();
805 * Creates a new Sone for the given own identity.
808 * The own identity to create a Sone for
809 * @return The created Sone
811 public Sone createSone(OwnIdentity ownIdentity) {
812 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
813 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
816 Sone sone = addLocalSone(ownIdentity);
817 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
818 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
819 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
820 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
821 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
822 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
824 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
825 touchConfiguration();
830 * Adds the Sone of the given identity.
833 * The identity whose Sone to add
834 * @return The added or already existing Sone
836 public Sone addRemoteSone(Identity identity) {
837 if (identity == null) {
838 logger.log(Level.WARNING, "Given Identity is null!");
841 synchronized (sones) {
842 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
843 boolean newSone = sone.getRequestUri() == null;
844 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
845 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
847 synchronized (knownSones) {
848 newSone = !knownSones.contains(sone.getId());
850 sone.setKnown(!newSone);
852 eventBus.post(new NewSoneFoundEvent(sone));
853 for (Sone localSone : getLocalSones()) {
854 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
855 followSone(localSone, sone.getId());
860 soneDownloader.addSone(sone);
861 soneDownloaders.execute(new Runnable() {
864 @SuppressWarnings("synthetic-access")
866 soneDownloader.fetchSone(sone, sone.getRequestUri());
875 * Lets the given local Sone follow the Sone with the given ID.
878 * The local Sone that should follow another Sone
880 * The ID of the Sone to follow
882 public void followSone(Sone sone, String soneId) {
883 checkNotNull(sone, "sone must not be null");
884 checkNotNull(soneId, "soneId must not be null");
885 sone.addFriend(soneId);
886 synchronized (soneFollowingTimes) {
887 if (!soneFollowingTimes.containsKey(soneId)) {
888 long now = System.currentTimeMillis();
889 soneFollowingTimes.put(soneId, now);
890 Optional<Sone> followedSone = getSone(soneId);
891 if (!followedSone.isPresent()) {
894 for (Post post : followedSone.get().getPosts()) {
895 if (post.getTime() < now) {
899 for (PostReply reply : followedSone.get().getReplies()) {
900 if (reply.getTime() < now) {
901 markReplyKnown(reply);
906 touchConfiguration();
910 * Lets the given local Sone unfollow the Sone with the given ID.
913 * The local Sone that should unfollow another Sone
915 * The ID of the Sone being unfollowed
917 public void unfollowSone(Sone sone, String soneId) {
918 checkNotNull(sone, "sone must not be null");
919 checkNotNull(soneId, "soneId must not be null");
920 sone.removeFriend(soneId);
921 boolean unfollowedSoneStillFollowed = false;
922 for (Sone localSone : getLocalSones()) {
923 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
925 if (!unfollowedSoneStillFollowed) {
926 synchronized (soneFollowingTimes) {
927 soneFollowingTimes.remove(soneId);
930 touchConfiguration();
934 * Sets the trust value of the given origin Sone for the target Sone.
941 * The trust value (from {@code -100} to {@code 100})
943 public void setTrust(Sone origin, Sone target, int trustValue) {
944 checkNotNull(origin, "origin must not be null");
945 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
946 checkNotNull(target, "target must not be null");
947 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
948 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
952 * Removes any trust assignment for the given target Sone.
959 public void removeTrust(Sone origin, Sone target) {
960 checkNotNull(origin, "origin must not be null");
961 checkNotNull(target, "target must not be null");
962 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
963 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
967 * Assigns the configured positive trust value for the given target.
974 public void trustSone(Sone origin, Sone target) {
975 setTrust(origin, target, preferences.getPositiveTrust());
979 * Assigns the configured negative trust value for the given target.
986 public void distrustSone(Sone origin, Sone target) {
987 setTrust(origin, target, preferences.getNegativeTrust());
991 * Removes the trust assignment for the given target.
998 public void untrustSone(Sone origin, Sone target) {
999 removeTrust(origin, target);
1003 * Updates the stored Sone with the given Sone.
1008 public void updateSone(Sone sone) {
1009 updateSone(sone, false);
1013 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1014 * {@code true}, an older Sone than the current Sone can be given to restore
1018 * The Sone to update
1019 * @param soneRescueMode
1020 * {@code true} if the stored Sone should be updated regardless
1021 * of the age of the given Sone
1023 public void updateSone(Sone sone, boolean soneRescueMode) {
1024 Optional<Sone> storedSone = getSone(sone.getId());
1025 if (storedSone.isPresent()) {
1026 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
1027 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1030 synchronized (posts) {
1031 if (!soneRescueMode) {
1032 for (Post post : storedSone.get().getPosts()) {
1033 posts.remove(post.getId());
1034 if (!sone.getPosts().contains(post)) {
1035 eventBus.post(new PostRemovedEvent(post));
1039 List<Post> storedPosts = storedSone.get().getPosts();
1040 synchronized (knownPosts) {
1041 for (Post post : sone.getPosts()) {
1042 post.setKnown(knownPosts.contains(post.getId()));
1043 if (!storedPosts.contains(post)) {
1044 if (post.getTime() < getSoneFollowingTime(sone)) {
1045 knownPosts.add(post.getId());
1046 post.setKnown(true);
1047 } else if (!knownPosts.contains(post.getId())) {
1048 eventBus.post(new NewPostFoundEvent(post));
1051 posts.put(post.getId(), post);
1055 synchronized (replies) {
1056 if (!soneRescueMode) {
1057 for (PostReply reply : storedSone.get().getReplies()) {
1058 replies.remove(reply.getId());
1059 if (!sone.getReplies().contains(reply)) {
1060 eventBus.post(new PostReplyRemovedEvent(reply));
1064 Set<PostReply> storedReplies = storedSone.get().getReplies();
1065 synchronized (knownReplies) {
1066 for (PostReply reply : sone.getReplies()) {
1067 reply.setKnown(knownReplies.contains(reply.getId()));
1068 if (!storedReplies.contains(reply)) {
1069 if (reply.getTime() < getSoneFollowingTime(sone)) {
1070 knownReplies.add(reply.getId());
1071 reply.setKnown(true);
1072 } else if (!knownReplies.contains(reply.getId())) {
1073 eventBus.post(new NewPostReplyFoundEvent(reply));
1076 replies.put(reply.getId(), reply);
1080 synchronized (albums) {
1081 synchronized (images) {
1082 for (Album album : storedSone.get().getAlbums()) {
1083 albums.remove(album.getId());
1084 for (Image image : album.getImages()) {
1085 images.remove(image.getId());
1088 for (Album album : sone.getAlbums()) {
1089 albums.put(album.getId(), album);
1090 for (Image image : album.getImages()) {
1091 images.put(image.getId(), image);
1096 synchronized (sones) {
1097 sones.put(sone.getId(), sone);
1103 * Deletes the given Sone. This will remove the Sone from the
1104 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1105 * remove the context from its identity.
1108 * The Sone to delete
1110 public void deleteSone(Sone sone) {
1111 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1112 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1115 synchronized (sones) {
1116 if (!getLocalSones().contains(sone)) {
1117 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1120 sones.remove(sone.getId());
1121 SoneInserter soneInserter = soneInserters.remove(sone);
1122 soneInserter.stop();
1124 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1125 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1127 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1128 } catch (ConfigurationException ce1) {
1129 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1134 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1135 * known} before, a {@link MarkSoneKnownEvent} is fired.
1138 * The Sone to mark as known
1140 public void markSoneKnown(Sone sone) {
1141 if (!sone.isKnown()) {
1142 sone.setKnown(true);
1143 synchronized (knownSones) {
1144 knownSones.add(sone.getId());
1146 eventBus.post(new MarkSoneKnownEvent(sone));
1147 touchConfiguration();
1152 * Loads and updates the given Sone from the configuration. If any error is
1153 * encountered, loading is aborted and the given Sone is not changed.
1156 * The Sone to load and update
1158 public void loadSone(Sone sone) {
1159 if (!sone.isLocal()) {
1160 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1164 /* initialize options. */
1165 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1166 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1167 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1168 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1169 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1170 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1173 String sonePrefix = "Sone/" + sone.getId();
1174 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1175 if (soneTime == null) {
1176 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1179 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1182 Profile profile = new Profile(sone);
1183 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1184 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1185 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1186 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1187 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1188 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1190 /* load profile fields. */
1192 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1193 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1194 if (fieldName == null) {
1197 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1198 profile.addField(fieldName).setValue(fieldValue);
1202 Set<Post> posts = new HashSet<Post>();
1204 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1205 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1206 if (postId == null) {
1209 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1210 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1211 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1212 if ((postTime == 0) || (postText == null)) {
1213 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1216 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1217 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1218 postBuilder.to(postRecipientId);
1220 posts.add(postBuilder.build());
1224 Set<PostReply> replies = new HashSet<PostReply>();
1226 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1227 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1228 if (replyId == null) {
1231 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1232 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1233 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1234 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1235 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1238 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1239 postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1240 replies.add(postReplyBuilder.build());
1243 /* load post likes. */
1244 Set<String> likedPostIds = new HashSet<String>();
1246 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1247 if (likedPostId == null) {
1250 likedPostIds.add(likedPostId);
1253 /* load reply likes. */
1254 Set<String> likedReplyIds = new HashSet<String>();
1256 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1257 if (likedReplyId == null) {
1260 likedReplyIds.add(likedReplyId);
1264 Set<String> friends = new HashSet<String>();
1266 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1267 if (friendId == null) {
1270 friends.add(friendId);
1274 List<Album> topLevelAlbums = new ArrayList<Album>();
1275 int albumCounter = 0;
1277 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1278 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1279 if (albumId == null) {
1282 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1283 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1284 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1285 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1286 if ((albumTitle == null) || (albumDescription == null)) {
1287 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1290 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1291 if (albumParentId != null) {
1292 Album parentAlbum = getAlbum(albumParentId, false);
1293 if (parentAlbum == null) {
1294 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1297 parentAlbum.addAlbum(album);
1299 if (!topLevelAlbums.contains(album)) {
1300 topLevelAlbums.add(album);
1306 int imageCounter = 0;
1308 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1309 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1310 if (imageId == null) {
1313 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1314 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1315 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1316 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1317 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1318 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1319 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1320 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1321 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1324 Album album = getAlbum(albumId, false);
1325 if (album == null) {
1326 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1329 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1330 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1331 album.addImage(image);
1335 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1336 if (avatarId != null) {
1337 profile.setAvatar(getImage(avatarId, false));
1341 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1342 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1343 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1344 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1345 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1346 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1348 /* if we’re still here, Sone was loaded successfully. */
1349 synchronized (sone) {
1350 sone.setTime(soneTime);
1351 sone.setProfile(profile);
1352 sone.setPosts(posts);
1353 sone.setReplies(replies);
1354 sone.setLikePostIds(likedPostIds);
1355 sone.setLikeReplyIds(likedReplyIds);
1356 for (String friendId : friends) {
1357 followSone(sone, friendId);
1359 sone.setAlbums(topLevelAlbums);
1360 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1362 synchronized (knownSones) {
1363 for (String friend : friends) {
1364 knownSones.add(friend);
1367 synchronized (this.posts) {
1368 for (Post post : posts) {
1369 this.posts.put(post.getId(), post);
1372 synchronized (knownPosts) {
1373 for (Post post : posts) {
1374 knownPosts.add(post.getId());
1377 synchronized (this.replies) {
1378 for (PostReply postReply : replies) {
1379 this.replies.put(postReply.getId(), postReply);
1382 synchronized (knownReplies) {
1383 for (PostReply reply : replies) {
1384 knownReplies.add(reply.getId());
1390 * Creates a new post.
1393 * The Sone that creates the post
1395 * The text of the post
1396 * @return The created post
1398 public Post createPost(Sone sone, String text) {
1399 return createPost(sone, System.currentTimeMillis(), text);
1403 * Creates a new post.
1406 * The Sone that creates the post
1408 * The time of the post
1410 * The text of the post
1411 * @return The created post
1413 public Post createPost(Sone sone, long time, String text) {
1414 return createPost(sone, null, time, text);
1418 * Creates a new post.
1421 * The Sone that creates the post
1423 * The recipient Sone, or {@code null} if this post does not have
1426 * The text of the post
1427 * @return The created post
1429 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1430 return createPost(sone, recipient, System.currentTimeMillis(), text);
1434 * Creates a new post.
1437 * The Sone that creates the post
1439 * The recipient Sone, or {@code null} if this post does not have
1442 * The time of the post
1444 * The text of the post
1445 * @return The created post
1447 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1448 checkNotNull(text, "text must not be null");
1449 checkArgument(text.trim().length() > 0, "text must not be empty");
1450 if (!sone.isLocal()) {
1451 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1454 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1455 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1456 if (recipient.isPresent()) {
1457 postBuilder.to(recipient.get().getId());
1459 final Post post = postBuilder.build();
1460 synchronized (posts) {
1461 posts.put(post.getId(), post);
1463 eventBus.post(new NewPostFoundEvent(post));
1465 touchConfiguration();
1466 localElementTicker.schedule(new Runnable() {
1473 markPostKnown(post);
1475 }, 10, TimeUnit.SECONDS);
1480 * Deletes the given post.
1483 * The post to delete
1485 public void deletePost(Post post) {
1486 if (!post.getSone().isLocal()) {
1487 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1490 post.getSone().removePost(post);
1491 synchronized (posts) {
1492 posts.remove(post.getId());
1494 eventBus.post(new PostRemovedEvent(post));
1495 markPostKnown(post);
1496 touchConfiguration();
1500 * Marks the given post as known, if it is currently not a known post
1501 * (according to {@link Post#isKnown()}).
1504 * The post to mark as known
1506 public void markPostKnown(Post post) {
1507 post.setKnown(true);
1508 synchronized (knownPosts) {
1509 eventBus.post(new MarkPostKnownEvent(post));
1510 if (knownPosts.add(post.getId())) {
1511 touchConfiguration();
1514 for (PostReply reply : getReplies(post)) {
1515 markReplyKnown(reply);
1520 * Bookmarks the given post.
1523 * The post to bookmark
1525 public void bookmark(Post post) {
1526 bookmarkPost(post.getId());
1530 * Bookmarks the post with the given ID.
1533 * The ID of the post to bookmark
1535 public void bookmarkPost(String id) {
1536 synchronized (bookmarkedPosts) {
1537 bookmarkedPosts.add(id);
1542 * Removes the given post from the bookmarks.
1545 * The post to unbookmark
1547 public void unbookmark(Post post) {
1548 unbookmarkPost(post.getId());
1552 * Removes the post with the given ID from the bookmarks.
1555 * The ID of the post to unbookmark
1557 public void unbookmarkPost(String id) {
1558 synchronized (bookmarkedPosts) {
1559 bookmarkedPosts.remove(id);
1564 * Creates a new reply.
1567 * The Sone that creates the reply
1569 * The post that this reply refers to
1571 * The text of the reply
1572 * @return The created reply
1574 public PostReply createReply(Sone sone, Post post, String text) {
1575 checkNotNull(text, "text must not be null");
1576 checkArgument(text.trim().length() > 0, "text must not be empty");
1577 if (!sone.isLocal()) {
1578 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1581 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1582 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1583 final PostReply reply = postReplyBuilder.build();
1584 synchronized (replies) {
1585 replies.put(reply.getId(), reply);
1587 synchronized (knownReplies) {
1588 eventBus.post(new NewPostReplyFoundEvent(reply));
1590 sone.addReply(reply);
1591 touchConfiguration();
1592 localElementTicker.schedule(new Runnable() {
1599 markReplyKnown(reply);
1601 }, 10, TimeUnit.SECONDS);
1606 * Deletes the given reply.
1609 * The reply to delete
1611 public void deleteReply(PostReply reply) {
1612 Sone sone = reply.getSone();
1613 if (!sone.isLocal()) {
1614 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1617 synchronized (replies) {
1618 replies.remove(reply.getId());
1620 synchronized (knownReplies) {
1621 markReplyKnown(reply);
1622 knownReplies.remove(reply.getId());
1624 sone.removeReply(reply);
1625 touchConfiguration();
1629 * Marks the given reply as known, if it is currently not a known reply
1630 * (according to {@link Reply#isKnown()}).
1633 * The reply to mark as known
1635 public void markReplyKnown(PostReply reply) {
1636 reply.setKnown(true);
1637 synchronized (knownReplies) {
1638 eventBus.post(new MarkPostReplyKnownEvent(reply));
1639 if (knownReplies.add(reply.getId())) {
1640 touchConfiguration();
1646 * Creates a new top-level album for the given Sone.
1649 * The Sone to create the album for
1650 * @return The new album
1652 public Album createAlbum(Sone sone) {
1653 return createAlbum(sone, null);
1657 * Creates a new album for the given Sone.
1660 * The Sone to create the album for
1662 * The parent of the album (may be {@code null} to create a
1664 * @return The new album
1666 public Album createAlbum(Sone sone, Album parent) {
1667 Album album = new Album();
1668 synchronized (albums) {
1669 albums.put(album.getId(), album);
1671 album.setSone(sone);
1672 if (parent != null) {
1673 parent.addAlbum(album);
1675 sone.addAlbum(album);
1681 * Deletes the given album. The owner of the album has to be a local Sone,
1682 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1685 * The album to remove
1687 public void deleteAlbum(Album album) {
1688 checkNotNull(album, "album must not be null");
1689 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1690 if (!album.isEmpty()) {
1693 if (album.getParent() == null) {
1694 album.getSone().removeAlbum(album);
1696 album.getParent().removeAlbum(album);
1698 synchronized (albums) {
1699 albums.remove(album.getId());
1701 touchConfiguration();
1705 * Creates a new image.
1708 * The Sone creating the image
1710 * The album the image will be inserted into
1711 * @param temporaryImage
1712 * The temporary image to create the image from
1713 * @return The newly created image
1715 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1716 checkNotNull(sone, "sone must not be null");
1717 checkNotNull(album, "album must not be null");
1718 checkNotNull(temporaryImage, "temporaryImage must not be null");
1719 checkArgument(sone.isLocal(), "sone must be a local Sone");
1720 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1721 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1722 album.addImage(image);
1723 synchronized (images) {
1724 images.put(image.getId(), image);
1726 imageInserter.insertImage(temporaryImage, image);
1731 * Deletes the given image. This method will also delete a matching
1734 * @see #deleteTemporaryImage(TemporaryImage)
1736 * The image to delete
1738 public void deleteImage(Image image) {
1739 checkNotNull(image, "image must not be null");
1740 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1741 deleteTemporaryImage(image.getId());
1742 image.getAlbum().removeImage(image);
1743 synchronized (images) {
1744 images.remove(image.getId());
1746 touchConfiguration();
1750 * Creates a new temporary image.
1753 * The MIME type of the temporary image
1755 * The encoded data of the image
1756 * @return The temporary image
1758 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1759 TemporaryImage temporaryImage = new TemporaryImage();
1760 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1761 synchronized (temporaryImages) {
1762 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1764 return temporaryImage;
1768 * Deletes the given temporary image.
1770 * @param temporaryImage
1771 * The temporary image to delete
1773 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1774 checkNotNull(temporaryImage, "temporaryImage must not be null");
1775 deleteTemporaryImage(temporaryImage.getId());
1779 * Deletes the temporary image with the given ID.
1782 * The ID of the temporary image to delete
1784 public void deleteTemporaryImage(String imageId) {
1785 checkNotNull(imageId, "imageId must not be null");
1786 synchronized (temporaryImages) {
1787 temporaryImages.remove(imageId);
1789 Image image = getImage(imageId, false);
1790 if (image != null) {
1791 imageInserter.cancelImageInsert(image);
1796 * Notifies the core that the configuration, either of the core or of a
1797 * single local Sone, has changed, and that the configuration should be
1800 public void touchConfiguration() {
1801 lastConfigurationUpdate = System.currentTimeMillis();
1812 public void serviceStart() {
1813 loadConfiguration();
1814 updateChecker.start();
1815 identityManager.start();
1816 webOfTrustUpdater.init();
1817 webOfTrustUpdater.start();
1824 public void serviceRun() {
1825 long lastSaved = System.currentTimeMillis();
1826 while (!shouldStop()) {
1828 long now = System.currentTimeMillis();
1829 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1830 for (Sone localSone : getLocalSones()) {
1831 saveSone(localSone);
1833 saveConfiguration();
1843 public void serviceStop() {
1844 localElementTicker.shutdownNow();
1845 synchronized (sones) {
1846 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1847 soneInserter.getValue().stop();
1848 saveSone(soneInserter.getKey());
1851 saveConfiguration();
1852 webOfTrustUpdater.stop();
1853 updateChecker.stop();
1854 soneDownloader.stop();
1855 soneDownloaders.shutdown();
1856 identityManager.stop();
1864 * Saves the given Sone. This will persist all local settings for the given
1865 * Sone, such as the friends list and similar, private options.
1870 private synchronized void saveSone(Sone sone) {
1871 if (!sone.isLocal()) {
1872 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1875 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1876 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1880 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1882 /* save Sone into configuration. */
1883 String sonePrefix = "Sone/" + sone.getId();
1884 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1885 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1888 Profile profile = sone.getProfile();
1889 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1890 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1891 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1892 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1893 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1894 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1895 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1897 /* save profile fields. */
1898 int fieldCounter = 0;
1899 for (Field profileField : profile.getFields()) {
1900 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1901 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1902 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1904 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1907 int postCounter = 0;
1908 for (Post post : sone.getPosts()) {
1909 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1910 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1911 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1912 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1913 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1915 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1918 int replyCounter = 0;
1919 for (PostReply reply : sone.getReplies()) {
1920 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1921 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1922 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1923 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1924 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1926 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1928 /* save post likes. */
1929 int postLikeCounter = 0;
1930 for (String postId : sone.getLikedPostIds()) {
1931 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1933 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1935 /* save reply likes. */
1936 int replyLikeCounter = 0;
1937 for (String replyId : sone.getLikedReplyIds()) {
1938 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1940 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1943 int friendCounter = 0;
1944 for (String friendId : sone.getFriends()) {
1945 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1947 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1949 /* save albums. first, collect in a flat structure, top-level first. */
1950 List<Album> albums = sone.getAllAlbums();
1952 int albumCounter = 0;
1953 for (Album album : albums) {
1954 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1955 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1956 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1957 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1958 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1959 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1961 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1964 int imageCounter = 0;
1965 for (Album album : albums) {
1966 for (Image image : album.getImages()) {
1967 if (!image.isInserted()) {
1970 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1971 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1972 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1973 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1974 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1975 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1976 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1977 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1978 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1981 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1984 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1985 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1986 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1987 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1988 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1989 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1991 configuration.save();
1993 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1995 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1996 } catch (ConfigurationException ce1) {
1997 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2002 * Saves the current options.
2004 private void saveConfiguration() {
2005 synchronized (configuration) {
2006 if (storingConfiguration) {
2007 logger.log(Level.FINE, "Already storing configuration…");
2010 storingConfiguration = true;
2013 /* store the options first. */
2015 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2016 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2017 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2018 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2019 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2020 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2021 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2022 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2023 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2024 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2025 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2026 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2028 /* save known Sones. */
2029 int soneCounter = 0;
2030 synchronized (knownSones) {
2031 for (String knownSoneId : knownSones) {
2032 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2034 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2037 /* save Sone following times. */
2039 synchronized (soneFollowingTimes) {
2040 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2041 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
2042 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2045 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2048 /* save known posts. */
2049 int postCounter = 0;
2050 synchronized (knownPosts) {
2051 for (String knownPostId : knownPosts) {
2052 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2054 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2057 /* save known replies. */
2058 int replyCounter = 0;
2059 synchronized (knownReplies) {
2060 for (String knownReplyId : knownReplies) {
2061 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2063 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2066 /* save bookmarked posts. */
2067 int bookmarkedPostCounter = 0;
2068 synchronized (bookmarkedPosts) {
2069 for (String bookmarkedPostId : bookmarkedPosts) {
2070 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2073 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2076 configuration.save();
2078 } catch (ConfigurationException ce1) {
2079 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2081 synchronized (configuration) {
2082 storingConfiguration = false;
2088 * Loads the configuration.
2090 private void loadConfiguration() {
2091 /* create options. */
2092 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2095 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2096 SoneInserter.setInsertionDelay(newValue);
2100 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2101 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2102 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2103 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2104 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2105 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2106 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2107 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2108 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2111 @SuppressWarnings("synthetic-access")
2112 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2113 fcpInterface.setActive(newValue);
2116 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2119 @SuppressWarnings("synthetic-access")
2120 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2121 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2126 loadConfigurationValue("InsertionDelay");
2127 loadConfigurationValue("PostsPerPage");
2128 loadConfigurationValue("ImagesPerPage");
2129 loadConfigurationValue("CharactersPerPost");
2130 loadConfigurationValue("PostCutOffLength");
2131 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2132 loadConfigurationValue("PositiveTrust");
2133 loadConfigurationValue("NegativeTrust");
2134 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2135 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2136 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2138 /* load known Sones. */
2139 int soneCounter = 0;
2141 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2142 if (knownSoneId == null) {
2145 synchronized (knownSones) {
2146 knownSones.add(knownSoneId);
2150 /* load Sone following times. */
2153 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2154 if (soneId == null) {
2157 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2158 synchronized (soneFollowingTimes) {
2159 soneFollowingTimes.put(soneId, time);
2164 /* load known posts. */
2165 int postCounter = 0;
2167 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2168 if (knownPostId == null) {
2171 synchronized (knownPosts) {
2172 knownPosts.add(knownPostId);
2176 /* load known replies. */
2177 int replyCounter = 0;
2179 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2180 if (knownReplyId == null) {
2183 synchronized (knownReplies) {
2184 knownReplies.add(knownReplyId);
2188 /* load bookmarked posts. */
2189 int bookmarkedPostCounter = 0;
2191 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2192 if (bookmarkedPostId == null) {
2195 synchronized (bookmarkedPosts) {
2196 bookmarkedPosts.add(bookmarkedPostId);
2203 * Loads an {@link Integer} configuration value for the option with the
2204 * given name, logging validation failures.
2207 * The name of the option to load
2209 private void loadConfigurationValue(String optionName) {
2211 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2212 } catch (IllegalArgumentException iae1) {
2213 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2218 * Notifies the core that a new {@link OwnIdentity} was added.
2220 * @param ownIdentityAddedEvent
2224 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2225 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2226 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2227 if (ownIdentity.hasContext("Sone")) {
2228 addLocalSone(ownIdentity);
2233 * Notifies the core that an {@link OwnIdentity} was removed.
2235 * @param ownIdentityRemovedEvent
2239 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2240 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2241 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2242 trustedIdentities.remove(ownIdentity);
2246 * Notifies the core that a new {@link Identity} was added.
2248 * @param identityAddedEvent
2252 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2253 Identity identity = identityAddedEvent.identity();
2254 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2255 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2256 addRemoteSone(identity);
2260 * Notifies the core that an {@link Identity} was updated.
2262 * @param identityUpdatedEvent
2266 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2267 final Identity identity = identityUpdatedEvent.identity();
2268 soneDownloaders.execute(new Runnable() {
2271 @SuppressWarnings("synthetic-access")
2273 Sone sone = getRemoteSone(identity.getId(), false);
2274 sone.setIdentity(identity);
2275 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2276 soneDownloader.addSone(sone);
2277 soneDownloader.fetchSone(sone);
2283 * Notifies the core that an {@link Identity} was removed.
2285 * @param identityRemovedEvent
2289 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2290 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2291 Identity identity = identityRemovedEvent.identity();
2292 trustedIdentities.get(ownIdentity).remove(identity);
2293 boolean foundIdentity = false;
2294 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2295 if (trustedIdentity.getKey().equals(ownIdentity)) {
2298 if (trustedIdentity.getValue().contains(identity)) {
2299 foundIdentity = true;
2302 if (foundIdentity) {
2303 /* some local identity still trusts this identity, don’t remove. */
2306 Optional<Sone> sone = getSone(identity.getId());
2307 if (!sone.isPresent()) {
2308 /* TODO - we don’t have the Sone anymore. should this happen? */
2311 synchronized (posts) {
2312 synchronized (knownPosts) {
2313 for (Post post : sone.get().getPosts()) {
2314 posts.remove(post.getId());
2315 eventBus.post(new PostRemovedEvent(post));
2319 synchronized (replies) {
2320 synchronized (knownReplies) {
2321 for (PostReply reply : sone.get().getReplies()) {
2322 replies.remove(reply.getId());
2323 eventBus.post(new PostReplyRemovedEvent(reply));
2327 synchronized (sones) {
2328 sones.remove(identity.getId());
2330 eventBus.post(new SoneRemovedEvent(sone.get()));
2334 * Deletes the temporary image.
2336 * @param imageInsertFinishedEvent
2340 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2341 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2342 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2343 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2344 touchConfiguration();