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.PostBuilder;
60 import net.pterodactylus.sone.data.PostBuilderFactory;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.PostReplyBuilder;
63 import net.pterodactylus.sone.data.PostReplyBuilderFactory;
64 import net.pterodactylus.sone.data.Profile;
65 import net.pterodactylus.sone.data.Profile.Field;
66 import net.pterodactylus.sone.data.Reply;
67 import net.pterodactylus.sone.data.Sone;
68 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
69 import net.pterodactylus.sone.data.Sone.SoneStatus;
70 import net.pterodactylus.sone.data.TemporaryImage;
71 import net.pterodactylus.sone.fcp.FcpInterface;
72 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
73 import net.pterodactylus.sone.freenet.wot.Identity;
74 import net.pterodactylus.sone.freenet.wot.IdentityManager;
75 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
81 import net.pterodactylus.sone.main.SonePlugin;
82 import net.pterodactylus.sone.utils.IntegerRangePredicate;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.logging.Logging;
86 import net.pterodactylus.util.number.Numbers;
87 import net.pterodactylus.util.service.AbstractService;
88 import net.pterodactylus.util.thread.NamedThreadFactory;
90 import com.google.common.base.Function;
91 import com.google.common.base.Optional;
92 import com.google.common.base.Predicate;
93 import com.google.common.base.Predicates;
94 import com.google.common.collect.Collections2;
95 import com.google.common.collect.FluentIterable;
96 import com.google.common.collect.Ordering;
97 import com.google.common.eventbus.EventBus;
98 import com.google.common.eventbus.Subscribe;
99 import com.google.inject.Inject;
101 import freenet.keys.FreenetURI;
106 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
108 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
111 private static final Logger logger = Logging.getLogger(Core.class);
113 /** The start time. */
114 private final long startupTime = System.currentTimeMillis();
117 private final Options options = new Options();
119 /** The preferences. */
120 private final Preferences preferences = new Preferences(options);
122 /** The event bus. */
123 private final EventBus eventBus;
125 /** The configuration. */
126 private Configuration configuration;
128 /** Whether we’re currently saving the configuration. */
129 private boolean storingConfiguration = false;
131 /** The identity manager. */
132 private final IdentityManager identityManager;
134 /** Interface to freenet. */
135 private final FreenetInterface freenetInterface;
137 /** The Sone downloader. */
138 private final SoneDownloader soneDownloader;
140 /** The image inserter. */
141 private final ImageInserter imageInserter;
143 /** Sone downloader thread-pool. */
144 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
146 /** The update checker. */
147 private final UpdateChecker updateChecker;
149 /** The trust updater. */
150 private final WebOfTrustUpdater webOfTrustUpdater;
152 /** The FCP interface. */
153 private volatile FcpInterface fcpInterface;
155 /** The times Sones were followed. */
156 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
158 /** Locked local Sones. */
159 /* synchronize on itself. */
160 private final Set<Sone> lockedSones = new HashSet<Sone>();
162 /** Sone inserters. */
163 /* synchronize access on this on sones. */
164 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
166 /** Sone rescuers. */
167 /* synchronize access on this on sones. */
168 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
171 /* synchronize access on this on itself. */
172 private final Map<String, Sone> sones = new HashMap<String, Sone>();
174 /** All known Sones. */
175 private final Set<String> knownSones = new HashSet<String>();
177 /** The post builder. */
178 private final PostBuilderFactory postBuilderFactory;
181 private final Map<String, Post> posts = new HashMap<String, Post>();
183 /** All known posts. */
184 private final Set<String> knownPosts = new HashSet<String>();
186 /** The post reply builder factory. */
187 private final PostReplyBuilderFactory postReplyBuilderFactory;
190 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
192 /** All known replies. */
193 private final Set<String> knownReplies = new HashSet<String>();
195 /** All bookmarked posts. */
196 /* synchronize access on itself. */
197 private final Set<String> bookmarkedPosts = new HashSet<String>();
199 /** Trusted identities, sorted by own identities. */
200 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
202 /** All known albums. */
203 private final Map<String, Album> albums = new HashMap<String, Album>();
205 /** All known images. */
206 private final Map<String, Image> images = new HashMap<String, Image>();
208 /** All temporary images. */
209 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
211 /** Ticker for threads that mark own elements as known. */
212 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
214 /** The time the configuration was last touched. */
215 private volatile long lastConfigurationUpdate;
218 * Creates a new core.
220 * @param configuration
221 * The configuration of the core
222 * @param freenetInterface
223 * The freenet interface
224 * @param identityManager
225 * The identity manager
226 * @param webOfTrustUpdater
227 * The WebOfTrust updater
230 * @param postBuilderFactory
232 * @param postReplyBuilderFactory
233 * The post reply builder factory
236 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
238 this.configuration = configuration;
239 this.freenetInterface = freenetInterface;
240 this.identityManager = identityManager;
241 this.soneDownloader = new SoneDownloader(this, freenetInterface);
242 this.imageInserter = new ImageInserter(freenetInterface);
243 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
244 this.webOfTrustUpdater = webOfTrustUpdater;
245 this.eventBus = eventBus;
246 this.postBuilderFactory = postBuilderFactory;
247 this.postReplyBuilderFactory = postReplyBuilderFactory;
255 * Returns the time Sone was started.
257 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
259 public long getStartupTime() {
264 * Sets the configuration to use. This will automatically save the current
265 * configuration to the given configuration.
267 * @param configuration
268 * The new configuration to use
270 public void setConfiguration(Configuration configuration) {
271 this.configuration = configuration;
272 touchConfiguration();
276 * Returns the options used by the core.
278 * @return The options of the core
280 public Preferences getPreferences() {
285 * Returns the identity manager used by the core.
287 * @return The identity manager
289 public IdentityManager getIdentityManager() {
290 return identityManager;
294 * Returns the update checker.
296 * @return The update checker
298 public UpdateChecker getUpdateChecker() {
299 return updateChecker;
303 * Sets the FCP interface to use.
305 * @param fcpInterface
306 * The FCP interface to use
308 public void setFcpInterface(FcpInterface fcpInterface) {
309 this.fcpInterface = fcpInterface;
313 * Returns the Sone rescuer for the given local Sone.
316 * The local Sone to get the rescuer for
317 * @return The Sone rescuer for the given Sone
319 public SoneRescuer getSoneRescuer(Sone sone) {
320 checkNotNull(sone, "sone must not be null");
321 checkArgument(sone.isLocal(), "sone must be local");
322 synchronized (sones) {
323 SoneRescuer soneRescuer = soneRescuers.get(sone);
324 if (soneRescuer == null) {
325 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
326 soneRescuers.put(sone, soneRescuer);
334 * Returns whether the given Sone is currently locked.
338 * @return {@code true} if the Sone is locked, {@code false} if it is not
340 public boolean isLocked(Sone sone) {
341 synchronized (lockedSones) {
342 return lockedSones.contains(sone);
347 * Returns all Sones, remote and local.
351 public Set<Sone> getSones() {
352 return new HashSet<Sone>(sones.values());
356 * Returns the Sone with the given ID, regardless whether it’s local or
360 * The ID of the Sone to get
361 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id) {
365 return getSone(id, true);
369 * Returns the Sone with the given ID, regardless whether it’s local or
373 * The ID of the Sone to get
375 * {@code true} to create a new Sone if none exists,
376 * {@code false} to return {@code null} if a Sone with the given
378 * @return The Sone with the given ID, or {@code null} if there is no such
382 public Sone getSone(String id, boolean create) {
383 synchronized (sones) {
384 if (!sones.containsKey(id) && create) {
385 Sone sone = new Sone(id, false);
388 return sones.get(id);
393 * Checks whether the core knows a Sone with the given ID.
397 * @return {@code true} if there is a Sone with the given ID, {@code false}
400 public boolean hasSone(String id) {
401 synchronized (sones) {
402 return sones.containsKey(id);
407 * Returns all local Sones.
409 * @return All local Sones
411 public Collection<Sone> getLocalSones() {
412 synchronized (sones) {
413 return Collections2.filter(sones.values(), new Predicate<Sone>() {
416 public boolean apply(Sone sone) {
417 return sone.isLocal();
424 * Returns the local Sone with the given ID, optionally creating a new Sone.
429 * {@code true} to create a new Sone if none exists,
430 * {@code false} to return null if none exists
431 * @return The Sone with the given ID, or {@code null}
433 public Sone getLocalSone(String id, boolean create) {
434 synchronized (sones) {
435 Sone sone = sones.get(id);
436 if ((sone == null) && create) {
437 sone = new Sone(id, true);
440 if ((sone != null) && !sone.isLocal()) {
441 sone = new Sone(id, true);
449 * Returns all remote Sones.
451 * @return All remote Sones
453 public Collection<Sone> getRemoteSones() {
454 synchronized (sones) {
455 return Collections2.filter(sones.values(), new Predicate<Sone>() {
458 public boolean apply(Sone sone) {
459 return !sone.isLocal();
466 * Returns the remote Sone with the given ID.
469 * The ID of the remote Sone to get
471 * {@code true} to always create a Sone, {@code false} to return
472 * {@code null} if no Sone with the given ID exists
473 * @return The Sone with the given ID
475 public Sone getRemoteSone(String id, boolean create) {
476 synchronized (sones) {
477 Sone sone = sones.get(id);
478 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
479 sone = new Sone(id, false);
487 * Returns whether the given Sone has been modified.
490 * The Sone to check for modifications
491 * @return {@code true} if a modification has been detected in the Sone,
492 * {@code false} otherwise
494 public boolean isModifiedSone(Sone sone) {
495 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
499 * Returns the time when the given was first followed by any local Sone.
502 * The Sone to get the time for
503 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
504 * been followed, or {@link Long#MAX_VALUE}
506 public long getSoneFollowingTime(Sone sone) {
507 synchronized (soneFollowingTimes) {
508 if (soneFollowingTimes.containsKey(sone)) {
509 return soneFollowingTimes.get(sone);
511 return Long.MAX_VALUE;
516 * Returns whether the target Sone is trusted by the origin Sone.
522 * @return {@code true} if the target Sone is trusted by the origin Sone
524 public boolean isSoneTrusted(Sone origin, Sone target) {
525 checkNotNull(origin, "origin must not be null");
526 checkNotNull(target, "target must not be null");
527 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
528 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
532 * Returns a post builder.
534 * @return A new post builder
536 public PostBuilder postBuilder() {
537 return postBuilderFactory.newPostBuilder();
544 public Optional<Post> getPost(String postId) {
545 synchronized (posts) {
546 return Optional.fromNullable(posts.get(postId));
551 * Returns all posts that have the given Sone as recipient.
553 * @see Post#getRecipient()
555 * The recipient of the posts
556 * @return All posts that have the given Sone as recipient
558 public Set<Post> getDirectedPosts(Sone recipient) {
559 checkNotNull(recipient, "recipient must not be null");
560 Set<Post> directedPosts = new HashSet<Post>();
561 synchronized (posts) {
562 for (Post post : posts.values()) {
563 if (recipient.equals(post.getRecipient())) {
564 directedPosts.add(post);
568 return directedPosts;
572 * Returns a post reply builder.
574 * @return A new post reply builder
576 public PostReplyBuilder postReplyBuilder() {
577 return postReplyBuilderFactory.newPostReplyBuilder();
584 public Optional<PostReply> getPostReply(String replyId) {
585 synchronized (replies) {
586 return Optional.fromNullable(replies.get(replyId));
594 public List<PostReply> getReplies(final Post post) {
595 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function<Sone, Iterable<PostReply>>() {
598 public Iterable<PostReply> apply(Sone sone) {
599 return sone.getReplies();
601 }).filter(new Predicate<PostReply>() {
604 public boolean apply(PostReply reply) {
605 return post.getId().equals(reply.getPostId());
611 * Returns all Sones that have liked the given post.
614 * The post to get the liking Sones for
615 * @return The Sones that like the given post
617 public Set<Sone> getLikes(Post post) {
618 Set<Sone> sones = new HashSet<Sone>();
619 for (Sone sone : getSones()) {
620 if (sone.getLikedPostIds().contains(post.getId())) {
628 * Returns all Sones that have liked the given reply.
631 * The reply to get the liking Sones for
632 * @return The Sones that like the given reply
634 public Set<Sone> getLikes(PostReply reply) {
635 Set<Sone> sones = new HashSet<Sone>();
636 for (Sone sone : getSones()) {
637 if (sone.getLikedReplyIds().contains(reply.getId())) {
645 * Returns whether the given post is bookmarked.
649 * @return {@code true} if the given post is bookmarked, {@code false}
652 public boolean isBookmarked(Post post) {
653 return isPostBookmarked(post.getId());
657 * Returns whether the post with the given ID is bookmarked.
660 * The ID of the post to check
661 * @return {@code true} if the post with the given ID is bookmarked,
662 * {@code false} otherwise
664 public boolean isPostBookmarked(String id) {
665 synchronized (bookmarkedPosts) {
666 return bookmarkedPosts.contains(id);
671 * Returns all currently known bookmarked posts.
673 * @return All bookmarked posts
675 public Set<Post> getBookmarkedPosts() {
676 Set<Post> posts = new HashSet<Post>();
677 synchronized (bookmarkedPosts) {
678 for (String bookmarkedPostId : bookmarkedPosts) {
679 Optional<Post> post = getPost(bookmarkedPostId);
680 if (!post.isPresent()) {
681 posts.add(post.get());
689 * Returns the album with the given ID, creating a new album if no album
690 * with the given ID can be found.
693 * The ID of the album
694 * @return The album with the given ID
696 public Album getAlbum(String albumId) {
697 return getAlbum(albumId, true);
701 * Returns the album with the given ID, optionally creating a new album if
702 * an album with the given ID can not be found.
705 * The ID of the album
707 * {@code true} to create a new album if none exists for the
709 * @return The album with the given ID, or {@code null} if no album with the
710 * given ID exists and {@code create} is {@code false}
712 public Album getAlbum(String albumId, boolean create) {
713 synchronized (albums) {
714 Album album = albums.get(albumId);
715 if (create && (album == null)) {
716 album = new Album(albumId);
717 albums.put(albumId, album);
724 * Returns the image with the given ID, creating it if necessary.
727 * The ID of the image
728 * @return The image with the given ID
730 public Image getImage(String imageId) {
731 return getImage(imageId, true);
735 * Returns the image with the given ID, optionally creating it if it does
739 * The ID of the image
741 * {@code true} to create an image if none exists with the given
743 * @return The image with the given ID, or {@code null} if none exists and
746 public Image getImage(String imageId, boolean create) {
747 synchronized (images) {
748 Image image = images.get(imageId);
749 if (create && (image == null)) {
750 image = new Image(imageId);
751 images.put(imageId, image);
758 * Returns the temporary image with the given ID.
761 * The ID of the temporary image
762 * @return The temporary image, or {@code null} if there is no temporary
763 * image with the given ID
765 public TemporaryImage getTemporaryImage(String imageId) {
766 synchronized (temporaryImages) {
767 return temporaryImages.get(imageId);
776 * Locks the given Sone. A locked Sone will not be inserted by
777 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
783 public void lockSone(Sone sone) {
784 synchronized (lockedSones) {
785 if (lockedSones.add(sone)) {
786 eventBus.post(new SoneLockedEvent(sone));
792 * Unlocks the given Sone.
794 * @see #lockSone(Sone)
798 public void unlockSone(Sone sone) {
799 synchronized (lockedSones) {
800 if (lockedSones.remove(sone)) {
801 eventBus.post(new SoneUnlockedEvent(sone));
807 * Adds a local Sone from the given own identity.
810 * The own identity to create a Sone from
811 * @return The added (or already existing) Sone
813 public Sone addLocalSone(OwnIdentity ownIdentity) {
814 if (ownIdentity == null) {
815 logger.log(Level.WARNING, "Given OwnIdentity is null!");
818 synchronized (sones) {
821 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
822 } catch (MalformedURLException mue1) {
823 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
826 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
827 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
829 /* TODO - load posts ’n stuff */
830 sones.put(ownIdentity.getId(), sone);
831 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
832 soneInserters.put(sone, soneInserter);
833 sone.setStatus(SoneStatus.idle);
835 soneInserter.start();
841 * Creates a new Sone for the given own identity.
844 * The own identity to create a Sone for
845 * @return The created Sone
847 public Sone createSone(OwnIdentity ownIdentity) {
848 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
849 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
852 Sone sone = addLocalSone(ownIdentity);
853 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
854 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
855 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
856 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
857 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
858 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
860 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
861 touchConfiguration();
866 * Adds the Sone of the given identity.
869 * The identity whose Sone to add
870 * @return The added or already existing Sone
872 public Sone addRemoteSone(Identity identity) {
873 if (identity == null) {
874 logger.log(Level.WARNING, "Given Identity is null!");
877 synchronized (sones) {
878 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
879 boolean newSone = sone.getRequestUri() == null;
880 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
881 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
883 synchronized (knownSones) {
884 newSone = !knownSones.contains(sone.getId());
886 sone.setKnown(!newSone);
888 eventBus.post(new NewSoneFoundEvent(sone));
889 for (Sone localSone : getLocalSones()) {
890 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
891 followSone(localSone, sone);
896 soneDownloader.addSone(sone);
897 soneDownloaders.execute(new Runnable() {
900 @SuppressWarnings("synthetic-access")
902 soneDownloader.fetchSone(sone, sone.getRequestUri());
911 * Lets the given local Sone follow the Sone with the given ID.
914 * The local Sone that should follow another Sone
916 * The ID of the Sone to follow
918 public void followSone(Sone sone, String soneId) {
919 checkNotNull(sone, "sone must not be null");
920 checkNotNull(soneId, "soneId must not be null");
921 Sone followedSone = getSone(soneId, true);
922 if (followedSone == null) {
923 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
926 followSone(sone, getSone(soneId));
930 * Lets the given local Sone follow the other given Sone. If the given Sone
931 * was not followed by any local Sone before, this will mark all elements of
932 * the followed Sone as read that have been created before the current
936 * The local Sone that should follow the other Sone
937 * @param followedSone
938 * The Sone that should be followed
940 public void followSone(Sone sone, Sone followedSone) {
941 checkNotNull(sone, "sone must not be null");
942 checkNotNull(followedSone, "followedSone must not be null");
943 sone.addFriend(followedSone.getId());
944 synchronized (soneFollowingTimes) {
945 if (!soneFollowingTimes.containsKey(followedSone)) {
946 long now = System.currentTimeMillis();
947 soneFollowingTimes.put(followedSone, now);
948 for (Post post : followedSone.getPosts()) {
949 if (post.getTime() < now) {
953 for (PostReply reply : followedSone.getReplies()) {
954 if (reply.getTime() < now) {
955 markReplyKnown(reply);
960 touchConfiguration();
964 * Lets the given local Sone unfollow the Sone with the given ID.
967 * The local Sone that should unfollow another Sone
969 * The ID of the Sone being unfollowed
971 public void unfollowSone(Sone sone, String soneId) {
972 checkNotNull(sone, "sone must not be null");
973 checkNotNull(soneId, "soneId must not be null");
974 unfollowSone(sone, getSone(soneId, false));
978 * Lets the given local Sone unfollow the other given Sone. If the given
979 * local Sone is the last local Sone that followed the given Sone, its
980 * following time will be removed.
983 * The local Sone that should unfollow another Sone
984 * @param unfollowedSone
985 * The Sone being unfollowed
987 public void unfollowSone(Sone sone, Sone unfollowedSone) {
988 checkNotNull(sone, "sone must not be null");
989 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
990 sone.removeFriend(unfollowedSone.getId());
991 boolean unfollowedSoneStillFollowed = false;
992 for (Sone localSone : getLocalSones()) {
993 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
995 if (!unfollowedSoneStillFollowed) {
996 synchronized (soneFollowingTimes) {
997 soneFollowingTimes.remove(unfollowedSone);
1000 touchConfiguration();
1004 * Sets the trust value of the given origin Sone for the target Sone.
1011 * The trust value (from {@code -100} to {@code 100})
1013 public void setTrust(Sone origin, Sone target, int trustValue) {
1014 checkNotNull(origin, "origin must not be null");
1015 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1016 checkNotNull(target, "target must not be null");
1017 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1018 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1022 * Removes any trust assignment for the given target Sone.
1029 public void removeTrust(Sone origin, Sone target) {
1030 checkNotNull(origin, "origin must not be null");
1031 checkNotNull(target, "target must not be null");
1032 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1033 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1037 * Assigns the configured positive trust value for the given target.
1044 public void trustSone(Sone origin, Sone target) {
1045 setTrust(origin, target, preferences.getPositiveTrust());
1049 * Assigns the configured negative trust value for the given target.
1056 public void distrustSone(Sone origin, Sone target) {
1057 setTrust(origin, target, preferences.getNegativeTrust());
1061 * Removes the trust assignment for the given target.
1068 public void untrustSone(Sone origin, Sone target) {
1069 removeTrust(origin, target);
1073 * Updates the stored Sone with the given Sone.
1078 public void updateSone(Sone sone) {
1079 updateSone(sone, false);
1083 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1084 * {@code true}, an older Sone than the current Sone can be given to restore
1088 * The Sone to update
1089 * @param soneRescueMode
1090 * {@code true} if the stored Sone should be updated regardless
1091 * of the age of the given Sone
1093 public void updateSone(Sone sone, boolean soneRescueMode) {
1094 if (hasSone(sone.getId())) {
1095 Sone storedSone = getSone(sone.getId());
1096 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1097 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1100 synchronized (posts) {
1101 if (!soneRescueMode) {
1102 for (Post post : storedSone.getPosts()) {
1103 posts.remove(post.getId());
1104 if (!sone.getPosts().contains(post)) {
1105 eventBus.post(new PostRemovedEvent(post));
1109 List<Post> storedPosts = storedSone.getPosts();
1110 synchronized (knownPosts) {
1111 for (Post post : sone.getPosts()) {
1112 post.setKnown(knownPosts.contains(post.getId()));
1113 if (!storedPosts.contains(post)) {
1114 if (post.getTime() < getSoneFollowingTime(sone)) {
1115 knownPosts.add(post.getId());
1116 post.setKnown(true);
1117 } else if (!knownPosts.contains(post.getId())) {
1118 eventBus.post(new NewPostFoundEvent(post));
1121 posts.put(post.getId(), post);
1125 synchronized (replies) {
1126 if (!soneRescueMode) {
1127 for (PostReply reply : storedSone.getReplies()) {
1128 replies.remove(reply.getId());
1129 if (!sone.getReplies().contains(reply)) {
1130 eventBus.post(new PostReplyRemovedEvent(reply));
1134 Set<PostReply> storedReplies = storedSone.getReplies();
1135 synchronized (knownReplies) {
1136 for (PostReply reply : sone.getReplies()) {
1137 reply.setKnown(knownReplies.contains(reply.getId()));
1138 if (!storedReplies.contains(reply)) {
1139 if (reply.getTime() < getSoneFollowingTime(sone)) {
1140 knownReplies.add(reply.getId());
1141 reply.setKnown(true);
1142 } else if (!knownReplies.contains(reply.getId())) {
1143 eventBus.post(new NewPostReplyFoundEvent(reply));
1146 replies.put(reply.getId(), reply);
1150 synchronized (albums) {
1151 synchronized (images) {
1152 for (Album album : storedSone.getAlbums()) {
1153 albums.remove(album.getId());
1154 for (Image image : album.getImages()) {
1155 images.remove(image.getId());
1158 for (Album album : sone.getAlbums()) {
1159 albums.put(album.getId(), album);
1160 for (Image image : album.getImages()) {
1161 images.put(image.getId(), image);
1166 synchronized (sones) {
1167 sones.put(sone.getId(), sone);
1173 * Deletes the given Sone. This will remove the Sone from the
1174 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1175 * remove the context from its identity.
1178 * The Sone to delete
1180 public void deleteSone(Sone sone) {
1181 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1182 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1185 synchronized (sones) {
1186 if (!getLocalSones().contains(sone)) {
1187 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1190 sones.remove(sone.getId());
1191 SoneInserter soneInserter = soneInserters.remove(sone);
1192 soneInserter.stop();
1194 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1195 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1197 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1198 } catch (ConfigurationException ce1) {
1199 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1204 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1205 * known} before, a {@link MarkSoneKnownEvent} is fired.
1208 * The Sone to mark as known
1210 public void markSoneKnown(Sone sone) {
1211 if (!sone.isKnown()) {
1212 sone.setKnown(true);
1213 synchronized (knownSones) {
1214 knownSones.add(sone.getId());
1216 eventBus.post(new MarkSoneKnownEvent(sone));
1217 touchConfiguration();
1222 * Loads and updates the given Sone from the configuration. If any error is
1223 * encountered, loading is aborted and the given Sone is not changed.
1226 * The Sone to load and update
1228 public void loadSone(Sone sone) {
1229 if (!sone.isLocal()) {
1230 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1234 /* initialize options. */
1235 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1236 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1237 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1238 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1239 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1240 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1243 String sonePrefix = "Sone/" + sone.getId();
1244 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1245 if (soneTime == null) {
1246 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1249 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1252 Profile profile = new Profile(sone);
1253 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1254 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1255 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1256 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1257 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1258 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1260 /* load profile fields. */
1262 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1263 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1264 if (fieldName == null) {
1267 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1268 profile.addField(fieldName).setValue(fieldValue);
1272 Set<Post> posts = new HashSet<Post>();
1274 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1275 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1276 if (postId == null) {
1279 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1280 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1281 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1282 if ((postTime == 0) || (postText == null)) {
1283 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1286 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1287 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1288 postBuilder.to(postRecipientId);
1290 posts.add(postBuilder.build());
1294 Set<PostReply> replies = new HashSet<PostReply>();
1296 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1297 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1298 if (replyId == null) {
1301 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1302 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1303 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1304 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1305 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1308 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1309 postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1310 replies.add(postReplyBuilder.build());
1313 /* load post likes. */
1314 Set<String> likedPostIds = new HashSet<String>();
1316 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1317 if (likedPostId == null) {
1320 likedPostIds.add(likedPostId);
1323 /* load reply likes. */
1324 Set<String> likedReplyIds = new HashSet<String>();
1326 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1327 if (likedReplyId == null) {
1330 likedReplyIds.add(likedReplyId);
1334 Set<String> friends = new HashSet<String>();
1336 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1337 if (friendId == null) {
1340 friends.add(friendId);
1344 List<Album> topLevelAlbums = new ArrayList<Album>();
1345 int albumCounter = 0;
1347 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1348 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1349 if (albumId == null) {
1352 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1353 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1354 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1355 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1356 if ((albumTitle == null) || (albumDescription == null)) {
1357 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1360 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1361 if (albumParentId != null) {
1362 Album parentAlbum = getAlbum(albumParentId, false);
1363 if (parentAlbum == null) {
1364 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1367 parentAlbum.addAlbum(album);
1369 if (!topLevelAlbums.contains(album)) {
1370 topLevelAlbums.add(album);
1376 int imageCounter = 0;
1378 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1379 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1380 if (imageId == null) {
1383 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1384 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1385 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1386 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1387 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1388 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1389 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1390 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1391 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1394 Album album = getAlbum(albumId, false);
1395 if (album == null) {
1396 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1399 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1400 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1401 album.addImage(image);
1405 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1406 if (avatarId != null) {
1407 profile.setAvatar(getImage(avatarId, false));
1411 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1412 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1413 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1414 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1415 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1416 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1418 /* if we’re still here, Sone was loaded successfully. */
1419 synchronized (sone) {
1420 sone.setTime(soneTime);
1421 sone.setProfile(profile);
1422 sone.setPosts(posts);
1423 sone.setReplies(replies);
1424 sone.setLikePostIds(likedPostIds);
1425 sone.setLikeReplyIds(likedReplyIds);
1426 for (String friendId : friends) {
1427 followSone(sone, friendId);
1429 sone.setAlbums(topLevelAlbums);
1430 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1432 synchronized (knownSones) {
1433 for (String friend : friends) {
1434 knownSones.add(friend);
1437 synchronized (knownPosts) {
1438 for (Post post : posts) {
1439 knownPosts.add(post.getId());
1442 synchronized (knownReplies) {
1443 for (PostReply reply : replies) {
1444 knownReplies.add(reply.getId());
1450 * Creates a new post.
1453 * The Sone that creates the post
1455 * The text of the post
1456 * @return The created post
1458 public Post createPost(Sone sone, String text) {
1459 return createPost(sone, System.currentTimeMillis(), text);
1463 * Creates a new post.
1466 * The Sone that creates the post
1468 * The time of the post
1470 * The text of the post
1471 * @return The created post
1473 public Post createPost(Sone sone, long time, String text) {
1474 return createPost(sone, null, time, text);
1478 * Creates a new post.
1481 * The Sone that creates the post
1483 * The recipient Sone, or {@code null} if this post does not have
1486 * The text of the post
1487 * @return The created post
1489 public Post createPost(Sone sone, Sone recipient, String text) {
1490 return createPost(sone, recipient, System.currentTimeMillis(), text);
1494 * Creates a new post.
1497 * The Sone that creates the post
1499 * The recipient Sone, or {@code null} if this post does not have
1502 * The time of the post
1504 * The text of the post
1505 * @return The created post
1507 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1508 checkNotNull(text, "text must not be null");
1509 checkArgument(text.trim().length() > 0, "text must not be empty");
1510 if (!sone.isLocal()) {
1511 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1514 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1515 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1516 if (recipient != null) {
1517 postBuilder.to(recipient.getId());
1519 final Post post = postBuilder.build();
1520 synchronized (posts) {
1521 posts.put(post.getId(), post);
1523 eventBus.post(new NewPostFoundEvent(post));
1525 touchConfiguration();
1526 localElementTicker.schedule(new Runnable() {
1533 markPostKnown(post);
1535 }, 10, TimeUnit.SECONDS);
1540 * Deletes the given post.
1543 * The post to delete
1545 public void deletePost(Post post) {
1546 if (!post.getSone().isLocal()) {
1547 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1550 post.getSone().removePost(post);
1551 synchronized (posts) {
1552 posts.remove(post.getId());
1554 eventBus.post(new PostRemovedEvent(post));
1555 markPostKnown(post);
1556 touchConfiguration();
1560 * Marks the given post as known, if it is currently not a known post
1561 * (according to {@link Post#isKnown()}).
1564 * The post to mark as known
1566 public void markPostKnown(Post post) {
1567 post.setKnown(true);
1568 synchronized (knownPosts) {
1569 eventBus.post(new MarkPostKnownEvent(post));
1570 if (knownPosts.add(post.getId())) {
1571 touchConfiguration();
1574 for (PostReply reply : getReplies(post)) {
1575 markReplyKnown(reply);
1580 * Bookmarks the given post.
1583 * The post to bookmark
1585 public void bookmark(Post post) {
1586 bookmarkPost(post.getId());
1590 * Bookmarks the post with the given ID.
1593 * The ID of the post to bookmark
1595 public void bookmarkPost(String id) {
1596 synchronized (bookmarkedPosts) {
1597 bookmarkedPosts.add(id);
1602 * Removes the given post from the bookmarks.
1605 * The post to unbookmark
1607 public void unbookmark(Post post) {
1608 unbookmarkPost(post.getId());
1612 * Removes the post with the given ID from the bookmarks.
1615 * The ID of the post to unbookmark
1617 public void unbookmarkPost(String id) {
1618 synchronized (bookmarkedPosts) {
1619 bookmarkedPosts.remove(id);
1624 * Creates a new reply.
1627 * The Sone that creates the reply
1629 * The post that this reply refers to
1631 * The text of the reply
1632 * @return The created reply
1634 public PostReply createReply(Sone sone, Post post, String text) {
1635 checkNotNull(text, "text must not be null");
1636 checkArgument(text.trim().length() > 0, "text must not be empty");
1637 if (!sone.isLocal()) {
1638 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1641 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1642 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1643 final PostReply reply = postReplyBuilder.build();
1644 synchronized (replies) {
1645 replies.put(reply.getId(), reply);
1647 synchronized (knownReplies) {
1648 eventBus.post(new NewPostReplyFoundEvent(reply));
1650 sone.addReply(reply);
1651 touchConfiguration();
1652 localElementTicker.schedule(new Runnable() {
1659 markReplyKnown(reply);
1661 }, 10, TimeUnit.SECONDS);
1666 * Deletes the given reply.
1669 * The reply to delete
1671 public void deleteReply(PostReply reply) {
1672 Sone sone = reply.getSone();
1673 if (!sone.isLocal()) {
1674 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1677 synchronized (replies) {
1678 replies.remove(reply.getId());
1680 synchronized (knownReplies) {
1681 markReplyKnown(reply);
1682 knownReplies.remove(reply.getId());
1684 sone.removeReply(reply);
1685 touchConfiguration();
1689 * Marks the given reply as known, if it is currently not a known reply
1690 * (according to {@link Reply#isKnown()}).
1693 * The reply to mark as known
1695 public void markReplyKnown(PostReply reply) {
1696 reply.setKnown(true);
1697 synchronized (knownReplies) {
1698 eventBus.post(new MarkPostReplyKnownEvent(reply));
1699 if (knownReplies.add(reply.getId())) {
1700 touchConfiguration();
1706 * Creates a new top-level album for the given Sone.
1709 * The Sone to create the album for
1710 * @return The new album
1712 public Album createAlbum(Sone sone) {
1713 return createAlbum(sone, null);
1717 * Creates a new album for the given Sone.
1720 * The Sone to create the album for
1722 * The parent of the album (may be {@code null} to create a
1724 * @return The new album
1726 public Album createAlbum(Sone sone, Album parent) {
1727 Album album = new Album();
1728 synchronized (albums) {
1729 albums.put(album.getId(), album);
1731 album.setSone(sone);
1732 if (parent != null) {
1733 parent.addAlbum(album);
1735 sone.addAlbum(album);
1741 * Deletes the given album. The owner of the album has to be a local Sone,
1742 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1745 * The album to remove
1747 public void deleteAlbum(Album album) {
1748 checkNotNull(album, "album must not be null");
1749 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1750 if (!album.isEmpty()) {
1753 if (album.getParent() == null) {
1754 album.getSone().removeAlbum(album);
1756 album.getParent().removeAlbum(album);
1758 synchronized (albums) {
1759 albums.remove(album.getId());
1761 touchConfiguration();
1765 * Creates a new image.
1768 * The Sone creating the image
1770 * The album the image will be inserted into
1771 * @param temporaryImage
1772 * The temporary image to create the image from
1773 * @return The newly created image
1775 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1776 checkNotNull(sone, "sone must not be null");
1777 checkNotNull(album, "album must not be null");
1778 checkNotNull(temporaryImage, "temporaryImage must not be null");
1779 checkArgument(sone.isLocal(), "sone must be a local Sone");
1780 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1781 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1782 album.addImage(image);
1783 synchronized (images) {
1784 images.put(image.getId(), image);
1786 imageInserter.insertImage(temporaryImage, image);
1791 * Deletes the given image. This method will also delete a matching
1794 * @see #deleteTemporaryImage(TemporaryImage)
1796 * The image to delete
1798 public void deleteImage(Image image) {
1799 checkNotNull(image, "image must not be null");
1800 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1801 deleteTemporaryImage(image.getId());
1802 image.getAlbum().removeImage(image);
1803 synchronized (images) {
1804 images.remove(image.getId());
1806 touchConfiguration();
1810 * Creates a new temporary image.
1813 * The MIME type of the temporary image
1815 * The encoded data of the image
1816 * @return The temporary image
1818 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1819 TemporaryImage temporaryImage = new TemporaryImage();
1820 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1821 synchronized (temporaryImages) {
1822 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1824 return temporaryImage;
1828 * Deletes the given temporary image.
1830 * @param temporaryImage
1831 * The temporary image to delete
1833 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1834 checkNotNull(temporaryImage, "temporaryImage must not be null");
1835 deleteTemporaryImage(temporaryImage.getId());
1839 * Deletes the temporary image with the given ID.
1842 * The ID of the temporary image to delete
1844 public void deleteTemporaryImage(String imageId) {
1845 checkNotNull(imageId, "imageId must not be null");
1846 synchronized (temporaryImages) {
1847 temporaryImages.remove(imageId);
1849 Image image = getImage(imageId, false);
1850 if (image != null) {
1851 imageInserter.cancelImageInsert(image);
1856 * Notifies the core that the configuration, either of the core or of a
1857 * single local Sone, has changed, and that the configuration should be
1860 public void touchConfiguration() {
1861 lastConfigurationUpdate = System.currentTimeMillis();
1872 public void serviceStart() {
1873 loadConfiguration();
1874 updateChecker.start();
1875 identityManager.start();
1876 webOfTrustUpdater.init();
1877 webOfTrustUpdater.start();
1884 public void serviceRun() {
1885 long lastSaved = System.currentTimeMillis();
1886 while (!shouldStop()) {
1888 long now = System.currentTimeMillis();
1889 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1890 for (Sone localSone : getLocalSones()) {
1891 saveSone(localSone);
1893 saveConfiguration();
1903 public void serviceStop() {
1904 localElementTicker.shutdownNow();
1905 synchronized (sones) {
1906 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1907 soneInserter.getValue().stop();
1908 saveSone(soneInserter.getKey());
1911 saveConfiguration();
1912 webOfTrustUpdater.stop();
1913 updateChecker.stop();
1914 soneDownloader.stop();
1915 soneDownloaders.shutdown();
1916 identityManager.stop();
1924 * Saves the given Sone. This will persist all local settings for the given
1925 * Sone, such as the friends list and similar, private options.
1930 private synchronized void saveSone(Sone sone) {
1931 if (!sone.isLocal()) {
1932 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1935 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1936 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1940 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1942 /* save Sone into configuration. */
1943 String sonePrefix = "Sone/" + sone.getId();
1944 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1945 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1948 Profile profile = sone.getProfile();
1949 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1950 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1951 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1952 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1953 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1954 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1955 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1957 /* save profile fields. */
1958 int fieldCounter = 0;
1959 for (Field profileField : profile.getFields()) {
1960 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1961 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1962 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1964 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1967 int postCounter = 0;
1968 for (Post post : sone.getPosts()) {
1969 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1970 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1971 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1972 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1973 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1975 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1978 int replyCounter = 0;
1979 for (PostReply reply : sone.getReplies()) {
1980 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1981 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1982 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1983 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1984 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1986 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1988 /* save post likes. */
1989 int postLikeCounter = 0;
1990 for (String postId : sone.getLikedPostIds()) {
1991 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1993 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1995 /* save reply likes. */
1996 int replyLikeCounter = 0;
1997 for (String replyId : sone.getLikedReplyIds()) {
1998 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2000 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2003 int friendCounter = 0;
2004 for (String friendId : sone.getFriends()) {
2005 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2007 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2009 /* save albums. first, collect in a flat structure, top-level first. */
2010 List<Album> albums = sone.getAllAlbums();
2012 int albumCounter = 0;
2013 for (Album album : albums) {
2014 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2015 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2016 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2017 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2018 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2019 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2021 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2024 int imageCounter = 0;
2025 for (Album album : albums) {
2026 for (Image image : album.getImages()) {
2027 if (!image.isInserted()) {
2030 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2031 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2032 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2033 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2034 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2035 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2036 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2037 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2038 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2041 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2044 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2045 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2046 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2047 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2048 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2049 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2051 configuration.save();
2053 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2055 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2056 } catch (ConfigurationException ce1) {
2057 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2062 * Saves the current options.
2064 private void saveConfiguration() {
2065 synchronized (configuration) {
2066 if (storingConfiguration) {
2067 logger.log(Level.FINE, "Already storing configuration…");
2070 storingConfiguration = true;
2073 /* store the options first. */
2075 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2076 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2077 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2078 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2079 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2080 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2081 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2082 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2083 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2084 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2085 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2086 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2088 /* save known Sones. */
2089 int soneCounter = 0;
2090 synchronized (knownSones) {
2091 for (String knownSoneId : knownSones) {
2092 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2094 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2097 /* save Sone following times. */
2099 synchronized (soneFollowingTimes) {
2100 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2101 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2102 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2105 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2108 /* save known posts. */
2109 int postCounter = 0;
2110 synchronized (knownPosts) {
2111 for (String knownPostId : knownPosts) {
2112 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2114 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2117 /* save known replies. */
2118 int replyCounter = 0;
2119 synchronized (knownReplies) {
2120 for (String knownReplyId : knownReplies) {
2121 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2123 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2126 /* save bookmarked posts. */
2127 int bookmarkedPostCounter = 0;
2128 synchronized (bookmarkedPosts) {
2129 for (String bookmarkedPostId : bookmarkedPosts) {
2130 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2133 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2136 configuration.save();
2138 } catch (ConfigurationException ce1) {
2139 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2141 synchronized (configuration) {
2142 storingConfiguration = false;
2148 * Loads the configuration.
2150 @SuppressWarnings("unchecked")
2151 private void loadConfiguration() {
2152 /* create options. */
2153 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2156 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2157 SoneInserter.setInsertionDelay(newValue);
2161 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2162 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2163 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2164 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2165 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2166 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2167 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2168 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2169 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2172 @SuppressWarnings("synthetic-access")
2173 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2174 fcpInterface.setActive(newValue);
2177 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2180 @SuppressWarnings("synthetic-access")
2181 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2182 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2187 loadConfigurationValue("InsertionDelay");
2188 loadConfigurationValue("PostsPerPage");
2189 loadConfigurationValue("ImagesPerPage");
2190 loadConfigurationValue("CharactersPerPost");
2191 loadConfigurationValue("PostCutOffLength");
2192 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2193 loadConfigurationValue("PositiveTrust");
2194 loadConfigurationValue("NegativeTrust");
2195 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2196 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2197 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2199 /* load known Sones. */
2200 int soneCounter = 0;
2202 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2203 if (knownSoneId == null) {
2206 synchronized (knownSones) {
2207 knownSones.add(knownSoneId);
2211 /* load Sone following times. */
2214 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2215 if (soneId == null) {
2218 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2219 Sone followedSone = getSone(soneId);
2220 if (followedSone == null) {
2221 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2223 synchronized (soneFollowingTimes) {
2224 soneFollowingTimes.put(getSone(soneId), time);
2230 /* load known posts. */
2231 int postCounter = 0;
2233 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2234 if (knownPostId == null) {
2237 synchronized (knownPosts) {
2238 knownPosts.add(knownPostId);
2242 /* load known replies. */
2243 int replyCounter = 0;
2245 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2246 if (knownReplyId == null) {
2249 synchronized (knownReplies) {
2250 knownReplies.add(knownReplyId);
2254 /* load bookmarked posts. */
2255 int bookmarkedPostCounter = 0;
2257 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2258 if (bookmarkedPostId == null) {
2261 synchronized (bookmarkedPosts) {
2262 bookmarkedPosts.add(bookmarkedPostId);
2269 * Loads an {@link Integer} configuration value for the option with the
2270 * given name, logging validation failures.
2273 * The name of the option to load
2275 private void loadConfigurationValue(String optionName) {
2277 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2278 } catch (IllegalArgumentException iae1) {
2279 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2284 * Notifies the core that a new {@link OwnIdentity} was added.
2286 * @param ownIdentityAddedEvent
2290 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2291 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2292 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2293 if (ownIdentity.hasContext("Sone")) {
2294 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2295 addLocalSone(ownIdentity);
2300 * Notifies the core that an {@link OwnIdentity} was removed.
2302 * @param ownIdentityRemovedEvent
2306 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2307 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2308 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2309 trustedIdentities.remove(ownIdentity);
2313 * Notifies the core that a new {@link Identity} was added.
2315 * @param identityAddedEvent
2319 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2320 Identity identity = identityAddedEvent.identity();
2321 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2322 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2323 addRemoteSone(identity);
2327 * Notifies the core that an {@link Identity} was updated.
2329 * @param identityUpdatedEvent
2333 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2334 final Identity identity = identityUpdatedEvent.identity();
2335 soneDownloaders.execute(new Runnable() {
2338 @SuppressWarnings("synthetic-access")
2340 Sone sone = getRemoteSone(identity.getId(), false);
2341 sone.setIdentity(identity);
2342 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2343 soneDownloader.addSone(sone);
2344 soneDownloader.fetchSone(sone);
2350 * Notifies the core that an {@link Identity} was removed.
2352 * @param identityRemovedEvent
2356 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2357 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2358 Identity identity = identityRemovedEvent.identity();
2359 trustedIdentities.get(ownIdentity).remove(identity);
2360 boolean foundIdentity = false;
2361 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2362 if (trustedIdentity.getKey().equals(ownIdentity)) {
2365 if (trustedIdentity.getValue().contains(identity)) {
2366 foundIdentity = true;
2369 if (foundIdentity) {
2370 /* some local identity still trusts this identity, don’t remove. */
2373 Sone sone = getSone(identity.getId(), false);
2375 /* TODO - we don’t have the Sone anymore. should this happen? */
2378 synchronized (posts) {
2379 synchronized (knownPosts) {
2380 for (Post post : sone.getPosts()) {
2381 posts.remove(post.getId());
2382 eventBus.post(new PostRemovedEvent(post));
2386 synchronized (replies) {
2387 synchronized (knownReplies) {
2388 for (PostReply reply : sone.getReplies()) {
2389 replies.remove(reply.getId());
2390 eventBus.post(new PostReplyRemovedEvent(reply));
2394 synchronized (sones) {
2395 sones.remove(identity.getId());
2397 eventBus.post(new SoneRemovedEvent(sone));
2401 * Deletes the temporary image.
2403 * @param imageInsertFinishedEvent
2407 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2408 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2409 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2410 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2411 touchConfiguration();