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.Predicate;
91 import com.google.common.base.Predicates;
92 import com.google.common.collect.Collections2;
93 import com.google.common.eventbus.EventBus;
94 import com.google.common.eventbus.Subscribe;
95 import com.google.inject.Inject;
97 import freenet.keys.FreenetURI;
102 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
104 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
107 private static final Logger logger = Logging.getLogger(Core.class);
109 /** The start time. */
110 private final long startupTime = System.currentTimeMillis();
113 private final Options options = new Options();
115 /** The preferences. */
116 private final Preferences preferences = new Preferences(options);
118 /** The event bus. */
119 private final EventBus eventBus;
121 /** The configuration. */
122 private Configuration configuration;
124 /** Whether we’re currently saving the configuration. */
125 private boolean storingConfiguration = false;
127 /** The identity manager. */
128 private final IdentityManager identityManager;
130 /** Interface to freenet. */
131 private final FreenetInterface freenetInterface;
133 /** The Sone downloader. */
134 private final SoneDownloader soneDownloader;
136 /** The image inserter. */
137 private final ImageInserter imageInserter;
139 /** Sone downloader thread-pool. */
140 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
142 /** The update checker. */
143 private final UpdateChecker updateChecker;
145 /** The trust updater. */
146 private final WebOfTrustUpdater webOfTrustUpdater;
148 /** The FCP interface. */
149 private volatile FcpInterface fcpInterface;
151 /** The times Sones were followed. */
152 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
154 /** Locked local Sones. */
155 /* synchronize on itself. */
156 private final Set<Sone> lockedSones = new HashSet<Sone>();
158 /** Sone inserters. */
159 /* synchronize access on this on sones. */
160 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
162 /** Sone rescuers. */
163 /* synchronize access on this on sones. */
164 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
167 /* synchronize access on this on itself. */
168 private final Map<String, Sone> sones = new HashMap<String, Sone>();
170 /** All known Sones. */
171 private final Set<String> knownSones = new HashSet<String>();
173 /** The post builder. */
174 private final PostBuilderFactory postBuilderFactory;
177 private final Map<String, Post> posts = new HashMap<String, Post>();
179 /** All known posts. */
180 private final Set<String> knownPosts = new HashSet<String>();
182 /** The post reply builder factory. */
183 private final PostReplyBuilderFactory postReplyBuilderFactory;
186 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
188 /** All known replies. */
189 private final Set<String> knownReplies = new HashSet<String>();
191 /** All bookmarked posts. */
192 /* synchronize access on itself. */
193 private final Set<String> bookmarkedPosts = new HashSet<String>();
195 /** Trusted identities, sorted by own identities. */
196 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
198 /** All known albums. */
199 private final Map<String, Album> albums = new HashMap<String, Album>();
201 /** All known images. */
202 private final Map<String, Image> images = new HashMap<String, Image>();
204 /** All temporary images. */
205 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
207 /** Ticker for threads that mark own elements as known. */
208 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
210 /** The time the configuration was last touched. */
211 private volatile long lastConfigurationUpdate;
214 * Creates a new core.
216 * @param configuration
217 * The configuration of the core
218 * @param freenetInterface
219 * The freenet interface
220 * @param identityManager
221 * The identity manager
222 * @param webOfTrustUpdater
223 * The WebOfTrust updater
226 * @param postBuilderFactory
228 * @param postReplyBuilderFactory
229 * The post reply builder factory
232 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
234 this.configuration = configuration;
235 this.freenetInterface = freenetInterface;
236 this.identityManager = identityManager;
237 this.soneDownloader = new SoneDownloader(this, freenetInterface);
238 this.imageInserter = new ImageInserter(freenetInterface);
239 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
240 this.webOfTrustUpdater = webOfTrustUpdater;
241 this.eventBus = eventBus;
242 this.postBuilderFactory = postBuilderFactory;
243 this.postReplyBuilderFactory = postReplyBuilderFactory;
251 * Returns the time Sone was started.
253 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
255 public long getStartupTime() {
260 * Sets the configuration to use. This will automatically save the current
261 * configuration to the given configuration.
263 * @param configuration
264 * The new configuration to use
266 public void setConfiguration(Configuration configuration) {
267 this.configuration = configuration;
268 touchConfiguration();
272 * Returns the options used by the core.
274 * @return The options of the core
276 public Preferences getPreferences() {
281 * Returns the identity manager used by the core.
283 * @return The identity manager
285 public IdentityManager getIdentityManager() {
286 return identityManager;
290 * Returns the update checker.
292 * @return The update checker
294 public UpdateChecker getUpdateChecker() {
295 return updateChecker;
299 * Sets the FCP interface to use.
301 * @param fcpInterface
302 * The FCP interface to use
304 public void setFcpInterface(FcpInterface fcpInterface) {
305 this.fcpInterface = fcpInterface;
309 * Returns the Sone rescuer for the given local Sone.
312 * The local Sone to get the rescuer for
313 * @return The Sone rescuer for the given Sone
315 public SoneRescuer getSoneRescuer(Sone sone) {
316 checkNotNull(sone, "sone must not be null");
317 checkArgument(sone.isLocal(), "sone must be local");
318 synchronized (sones) {
319 SoneRescuer soneRescuer = soneRescuers.get(sone);
320 if (soneRescuer == null) {
321 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
322 soneRescuers.put(sone, soneRescuer);
330 * Returns whether the given Sone is currently locked.
334 * @return {@code true} if the Sone is locked, {@code false} if it is not
336 public boolean isLocked(Sone sone) {
337 synchronized (lockedSones) {
338 return lockedSones.contains(sone);
343 * Returns all Sones, remote and local.
347 public Set<Sone> getSones() {
348 return new HashSet<Sone>(sones.values());
352 * Returns the Sone with the given ID, regardless whether it’s local or
356 * The ID of the Sone to get
357 * @return The Sone with the given ID, or {@code null} if there is no such
360 public Sone getSone(String id) {
361 return getSone(id, true);
365 * Returns the Sone with the given ID, regardless whether it’s local or
369 * The ID of the Sone to get
371 * {@code true} to create a new Sone if none exists,
372 * {@code false} to return {@code null} if a Sone with the given
374 * @return The Sone with the given ID, or {@code null} if there is no such
378 public Sone getSone(String id, boolean create) {
379 synchronized (sones) {
380 if (!sones.containsKey(id) && create) {
381 Sone sone = new Sone(id, false);
384 return sones.get(id);
389 * Checks whether the core knows a Sone with the given ID.
393 * @return {@code true} if there is a Sone with the given ID, {@code false}
396 public boolean hasSone(String id) {
397 synchronized (sones) {
398 return sones.containsKey(id);
403 * Returns all local Sones.
405 * @return All local Sones
407 public Collection<Sone> getLocalSones() {
408 synchronized (sones) {
409 return Collections2.filter(sones.values(), new Predicate<Sone>() {
412 public boolean apply(Sone sone) {
413 return sone.isLocal();
420 * Returns the local Sone with the given ID, optionally creating a new Sone.
425 * {@code true} to create a new Sone if none exists,
426 * {@code false} to return null if none exists
427 * @return The Sone with the given ID, or {@code null}
429 public Sone getLocalSone(String id, boolean create) {
430 synchronized (sones) {
431 Sone sone = sones.get(id);
432 if ((sone == null) && create) {
433 sone = new Sone(id, true);
436 if ((sone != null) && !sone.isLocal()) {
437 sone = new Sone(id, true);
445 * Returns all remote Sones.
447 * @return All remote Sones
449 public Collection<Sone> getRemoteSones() {
450 synchronized (sones) {
451 return Collections2.filter(sones.values(), new Predicate<Sone>() {
454 public boolean apply(Sone sone) {
455 return !sone.isLocal();
462 * Returns the remote Sone with the given ID.
465 * The ID of the remote Sone to get
467 * {@code true} to always create a Sone, {@code false} to return
468 * {@code null} if no Sone with the given ID exists
469 * @return The Sone with the given ID
471 public Sone getRemoteSone(String id, boolean create) {
472 synchronized (sones) {
473 Sone sone = sones.get(id);
474 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
475 sone = new Sone(id, false);
483 * Returns whether the given Sone has been modified.
486 * The Sone to check for modifications
487 * @return {@code true} if a modification has been detected in the Sone,
488 * {@code false} otherwise
490 public boolean isModifiedSone(Sone sone) {
491 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
495 * Returns the time when the given was first followed by any local Sone.
498 * The Sone to get the time for
499 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
500 * been followed, or {@link Long#MAX_VALUE}
502 public long getSoneFollowingTime(Sone sone) {
503 synchronized (soneFollowingTimes) {
504 if (soneFollowingTimes.containsKey(sone)) {
505 return soneFollowingTimes.get(sone);
507 return Long.MAX_VALUE;
512 * Returns whether the target Sone is trusted by the origin Sone.
518 * @return {@code true} if the target Sone is trusted by the origin Sone
520 public boolean isSoneTrusted(Sone origin, Sone target) {
521 checkNotNull(origin, "origin must not be null");
522 checkNotNull(target, "target must not be null");
523 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
524 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
528 * Returns a post builder.
530 * @return A new post builder
532 public PostBuilder postBuilder() {
533 return postBuilderFactory.newPostBuilder();
540 public Post getPost(String postId) {
541 synchronized (posts) {
542 return posts.get(postId);
547 * Returns all posts that have the given Sone as recipient.
549 * @see Post#getRecipient()
551 * The recipient of the posts
552 * @return All posts that have the given Sone as recipient
554 public Set<Post> getDirectedPosts(Sone recipient) {
555 checkNotNull(recipient, "recipient must not be null");
556 Set<Post> directedPosts = new HashSet<Post>();
557 synchronized (posts) {
558 for (Post post : posts.values()) {
559 if (recipient.equals(post.getRecipient())) {
560 directedPosts.add(post);
564 return directedPosts;
568 * Returns a post reply builder.
570 * @return A new post reply builder
572 public PostReplyBuilder postReplyBuilder() {
573 return postReplyBuilderFactory.newPostReplyBuilder();
580 public PostReply getPostReply(String replyId) {
581 synchronized (replies) {
582 return replies.get(replyId);
590 public List<PostReply> getReplies(Post post) {
591 Set<Sone> sones = getSones();
592 List<PostReply> replies = new ArrayList<PostReply>();
593 for (Sone sone : sones) {
594 for (PostReply reply : sone.getReplies()) {
595 if (reply.getPost().equals(post)) {
600 Collections.sort(replies, Reply.TIME_COMPARATOR);
605 * Returns all Sones that have liked the given post.
608 * The post to get the liking Sones for
609 * @return The Sones that like the given post
611 public Set<Sone> getLikes(Post post) {
612 Set<Sone> sones = new HashSet<Sone>();
613 for (Sone sone : getSones()) {
614 if (sone.getLikedPostIds().contains(post.getId())) {
622 * Returns all Sones that have liked the given reply.
625 * The reply to get the liking Sones for
626 * @return The Sones that like the given reply
628 public Set<Sone> getLikes(PostReply reply) {
629 Set<Sone> sones = new HashSet<Sone>();
630 for (Sone sone : getSones()) {
631 if (sone.getLikedReplyIds().contains(reply.getId())) {
639 * Returns whether the given post is bookmarked.
643 * @return {@code true} if the given post is bookmarked, {@code false}
646 public boolean isBookmarked(Post post) {
647 return isPostBookmarked(post.getId());
651 * Returns whether the post with the given ID is bookmarked.
654 * The ID of the post to check
655 * @return {@code true} if the post with the given ID is bookmarked,
656 * {@code false} otherwise
658 public boolean isPostBookmarked(String id) {
659 synchronized (bookmarkedPosts) {
660 return bookmarkedPosts.contains(id);
665 * Returns all currently known bookmarked posts.
667 * @return All bookmarked posts
669 public Set<Post> getBookmarkedPosts() {
670 Set<Post> posts = new HashSet<Post>();
671 synchronized (bookmarkedPosts) {
672 for (String bookmarkedPostId : bookmarkedPosts) {
673 Post post = getPost(bookmarkedPostId);
683 * Returns the album with the given ID, creating a new album if no album
684 * with the given ID can be found.
687 * The ID of the album
688 * @return The album with the given ID
690 public Album getAlbum(String albumId) {
691 return getAlbum(albumId, true);
695 * Returns the album with the given ID, optionally creating a new album if
696 * an album with the given ID can not be found.
699 * The ID of the album
701 * {@code true} to create a new album if none exists for the
703 * @return The album with the given ID, or {@code null} if no album with the
704 * given ID exists and {@code create} is {@code false}
706 public Album getAlbum(String albumId, boolean create) {
707 synchronized (albums) {
708 Album album = albums.get(albumId);
709 if (create && (album == null)) {
710 album = new Album(albumId);
711 albums.put(albumId, album);
718 * Returns the image with the given ID, creating it if necessary.
721 * The ID of the image
722 * @return The image with the given ID
724 public Image getImage(String imageId) {
725 return getImage(imageId, true);
729 * Returns the image with the given ID, optionally creating it if it does
733 * The ID of the image
735 * {@code true} to create an image if none exists with the given
737 * @return The image with the given ID, or {@code null} if none exists and
740 public Image getImage(String imageId, boolean create) {
741 synchronized (images) {
742 Image image = images.get(imageId);
743 if (create && (image == null)) {
744 image = new Image(imageId);
745 images.put(imageId, image);
752 * Returns the temporary image with the given ID.
755 * The ID of the temporary image
756 * @return The temporary image, or {@code null} if there is no temporary
757 * image with the given ID
759 public TemporaryImage getTemporaryImage(String imageId) {
760 synchronized (temporaryImages) {
761 return temporaryImages.get(imageId);
770 * Locks the given Sone. A locked Sone will not be inserted by
771 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
777 public void lockSone(Sone sone) {
778 synchronized (lockedSones) {
779 if (lockedSones.add(sone)) {
780 eventBus.post(new SoneLockedEvent(sone));
786 * Unlocks the given Sone.
788 * @see #lockSone(Sone)
792 public void unlockSone(Sone sone) {
793 synchronized (lockedSones) {
794 if (lockedSones.remove(sone)) {
795 eventBus.post(new SoneUnlockedEvent(sone));
801 * Adds a local Sone from the given own identity.
804 * The own identity to create a Sone from
805 * @return The added (or already existing) Sone
807 public Sone addLocalSone(OwnIdentity ownIdentity) {
808 if (ownIdentity == null) {
809 logger.log(Level.WARNING, "Given OwnIdentity is null!");
812 synchronized (sones) {
815 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
816 } catch (MalformedURLException mue1) {
817 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
820 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
821 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
823 /* TODO - load posts ’n stuff */
824 sones.put(ownIdentity.getId(), sone);
825 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
826 soneInserters.put(sone, soneInserter);
827 sone.setStatus(SoneStatus.idle);
829 soneInserter.start();
835 * Creates a new Sone for the given own identity.
838 * The own identity to create a Sone for
839 * @return The created Sone
841 public Sone createSone(OwnIdentity ownIdentity) {
842 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
843 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
846 Sone sone = addLocalSone(ownIdentity);
847 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
848 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
849 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
850 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
851 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
852 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
854 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
855 touchConfiguration();
860 * Adds the Sone of the given identity.
863 * The identity whose Sone to add
864 * @return The added or already existing Sone
866 public Sone addRemoteSone(Identity identity) {
867 if (identity == null) {
868 logger.log(Level.WARNING, "Given Identity is null!");
871 synchronized (sones) {
872 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
873 boolean newSone = sone.getRequestUri() == null;
874 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
875 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
877 synchronized (knownSones) {
878 newSone = !knownSones.contains(sone.getId());
880 sone.setKnown(!newSone);
882 eventBus.post(new NewSoneFoundEvent(sone));
883 for (Sone localSone : getLocalSones()) {
884 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
885 followSone(localSone, sone.getId());
890 soneDownloader.addSone(sone);
891 soneDownloaders.execute(new Runnable() {
894 @SuppressWarnings("synthetic-access")
896 soneDownloader.fetchSone(sone, sone.getRequestUri());
905 * Lets the given local Sone follow the Sone with the given ID.
908 * The local Sone that should follow another Sone
910 * The ID of the Sone to follow
912 public void followSone(Sone sone, String soneId) {
913 checkNotNull(sone, "sone must not be null");
914 checkNotNull(soneId, "soneId must not be null");
915 sone.addFriend(soneId);
916 synchronized (soneFollowingTimes) {
917 if (!soneFollowingTimes.containsKey(soneId)) {
918 long now = System.currentTimeMillis();
919 soneFollowingTimes.put(soneId, now);
920 Sone followedSone = getSone(soneId);
921 if (followedSone == null) {
924 for (Post post : followedSone.getPosts()) {
925 if (post.getTime() < now) {
929 for (PostReply reply : followedSone.getReplies()) {
930 if (reply.getTime() < now) {
931 markReplyKnown(reply);
936 touchConfiguration();
940 * Lets the given local Sone unfollow the Sone with the given ID.
943 * The local Sone that should unfollow another Sone
945 * The ID of the Sone being unfollowed
947 public void unfollowSone(Sone sone, String soneId) {
948 checkNotNull(sone, "sone must not be null");
949 checkNotNull(soneId, "soneId must not be null");
950 sone.removeFriend(soneId);
951 boolean unfollowedSoneStillFollowed = false;
952 for (Sone localSone : getLocalSones()) {
953 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
955 if (!unfollowedSoneStillFollowed) {
956 synchronized (soneFollowingTimes) {
957 soneFollowingTimes.remove(soneId);
960 touchConfiguration();
964 * Sets the trust value of the given origin Sone for the target Sone.
971 * The trust value (from {@code -100} to {@code 100})
973 public void setTrust(Sone origin, Sone target, int trustValue) {
974 checkNotNull(origin, "origin must not be null");
975 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
976 checkNotNull(target, "target must not be null");
977 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
978 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
982 * Removes any trust assignment for the given target Sone.
989 public void removeTrust(Sone origin, Sone target) {
990 checkNotNull(origin, "origin must not be null");
991 checkNotNull(target, "target must not be null");
992 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
993 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
997 * Assigns the configured positive trust value for the given target.
1004 public void trustSone(Sone origin, Sone target) {
1005 setTrust(origin, target, preferences.getPositiveTrust());
1009 * Assigns the configured negative trust value for the given target.
1016 public void distrustSone(Sone origin, Sone target) {
1017 setTrust(origin, target, preferences.getNegativeTrust());
1021 * Removes the trust assignment for the given target.
1028 public void untrustSone(Sone origin, Sone target) {
1029 removeTrust(origin, target);
1033 * Updates the stored Sone with the given Sone.
1038 public void updateSone(Sone sone) {
1039 updateSone(sone, false);
1043 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1044 * {@code true}, an older Sone than the current Sone can be given to restore
1048 * The Sone to update
1049 * @param soneRescueMode
1050 * {@code true} if the stored Sone should be updated regardless
1051 * of the age of the given Sone
1053 public void updateSone(Sone sone, boolean soneRescueMode) {
1054 if (hasSone(sone.getId())) {
1055 Sone storedSone = getSone(sone.getId());
1056 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1057 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1060 synchronized (posts) {
1061 if (!soneRescueMode) {
1062 for (Post post : storedSone.getPosts()) {
1063 posts.remove(post.getId());
1064 if (!sone.getPosts().contains(post)) {
1065 eventBus.post(new PostRemovedEvent(post));
1069 List<Post> storedPosts = storedSone.getPosts();
1070 synchronized (knownPosts) {
1071 for (Post post : sone.getPosts()) {
1072 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1073 postBuilder.copyPost(post).from(storedSone.getId());
1074 Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
1075 if (!storedPosts.contains(newPost)) {
1076 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1077 knownPosts.add(newPost.getId());
1078 newPost.setKnown(true);
1079 } else if (!knownPosts.contains(newPost.getId())) {
1080 eventBus.post(new NewPostFoundEvent(newPost));
1083 posts.put(newPost.getId(), newPost);
1087 synchronized (replies) {
1088 if (!soneRescueMode) {
1089 for (PostReply reply : storedSone.getReplies()) {
1090 replies.remove(reply.getId());
1091 if (!sone.getReplies().contains(reply)) {
1092 eventBus.post(new PostReplyRemovedEvent(reply));
1096 Set<PostReply> storedReplies = storedSone.getReplies();
1097 synchronized (knownReplies) {
1098 for (PostReply reply : sone.getReplies()) {
1099 reply.setKnown(knownReplies.contains(reply.getId()));
1100 if (!storedReplies.contains(reply)) {
1101 if (reply.getTime() < getSoneFollowingTime(sone)) {
1102 knownReplies.add(reply.getId());
1103 reply.setKnown(true);
1104 } else if (!knownReplies.contains(reply.getId())) {
1105 eventBus.post(new NewPostReplyFoundEvent(reply));
1108 replies.put(reply.getId(), reply);
1112 synchronized (albums) {
1113 synchronized (images) {
1114 for (Album album : storedSone.getAlbums()) {
1115 albums.remove(album.getId());
1116 for (Image image : album.getImages()) {
1117 images.remove(image.getId());
1120 for (Album album : sone.getAlbums()) {
1121 albums.put(album.getId(), album);
1122 for (Image image : album.getImages()) {
1123 images.put(image.getId(), image);
1128 synchronized (storedSone) {
1129 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1130 storedSone.setTime(sone.getTime());
1132 storedSone.setClient(sone.getClient());
1133 storedSone.setProfile(sone.getProfile());
1134 if (soneRescueMode) {
1135 for (Post post : sone.getPosts()) {
1136 storedSone.addPost(post);
1138 for (PostReply reply : sone.getReplies()) {
1139 storedSone.addReply(reply);
1141 for (String likedPostId : sone.getLikedPostIds()) {
1142 storedSone.addLikedPostId(likedPostId);
1144 for (String likedReplyId : sone.getLikedReplyIds()) {
1145 storedSone.addLikedReplyId(likedReplyId);
1147 for (Album album : sone.getAlbums()) {
1148 storedSone.addAlbum(album);
1151 storedSone.setPosts(sone.getPosts());
1152 storedSone.setReplies(sone.getReplies());
1153 storedSone.setLikePostIds(sone.getLikedPostIds());
1154 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1155 storedSone.setAlbums(sone.getAlbums());
1157 storedSone.setLatestEdition(sone.getLatestEdition());
1163 * Deletes the given Sone. This will remove the Sone from the
1164 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1165 * remove the context from its identity.
1168 * The Sone to delete
1170 public void deleteSone(Sone sone) {
1171 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1172 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1175 synchronized (sones) {
1176 if (!getLocalSones().contains(sone)) {
1177 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1180 sones.remove(sone.getId());
1181 SoneInserter soneInserter = soneInserters.remove(sone);
1182 soneInserter.stop();
1184 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1185 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1187 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1188 } catch (ConfigurationException ce1) {
1189 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1194 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1195 * known} before, a {@link MarkSoneKnownEvent} is fired.
1198 * The Sone to mark as known
1200 public void markSoneKnown(Sone sone) {
1201 if (!sone.isKnown()) {
1202 sone.setKnown(true);
1203 synchronized (knownSones) {
1204 knownSones.add(sone.getId());
1206 eventBus.post(new MarkSoneKnownEvent(sone));
1207 touchConfiguration();
1212 * Loads and updates the given Sone from the configuration. If any error is
1213 * encountered, loading is aborted and the given Sone is not changed.
1216 * The Sone to load and update
1218 public void loadSone(Sone sone) {
1219 if (!sone.isLocal()) {
1220 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1224 /* initialize options. */
1225 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1226 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1227 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1228 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1229 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1230 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1233 String sonePrefix = "Sone/" + sone.getId();
1234 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1235 if (soneTime == null) {
1236 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1239 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1242 Profile profile = new Profile(sone);
1243 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1244 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1245 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1246 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1247 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1248 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1250 /* load profile fields. */
1252 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1253 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1254 if (fieldName == null) {
1257 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1258 profile.addField(fieldName).setValue(fieldValue);
1262 Set<Post> posts = new HashSet<Post>();
1264 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1265 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1266 if (postId == null) {
1269 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1270 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1271 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1272 if ((postTime == 0) || (postText == null)) {
1273 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1276 PostBuilder postBuilder = postBuilderFactory.newPostBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1277 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1278 postBuilder.to(postRecipientId);
1280 posts.add(postBuilder.build());
1284 Set<PostReply> replies = new HashSet<PostReply>();
1286 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1287 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1288 if (replyId == null) {
1291 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1292 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1293 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1294 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1295 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1298 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1299 postReplyBuilder.withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1300 replies.add(postReplyBuilder.build());
1303 /* load post likes. */
1304 Set<String> likedPostIds = new HashSet<String>();
1306 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1307 if (likedPostId == null) {
1310 likedPostIds.add(likedPostId);
1313 /* load reply likes. */
1314 Set<String> likedReplyIds = new HashSet<String>();
1316 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1317 if (likedReplyId == null) {
1320 likedReplyIds.add(likedReplyId);
1324 Set<String> friends = new HashSet<String>();
1326 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1327 if (friendId == null) {
1330 friends.add(friendId);
1334 List<Album> topLevelAlbums = new ArrayList<Album>();
1335 int albumCounter = 0;
1337 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1338 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1339 if (albumId == null) {
1342 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1343 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1344 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1345 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1346 if ((albumTitle == null) || (albumDescription == null)) {
1347 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1350 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1351 if (albumParentId != null) {
1352 Album parentAlbum = getAlbum(albumParentId, false);
1353 if (parentAlbum == null) {
1354 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1357 parentAlbum.addAlbum(album);
1359 if (!topLevelAlbums.contains(album)) {
1360 topLevelAlbums.add(album);
1366 int imageCounter = 0;
1368 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1369 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1370 if (imageId == null) {
1373 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1374 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1375 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1376 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1377 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1378 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1379 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1380 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1381 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1384 Album album = getAlbum(albumId, false);
1385 if (album == null) {
1386 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1389 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1390 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1391 album.addImage(image);
1395 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1396 if (avatarId != null) {
1397 profile.setAvatar(getImage(avatarId, false));
1401 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1402 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1403 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1404 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1405 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1406 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1408 /* if we’re still here, Sone was loaded successfully. */
1409 synchronized (sone) {
1410 sone.setTime(soneTime);
1411 sone.setProfile(profile);
1412 sone.setPosts(posts);
1413 sone.setReplies(replies);
1414 sone.setLikePostIds(likedPostIds);
1415 sone.setLikeReplyIds(likedReplyIds);
1416 for (String friendId : friends) {
1417 followSone(sone, friendId);
1419 sone.setAlbums(topLevelAlbums);
1420 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1422 synchronized (knownSones) {
1423 for (String friend : friends) {
1424 knownSones.add(friend);
1427 synchronized (knownPosts) {
1428 for (Post post : posts) {
1429 knownPosts.add(post.getId());
1432 synchronized (knownReplies) {
1433 for (PostReply reply : replies) {
1434 knownReplies.add(reply.getId());
1440 * Creates a new post.
1443 * The Sone that creates the post
1445 * The text of the post
1446 * @return The created post
1448 public Post createPost(Sone sone, String text) {
1449 return createPost(sone, System.currentTimeMillis(), text);
1453 * Creates a new post.
1456 * The Sone that creates the post
1458 * The time of the post
1460 * The text of the post
1461 * @return The created post
1463 public Post createPost(Sone sone, long time, String text) {
1464 return createPost(sone, null, time, text);
1468 * Creates a new post.
1471 * The Sone that creates the post
1473 * The recipient Sone, or {@code null} if this post does not have
1476 * The text of the post
1477 * @return The created post
1479 public Post createPost(Sone sone, Sone recipient, String text) {
1480 return createPost(sone, recipient, System.currentTimeMillis(), text);
1484 * Creates a new post.
1487 * The Sone that creates the post
1489 * The recipient Sone, or {@code null} if this post does not have
1492 * The time of the post
1494 * The text of the post
1495 * @return The created post
1497 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1498 checkNotNull(text, "text must not be null");
1499 checkArgument(text.trim().length() > 0, "text must not be empty");
1500 if (!sone.isLocal()) {
1501 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1504 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1505 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1506 if (recipient != null) {
1507 postBuilder.to(recipient.getId());
1509 final Post post = postBuilder.build();
1510 synchronized (posts) {
1511 posts.put(post.getId(), post);
1513 eventBus.post(new NewPostFoundEvent(post));
1515 touchConfiguration();
1516 localElementTicker.schedule(new Runnable() {
1523 markPostKnown(post);
1525 }, 10, TimeUnit.SECONDS);
1530 * Deletes the given post.
1533 * The post to delete
1535 public void deletePost(Post post) {
1536 if (!post.getSone().isLocal()) {
1537 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1540 post.getSone().removePost(post);
1541 synchronized (posts) {
1542 posts.remove(post.getId());
1544 eventBus.post(new PostRemovedEvent(post));
1545 markPostKnown(post);
1546 touchConfiguration();
1550 * Marks the given post as known, if it is currently not a known post
1551 * (according to {@link Post#isKnown()}).
1554 * The post to mark as known
1556 public void markPostKnown(Post post) {
1557 post.setKnown(true);
1558 synchronized (knownPosts) {
1559 eventBus.post(new MarkPostKnownEvent(post));
1560 if (knownPosts.add(post.getId())) {
1561 touchConfiguration();
1564 for (PostReply reply : getReplies(post)) {
1565 markReplyKnown(reply);
1570 * Bookmarks the given post.
1573 * The post to bookmark
1575 public void bookmark(Post post) {
1576 bookmarkPost(post.getId());
1580 * Bookmarks the post with the given ID.
1583 * The ID of the post to bookmark
1585 public void bookmarkPost(String id) {
1586 synchronized (bookmarkedPosts) {
1587 bookmarkedPosts.add(id);
1592 * Removes the given post from the bookmarks.
1595 * The post to unbookmark
1597 public void unbookmark(Post post) {
1598 unbookmarkPost(post.getId());
1602 * Removes the post with the given ID from the bookmarks.
1605 * The ID of the post to unbookmark
1607 public void unbookmarkPost(String id) {
1608 synchronized (bookmarkedPosts) {
1609 bookmarkedPosts.remove(id);
1614 * Creates a new reply.
1617 * The Sone that creates the reply
1619 * The post that this reply refers to
1621 * The text of the reply
1622 * @return The created reply
1624 public PostReply createReply(Sone sone, Post post, String text) {
1625 checkNotNull(text, "text must not be null");
1626 checkArgument(text.trim().length() > 0, "text must not be empty");
1627 if (!sone.isLocal()) {
1628 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1631 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1632 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1633 final PostReply reply = postReplyBuilder.build();
1634 synchronized (replies) {
1635 replies.put(reply.getId(), reply);
1637 synchronized (knownReplies) {
1638 eventBus.post(new NewPostReplyFoundEvent(reply));
1640 sone.addReply(reply);
1641 touchConfiguration();
1642 localElementTicker.schedule(new Runnable() {
1649 markReplyKnown(reply);
1651 }, 10, TimeUnit.SECONDS);
1656 * Deletes the given reply.
1659 * The reply to delete
1661 public void deleteReply(PostReply reply) {
1662 Sone sone = reply.getSone();
1663 if (!sone.isLocal()) {
1664 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1667 synchronized (replies) {
1668 replies.remove(reply.getId());
1670 synchronized (knownReplies) {
1671 markReplyKnown(reply);
1672 knownReplies.remove(reply.getId());
1674 sone.removeReply(reply);
1675 touchConfiguration();
1679 * Marks the given reply as known, if it is currently not a known reply
1680 * (according to {@link Reply#isKnown()}).
1683 * The reply to mark as known
1685 public void markReplyKnown(PostReply reply) {
1686 reply.setKnown(true);
1687 synchronized (knownReplies) {
1688 eventBus.post(new MarkPostReplyKnownEvent(reply));
1689 if (knownReplies.add(reply.getId())) {
1690 touchConfiguration();
1696 * Creates a new top-level album for the given Sone.
1699 * The Sone to create the album for
1700 * @return The new album
1702 public Album createAlbum(Sone sone) {
1703 return createAlbum(sone, null);
1707 * Creates a new album for the given Sone.
1710 * The Sone to create the album for
1712 * The parent of the album (may be {@code null} to create a
1714 * @return The new album
1716 public Album createAlbum(Sone sone, Album parent) {
1717 Album album = new Album();
1718 synchronized (albums) {
1719 albums.put(album.getId(), album);
1721 album.setSone(sone);
1722 if (parent != null) {
1723 parent.addAlbum(album);
1725 sone.addAlbum(album);
1731 * Deletes the given album. The owner of the album has to be a local Sone,
1732 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1735 * The album to remove
1737 public void deleteAlbum(Album album) {
1738 checkNotNull(album, "album must not be null");
1739 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1740 if (!album.isEmpty()) {
1743 if (album.getParent() == null) {
1744 album.getSone().removeAlbum(album);
1746 album.getParent().removeAlbum(album);
1748 synchronized (albums) {
1749 albums.remove(album.getId());
1751 touchConfiguration();
1755 * Creates a new image.
1758 * The Sone creating the image
1760 * The album the image will be inserted into
1761 * @param temporaryImage
1762 * The temporary image to create the image from
1763 * @return The newly created image
1765 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1766 checkNotNull(sone, "sone must not be null");
1767 checkNotNull(album, "album must not be null");
1768 checkNotNull(temporaryImage, "temporaryImage must not be null");
1769 checkArgument(sone.isLocal(), "sone must be a local Sone");
1770 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1771 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1772 album.addImage(image);
1773 synchronized (images) {
1774 images.put(image.getId(), image);
1776 imageInserter.insertImage(temporaryImage, image);
1781 * Deletes the given image. This method will also delete a matching
1784 * @see #deleteTemporaryImage(TemporaryImage)
1786 * The image to delete
1788 public void deleteImage(Image image) {
1789 checkNotNull(image, "image must not be null");
1790 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1791 deleteTemporaryImage(image.getId());
1792 image.getAlbum().removeImage(image);
1793 synchronized (images) {
1794 images.remove(image.getId());
1796 touchConfiguration();
1800 * Creates a new temporary image.
1803 * The MIME type of the temporary image
1805 * The encoded data of the image
1806 * @return The temporary image
1808 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1809 TemporaryImage temporaryImage = new TemporaryImage();
1810 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1811 synchronized (temporaryImages) {
1812 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1814 return temporaryImage;
1818 * Deletes the given temporary image.
1820 * @param temporaryImage
1821 * The temporary image to delete
1823 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1824 checkNotNull(temporaryImage, "temporaryImage must not be null");
1825 deleteTemporaryImage(temporaryImage.getId());
1829 * Deletes the temporary image with the given ID.
1832 * The ID of the temporary image to delete
1834 public void deleteTemporaryImage(String imageId) {
1835 checkNotNull(imageId, "imageId must not be null");
1836 synchronized (temporaryImages) {
1837 temporaryImages.remove(imageId);
1839 Image image = getImage(imageId, false);
1840 if (image != null) {
1841 imageInserter.cancelImageInsert(image);
1846 * Notifies the core that the configuration, either of the core or of a
1847 * single local Sone, has changed, and that the configuration should be
1850 public void touchConfiguration() {
1851 lastConfigurationUpdate = System.currentTimeMillis();
1862 public void serviceStart() {
1863 loadConfiguration();
1864 updateChecker.start();
1865 identityManager.start();
1866 webOfTrustUpdater.init();
1867 webOfTrustUpdater.start();
1874 public void serviceRun() {
1875 long lastSaved = System.currentTimeMillis();
1876 while (!shouldStop()) {
1878 long now = System.currentTimeMillis();
1879 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1880 for (Sone localSone : getLocalSones()) {
1881 saveSone(localSone);
1883 saveConfiguration();
1893 public void serviceStop() {
1894 localElementTicker.shutdownNow();
1895 synchronized (sones) {
1896 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1897 soneInserter.getValue().stop();
1898 saveSone(soneInserter.getKey());
1901 saveConfiguration();
1902 webOfTrustUpdater.stop();
1903 updateChecker.stop();
1904 soneDownloader.stop();
1905 identityManager.stop();
1913 * Saves the given Sone. This will persist all local settings for the given
1914 * Sone, such as the friends list and similar, private options.
1919 private synchronized void saveSone(Sone sone) {
1920 if (!sone.isLocal()) {
1921 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1924 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1925 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1929 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1931 /* save Sone into configuration. */
1932 String sonePrefix = "Sone/" + sone.getId();
1933 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1934 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1937 Profile profile = sone.getProfile();
1938 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1939 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1940 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1941 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1942 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1943 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1944 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1946 /* save profile fields. */
1947 int fieldCounter = 0;
1948 for (Field profileField : profile.getFields()) {
1949 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1950 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1951 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1953 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1956 int postCounter = 0;
1957 for (Post post : sone.getPosts()) {
1958 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1959 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1960 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1961 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1962 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1964 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1967 int replyCounter = 0;
1968 for (PostReply reply : sone.getReplies()) {
1969 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1970 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1971 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1972 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1973 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1975 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1977 /* save post likes. */
1978 int postLikeCounter = 0;
1979 for (String postId : sone.getLikedPostIds()) {
1980 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1982 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1984 /* save reply likes. */
1985 int replyLikeCounter = 0;
1986 for (String replyId : sone.getLikedReplyIds()) {
1987 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1989 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1992 int friendCounter = 0;
1993 for (String friendId : sone.getFriends()) {
1994 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1996 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1998 /* save albums. first, collect in a flat structure, top-level first. */
1999 List<Album> albums = sone.getAllAlbums();
2001 int albumCounter = 0;
2002 for (Album album : albums) {
2003 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2004 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2005 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2006 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2007 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2008 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2010 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2013 int imageCounter = 0;
2014 for (Album album : albums) {
2015 for (Image image : album.getImages()) {
2016 if (!image.isInserted()) {
2019 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2020 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2021 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2022 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2023 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2024 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2025 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2026 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2027 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2030 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2033 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2034 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2035 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2036 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2037 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2038 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2040 configuration.save();
2042 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2044 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2045 } catch (ConfigurationException ce1) {
2046 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2051 * Saves the current options.
2053 private void saveConfiguration() {
2054 synchronized (configuration) {
2055 if (storingConfiguration) {
2056 logger.log(Level.FINE, "Already storing configuration…");
2059 storingConfiguration = true;
2062 /* store the options first. */
2064 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2065 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2066 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2067 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2068 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2069 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2070 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2071 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2072 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2073 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2074 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2075 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2077 /* save known Sones. */
2078 int soneCounter = 0;
2079 synchronized (knownSones) {
2080 for (String knownSoneId : knownSones) {
2081 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2083 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2086 /* save Sone following times. */
2088 synchronized (soneFollowingTimes) {
2089 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2090 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
2091 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2094 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2097 /* save known posts. */
2098 int postCounter = 0;
2099 synchronized (knownPosts) {
2100 for (String knownPostId : knownPosts) {
2101 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2103 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2106 /* save known replies. */
2107 int replyCounter = 0;
2108 synchronized (knownReplies) {
2109 for (String knownReplyId : knownReplies) {
2110 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2112 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2115 /* save bookmarked posts. */
2116 int bookmarkedPostCounter = 0;
2117 synchronized (bookmarkedPosts) {
2118 for (String bookmarkedPostId : bookmarkedPosts) {
2119 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2122 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2125 configuration.save();
2127 } catch (ConfigurationException ce1) {
2128 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2130 synchronized (configuration) {
2131 storingConfiguration = false;
2137 * Loads the configuration.
2139 @SuppressWarnings("unchecked")
2140 private void loadConfiguration() {
2141 /* create options. */
2142 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2145 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2146 SoneInserter.setInsertionDelay(newValue);
2150 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2151 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2152 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2153 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2154 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2155 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2156 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2157 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2158 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2161 @SuppressWarnings("synthetic-access")
2162 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2163 fcpInterface.setActive(newValue);
2166 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2169 @SuppressWarnings("synthetic-access")
2170 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2171 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2176 loadConfigurationValue("InsertionDelay");
2177 loadConfigurationValue("PostsPerPage");
2178 loadConfigurationValue("ImagesPerPage");
2179 loadConfigurationValue("CharactersPerPost");
2180 loadConfigurationValue("PostCutOffLength");
2181 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2182 loadConfigurationValue("PositiveTrust");
2183 loadConfigurationValue("NegativeTrust");
2184 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2185 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2186 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2188 /* load known Sones. */
2189 int soneCounter = 0;
2191 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2192 if (knownSoneId == null) {
2195 synchronized (knownSones) {
2196 knownSones.add(knownSoneId);
2200 /* load Sone following times. */
2203 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2204 if (soneId == null) {
2207 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2208 Sone followedSone = getSone(soneId);
2209 if (followedSone == null) {
2210 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2212 synchronized (soneFollowingTimes) {
2213 soneFollowingTimes.put(soneId, time);
2219 /* load known posts. */
2220 int postCounter = 0;
2222 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2223 if (knownPostId == null) {
2226 synchronized (knownPosts) {
2227 knownPosts.add(knownPostId);
2231 /* load known replies. */
2232 int replyCounter = 0;
2234 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2235 if (knownReplyId == null) {
2238 synchronized (knownReplies) {
2239 knownReplies.add(knownReplyId);
2243 /* load bookmarked posts. */
2244 int bookmarkedPostCounter = 0;
2246 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2247 if (bookmarkedPostId == null) {
2250 synchronized (bookmarkedPosts) {
2251 bookmarkedPosts.add(bookmarkedPostId);
2258 * Loads an {@link Integer} configuration value for the option with the
2259 * given name, logging validation failures.
2262 * The name of the option to load
2264 private void loadConfigurationValue(String optionName) {
2266 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2267 } catch (IllegalArgumentException iae1) {
2268 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2273 * Notifies the core that a new {@link OwnIdentity} was added.
2275 * @param ownIdentityAddedEvent
2279 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2280 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2281 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2282 if (ownIdentity.hasContext("Sone")) {
2283 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2284 addLocalSone(ownIdentity);
2289 * Notifies the core that an {@link OwnIdentity} was removed.
2291 * @param ownIdentityRemovedEvent
2295 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2296 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2297 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2298 trustedIdentities.remove(ownIdentity);
2302 * Notifies the core that a new {@link Identity} was added.
2304 * @param identityAddedEvent
2308 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2309 Identity identity = identityAddedEvent.identity();
2310 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2311 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2312 addRemoteSone(identity);
2316 * Notifies the core that an {@link Identity} was updated.
2318 * @param identityUpdatedEvent
2322 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2323 final Identity identity = identityUpdatedEvent.identity();
2324 soneDownloaders.execute(new Runnable() {
2327 @SuppressWarnings("synthetic-access")
2329 Sone sone = getRemoteSone(identity.getId(), false);
2330 sone.setIdentity(identity);
2331 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2332 soneDownloader.addSone(sone);
2333 soneDownloader.fetchSone(sone);
2339 * Notifies the core that an {@link Identity} was removed.
2341 * @param identityRemovedEvent
2345 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2346 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2347 Identity identity = identityRemovedEvent.identity();
2348 trustedIdentities.get(ownIdentity).remove(identity);
2349 boolean foundIdentity = false;
2350 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2351 if (trustedIdentity.getKey().equals(ownIdentity)) {
2354 if (trustedIdentity.getValue().contains(identity)) {
2355 foundIdentity = true;
2358 if (foundIdentity) {
2359 /* some local identity still trusts this identity, don’t remove. */
2362 Sone sone = getSone(identity.getId(), false);
2364 /* TODO - we don’t have the Sone anymore. should this happen? */
2367 synchronized (posts) {
2368 synchronized (knownPosts) {
2369 for (Post post : sone.getPosts()) {
2370 posts.remove(post.getId());
2371 eventBus.post(new PostRemovedEvent(post));
2375 synchronized (replies) {
2376 synchronized (knownReplies) {
2377 for (PostReply reply : sone.getReplies()) {
2378 replies.remove(reply.getId());
2379 eventBus.post(new PostReplyRemovedEvent(reply));
2383 synchronized (sones) {
2384 sones.remove(identity.getId());
2386 eventBus.post(new SoneRemovedEvent(sone));
2390 * Deletes the temporary image.
2392 * @param imageInsertFinishedEvent
2396 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2397 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2398 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2399 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2400 touchConfiguration();