2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.data.impl.PostImpl;
68 import net.pterodactylus.sone.data.impl.PostReplyImpl;
69 import net.pterodactylus.sone.fcp.FcpInterface;
70 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
71 import net.pterodactylus.sone.freenet.wot.Identity;
72 import net.pterodactylus.sone.freenet.wot.IdentityManager;
73 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
74 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
75 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
79 import net.pterodactylus.sone.main.SonePlugin;
80 import net.pterodactylus.sone.utils.IntegerRangePredicate;
81 import net.pterodactylus.util.config.Configuration;
82 import net.pterodactylus.util.config.ConfigurationException;
83 import net.pterodactylus.util.logging.Logging;
84 import net.pterodactylus.util.number.Numbers;
85 import net.pterodactylus.util.service.AbstractService;
86 import net.pterodactylus.util.thread.NamedThreadFactory;
88 import com.google.common.base.Predicate;
89 import com.google.common.base.Predicates;
90 import com.google.common.collect.Collections2;
91 import com.google.common.eventbus.EventBus;
92 import com.google.common.eventbus.Subscribe;
93 import com.google.inject.Inject;
95 import freenet.keys.FreenetURI;
100 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
102 public class Core extends AbstractService implements SoneProvider, PostProvider {
105 private static final Logger logger = Logging.getLogger(Core.class);
107 /** The start time. */
108 private final long startupTime = System.currentTimeMillis();
111 private final Options options = new Options();
113 /** The preferences. */
114 private final Preferences preferences = new Preferences(options);
116 /** The event bus. */
117 private final EventBus eventBus;
119 /** The configuration. */
120 private Configuration configuration;
122 /** Whether we’re currently saving the configuration. */
123 private boolean storingConfiguration = false;
125 /** The identity manager. */
126 private final IdentityManager identityManager;
128 /** Interface to freenet. */
129 private final FreenetInterface freenetInterface;
131 /** The Sone downloader. */
132 private final SoneDownloader soneDownloader;
134 /** The image inserter. */
135 private final ImageInserter imageInserter;
137 /** Sone downloader thread-pool. */
138 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
140 /** The update checker. */
141 private final UpdateChecker updateChecker;
143 /** The trust updater. */
144 private final WebOfTrustUpdater webOfTrustUpdater;
146 /** The FCP interface. */
147 private volatile FcpInterface fcpInterface;
149 /** The times Sones were followed. */
150 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
152 /** Locked local Sones. */
153 /* synchronize on itself. */
154 private final Set<Sone> lockedSones = new HashSet<Sone>();
156 /** Sone inserters. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
160 /** Sone rescuers. */
161 /* synchronize access on this on sones. */
162 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
165 /* synchronize access on this on itself. */
166 private final Map<String, Sone> sones = new HashMap<String, Sone>();
168 /** All known Sones. */
169 private final Set<String> knownSones = new HashSet<String>();
172 private final Map<String, Post> posts = new HashMap<String, Post>();
174 /** All known posts. */
175 private final Set<String> knownPosts = new HashSet<String>();
178 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
180 /** All known replies. */
181 private final Set<String> knownReplies = new HashSet<String>();
183 /** All bookmarked posts. */
184 /* synchronize access on itself. */
185 private final Set<String> bookmarkedPosts = new HashSet<String>();
187 /** Trusted identities, sorted by own identities. */
188 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
190 /** All known albums. */
191 private final Map<String, Album> albums = new HashMap<String, Album>();
193 /** All known images. */
194 private final Map<String, Image> images = new HashMap<String, Image>();
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(freenetInterface);
227 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
237 * Returns the time Sone was started.
239 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
241 public long getStartupTime() {
246 * Sets the configuration to use. This will automatically save the current
247 * configuration to the given configuration.
249 * @param configuration
250 * The new configuration to use
252 public void setConfiguration(Configuration configuration) {
253 this.configuration = configuration;
254 touchConfiguration();
258 * Returns the options used by the core.
260 * @return The options of the core
262 public Preferences getPreferences() {
267 * Returns the identity manager used by the core.
269 * @return The identity manager
271 public IdentityManager getIdentityManager() {
272 return identityManager;
276 * Returns the update checker.
278 * @return The update checker
280 public UpdateChecker getUpdateChecker() {
281 return updateChecker;
285 * Sets the FCP interface to use.
287 * @param fcpInterface
288 * The FCP interface to use
290 public void setFcpInterface(FcpInterface fcpInterface) {
291 this.fcpInterface = fcpInterface;
295 * Returns the Sone rescuer for the given local Sone.
298 * The local Sone to get the rescuer for
299 * @return The Sone rescuer for the given Sone
301 public SoneRescuer getSoneRescuer(Sone sone) {
302 checkNotNull(sone, "sone must not be null");
303 checkArgument(sone.isLocal(), "sone must be local");
304 synchronized (sones) {
305 SoneRescuer soneRescuer = soneRescuers.get(sone);
306 if (soneRescuer == null) {
307 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
308 soneRescuers.put(sone, soneRescuer);
316 * Returns whether the given Sone is currently locked.
320 * @return {@code true} if the Sone is locked, {@code false} if it is not
322 public boolean isLocked(Sone sone) {
323 synchronized (lockedSones) {
324 return lockedSones.contains(sone);
329 * Returns all Sones, remote and local.
333 public Set<Sone> getSones() {
334 return new HashSet<Sone>(sones.values());
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
343 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Sone getSone(String id) {
347 return getSone(id, true);
351 * Returns the Sone with the given ID, regardless whether it’s local or
355 * The ID of the Sone to get
357 * {@code true} to create a new Sone if none exists,
358 * {@code false} to return {@code null} if a Sone with the given
360 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id, boolean create) {
365 synchronized (sones) {
366 if (!sones.containsKey(id) && create) {
367 Sone sone = new Sone(id, false);
370 return sones.get(id);
375 * Checks whether the core knows a Sone with the given ID.
379 * @return {@code true} if there is a Sone with the given ID, {@code false}
382 public boolean hasSone(String id) {
383 synchronized (sones) {
384 return sones.containsKey(id);
389 * Returns all local Sones.
391 * @return All local Sones
393 public Collection<Sone> getLocalSones() {
394 synchronized (sones) {
395 return Collections2.filter(sones.values(), new Predicate<Sone>() {
398 public boolean apply(Sone sone) {
399 return sone.isLocal();
406 * Returns the local Sone with the given ID, optionally creating a new Sone.
411 * {@code true} to create a new Sone if none exists,
412 * {@code false} to return null if none exists
413 * @return The Sone with the given ID, or {@code null}
415 public Sone getLocalSone(String id, boolean create) {
416 synchronized (sones) {
417 Sone sone = sones.get(id);
418 if ((sone == null) && create) {
419 sone = new Sone(id, true);
422 if ((sone != null) && !sone.isLocal()) {
423 sone = new Sone(id, true);
431 * Returns all remote Sones.
433 * @return All remote Sones
435 public Collection<Sone> getRemoteSones() {
436 synchronized (sones) {
437 return Collections2.filter(sones.values(), new Predicate<Sone>() {
440 public boolean apply(Sone sone) {
441 return !sone.isLocal();
448 * Returns the remote Sone with the given ID.
451 * The ID of the remote Sone to get
453 * {@code true} to always create a Sone, {@code false} to return
454 * {@code null} if no Sone with the given ID exists
455 * @return The Sone with the given ID
457 public Sone getRemoteSone(String id, boolean create) {
458 synchronized (sones) {
459 Sone sone = sones.get(id);
460 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
461 sone = new Sone(id, false);
469 * Returns whether the given Sone has been modified.
472 * The Sone to check for modifications
473 * @return {@code true} if a modification has been detected in the Sone,
474 * {@code false} otherwise
476 public boolean isModifiedSone(Sone sone) {
477 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
481 * Returns the time when the given was first followed by any local Sone.
484 * The Sone to get the time for
485 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
486 * been followed, or {@link Long#MAX_VALUE}
488 public long getSoneFollowingTime(Sone sone) {
489 synchronized (soneFollowingTimes) {
490 if (soneFollowingTimes.containsKey(sone)) {
491 return soneFollowingTimes.get(sone);
493 return Long.MAX_VALUE;
498 * Returns whether the target Sone is trusted by the origin Sone.
504 * @return {@code true} if the target Sone is trusted by the origin Sone
506 public boolean isSoneTrusted(Sone origin, Sone target) {
507 checkNotNull(origin, "origin must not be null");
508 checkNotNull(target, "target must not be null");
509 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
510 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
514 * Returns the post with the given ID.
517 * The ID of the post to get
518 * @return The post with the given ID, or a new post with the given ID
520 public Post getPost(String postId) {
521 return getPost(postId, true);
528 public Post getPost(String postId) {
529 synchronized (posts) {
530 return posts.get(postId);
535 * Returns all posts that have the given Sone as recipient.
537 * @see Post#getRecipient()
539 * The recipient of the posts
540 * @return All posts that have the given Sone as recipient
542 public Set<Post> getDirectedPosts(Sone recipient) {
543 checkNotNull(recipient, "recipient must not be null");
544 Set<Post> directedPosts = new HashSet<Post>();
545 synchronized (posts) {
546 for (Post post : posts.values()) {
547 if (recipient.equals(post.getRecipient())) {
548 directedPosts.add(post);
552 return directedPosts;
556 * Returns the reply with the given ID. If there is no reply with the given
557 * ID yet, a new one is created, unless {@code create} is false in which
558 * case {@code null} is returned.
561 * The ID of the reply to get
563 * {@code true} to always return a {@link Reply}, {@code false}
564 * to return {@code null} if no reply can be found
565 * @return The reply, or {@code null} if there is no such reply
567 public PostReply getPostReply(String replyId, boolean create) {
568 synchronized (replies) {
569 PostReply reply = replies.get(replyId);
570 if (create && (reply == null)) {
571 reply = new PostReplyImpl(replyId);
572 replies.put(replyId, reply);
579 * Returns all replies for the given post, order ascending by time.
582 * The post to get all replies for
583 * @return All replies for the given post
585 public List<PostReply> getReplies(Post post) {
586 Set<Sone> sones = getSones();
587 List<PostReply> replies = new ArrayList<PostReply>();
588 for (Sone sone : sones) {
589 for (PostReply reply : sone.getReplies()) {
590 if (reply.getPost().equals(post)) {
595 Collections.sort(replies, Reply.TIME_COMPARATOR);
600 * Returns all Sones that have liked the given post.
603 * The post to get the liking Sones for
604 * @return The Sones that like the given post
606 public Set<Sone> getLikes(Post post) {
607 Set<Sone> sones = new HashSet<Sone>();
608 for (Sone sone : getSones()) {
609 if (sone.getLikedPostIds().contains(post.getId())) {
617 * Returns all Sones that have liked the given reply.
620 * The reply to get the liking Sones for
621 * @return The Sones that like the given reply
623 public Set<Sone> getLikes(PostReply reply) {
624 Set<Sone> sones = new HashSet<Sone>();
625 for (Sone sone : getSones()) {
626 if (sone.getLikedReplyIds().contains(reply.getId())) {
634 * Returns whether the given post is bookmarked.
638 * @return {@code true} if the given post is bookmarked, {@code false}
641 public boolean isBookmarked(Post post) {
642 return isPostBookmarked(post.getId());
646 * Returns whether the post with the given ID is bookmarked.
649 * The ID of the post to check
650 * @return {@code true} if the post with the given ID is bookmarked,
651 * {@code false} otherwise
653 public boolean isPostBookmarked(String id) {
654 synchronized (bookmarkedPosts) {
655 return bookmarkedPosts.contains(id);
660 * Returns all currently known bookmarked posts.
662 * @return All bookmarked posts
664 public Set<Post> getBookmarkedPosts() {
665 Set<Post> posts = new HashSet<Post>();
666 synchronized (bookmarkedPosts) {
667 for (String bookmarkedPostId : bookmarkedPosts) {
668 Post post = getPost(bookmarkedPostId);
678 * Returns the album with the given ID, creating a new album if no album
679 * with the given ID can be found.
682 * The ID of the album
683 * @return The album with the given ID
685 public Album getAlbum(String albumId) {
686 return getAlbum(albumId, true);
690 * Returns the album with the given ID, optionally creating a new album if
691 * an album with the given ID can not be found.
694 * The ID of the album
696 * {@code true} to create a new album if none exists for the
698 * @return The album with the given ID, or {@code null} if no album with the
699 * given ID exists and {@code create} is {@code false}
701 public Album getAlbum(String albumId, boolean create) {
702 synchronized (albums) {
703 Album album = albums.get(albumId);
704 if (create && (album == null)) {
705 album = new Album(albumId);
706 albums.put(albumId, album);
713 * Returns the image with the given ID, creating it if necessary.
716 * The ID of the image
717 * @return The image with the given ID
719 public Image getImage(String imageId) {
720 return getImage(imageId, true);
724 * Returns the image with the given ID, optionally creating it if it does
728 * The ID of the image
730 * {@code true} to create an image if none exists with the given
732 * @return The image with the given ID, or {@code null} if none exists and
735 public Image getImage(String imageId, boolean create) {
736 synchronized (images) {
737 Image image = images.get(imageId);
738 if (create && (image == null)) {
739 image = new Image(imageId);
740 images.put(imageId, image);
747 * Returns the temporary image with the given ID.
750 * The ID of the temporary image
751 * @return The temporary image, or {@code null} if there is no temporary
752 * image with the given ID
754 public TemporaryImage getTemporaryImage(String imageId) {
755 synchronized (temporaryImages) {
756 return temporaryImages.get(imageId);
765 * Locks the given Sone. A locked Sone will not be inserted by
766 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
772 public void lockSone(Sone sone) {
773 synchronized (lockedSones) {
774 if (lockedSones.add(sone)) {
775 eventBus.post(new SoneLockedEvent(sone));
781 * Unlocks the given Sone.
783 * @see #lockSone(Sone)
787 public void unlockSone(Sone sone) {
788 synchronized (lockedSones) {
789 if (lockedSones.remove(sone)) {
790 eventBus.post(new SoneUnlockedEvent(sone));
796 * Adds a local Sone from the given own identity.
799 * The own identity to create a Sone from
800 * @return The added (or already existing) Sone
802 public Sone addLocalSone(OwnIdentity ownIdentity) {
803 if (ownIdentity == null) {
804 logger.log(Level.WARNING, "Given OwnIdentity is null!");
807 synchronized (sones) {
810 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
811 } catch (MalformedURLException mue1) {
812 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
815 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
816 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
818 /* TODO - load posts ’n stuff */
819 sones.put(ownIdentity.getId(), sone);
820 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
821 soneInserters.put(sone, soneInserter);
822 sone.setStatus(SoneStatus.idle);
824 soneInserter.start();
830 * Creates a new Sone for the given own identity.
833 * The own identity to create a Sone for
834 * @return The created Sone
836 public Sone createSone(OwnIdentity ownIdentity) {
837 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
838 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
841 Sone sone = addLocalSone(ownIdentity);
842 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
843 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
844 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
845 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
846 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
847 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
849 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
850 touchConfiguration();
855 * Adds the Sone of the given identity.
858 * The identity whose Sone to add
859 * @return The added or already existing Sone
861 public Sone addRemoteSone(Identity identity) {
862 if (identity == null) {
863 logger.log(Level.WARNING, "Given Identity is null!");
866 synchronized (sones) {
867 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
868 boolean newSone = sone.getRequestUri() == null;
869 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
870 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
872 synchronized (knownSones) {
873 newSone = !knownSones.contains(sone.getId());
875 sone.setKnown(!newSone);
877 eventBus.post(new NewSoneFoundEvent(sone));
878 for (Sone localSone : getLocalSones()) {
879 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
880 followSone(localSone, sone);
885 soneDownloader.addSone(sone);
886 soneDownloaders.execute(new Runnable() {
889 @SuppressWarnings("synthetic-access")
891 soneDownloader.fetchSone(sone, sone.getRequestUri());
900 * Lets the given local Sone follow the Sone with the given ID.
903 * The local Sone that should follow another Sone
905 * The ID of the Sone to follow
907 public void followSone(Sone sone, String soneId) {
908 checkNotNull(sone, "sone must not be null");
909 checkNotNull(soneId, "soneId must not be null");
910 Sone followedSone = getSone(soneId, true);
911 if (followedSone == null) {
912 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
915 followSone(sone, getSone(soneId));
919 * Lets the given local Sone follow the other given Sone. If the given Sone
920 * was not followed by any local Sone before, this will mark all elements of
921 * the followed Sone as read that have been created before the current
925 * The local Sone that should follow the other Sone
926 * @param followedSone
927 * The Sone that should be followed
929 public void followSone(Sone sone, Sone followedSone) {
930 checkNotNull(sone, "sone must not be null");
931 checkNotNull(followedSone, "followedSone must not be null");
932 sone.addFriend(followedSone.getId());
933 synchronized (soneFollowingTimes) {
934 if (!soneFollowingTimes.containsKey(followedSone)) {
935 long now = System.currentTimeMillis();
936 soneFollowingTimes.put(followedSone, now);
937 for (Post post : followedSone.getPosts()) {
938 if (post.getTime() < now) {
942 for (PostReply reply : followedSone.getReplies()) {
943 if (reply.getTime() < now) {
944 markReplyKnown(reply);
949 touchConfiguration();
953 * Lets the given local Sone unfollow the Sone with the given ID.
956 * The local Sone that should unfollow another Sone
958 * The ID of the Sone being unfollowed
960 public void unfollowSone(Sone sone, String soneId) {
961 checkNotNull(sone, "sone must not be null");
962 checkNotNull(soneId, "soneId must not be null");
963 unfollowSone(sone, getSone(soneId, false));
967 * Lets the given local Sone unfollow the other given Sone. If the given
968 * local Sone is the last local Sone that followed the given Sone, its
969 * following time will be removed.
972 * The local Sone that should unfollow another Sone
973 * @param unfollowedSone
974 * The Sone being unfollowed
976 public void unfollowSone(Sone sone, Sone unfollowedSone) {
977 checkNotNull(sone, "sone must not be null");
978 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
979 sone.removeFriend(unfollowedSone.getId());
980 boolean unfollowedSoneStillFollowed = false;
981 for (Sone localSone : getLocalSones()) {
982 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
984 if (!unfollowedSoneStillFollowed) {
985 synchronized (soneFollowingTimes) {
986 soneFollowingTimes.remove(unfollowedSone);
989 touchConfiguration();
993 * Sets the trust value of the given origin Sone for the target Sone.
1000 * The trust value (from {@code -100} to {@code 100})
1002 public void setTrust(Sone origin, Sone target, int trustValue) {
1003 checkNotNull(origin, "origin must not be null");
1004 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1005 checkNotNull(target, "target must not be null");
1006 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1007 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1011 * Removes any trust assignment for the given target Sone.
1018 public void removeTrust(Sone origin, Sone target) {
1019 checkNotNull(origin, "origin must not be null");
1020 checkNotNull(target, "target must not be null");
1021 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1022 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1026 * Assigns the configured positive trust value for the given target.
1033 public void trustSone(Sone origin, Sone target) {
1034 setTrust(origin, target, preferences.getPositiveTrust());
1038 * Assigns the configured negative trust value for the given target.
1045 public void distrustSone(Sone origin, Sone target) {
1046 setTrust(origin, target, preferences.getNegativeTrust());
1050 * Removes the trust assignment for the given target.
1057 public void untrustSone(Sone origin, Sone target) {
1058 removeTrust(origin, target);
1062 * Updates the stored Sone with the given Sone.
1067 public void updateSone(Sone sone) {
1068 updateSone(sone, false);
1072 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1073 * {@code true}, an older Sone than the current Sone can be given to restore
1077 * The Sone to update
1078 * @param soneRescueMode
1079 * {@code true} if the stored Sone should be updated regardless
1080 * of the age of the given Sone
1082 public void updateSone(Sone sone, boolean soneRescueMode) {
1083 if (hasSone(sone.getId())) {
1084 Sone storedSone = getSone(sone.getId());
1085 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1086 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1089 synchronized (posts) {
1090 if (!soneRescueMode) {
1091 for (Post post : storedSone.getPosts()) {
1092 posts.remove(post.getId());
1093 if (!sone.getPosts().contains(post)) {
1094 eventBus.post(new PostRemovedEvent(post));
1098 List<Post> storedPosts = storedSone.getPosts();
1099 synchronized (knownPosts) {
1100 for (Post post : sone.getPosts()) {
1101 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1102 if (!storedPosts.contains(post)) {
1103 if (post.getTime() < getSoneFollowingTime(sone)) {
1104 knownPosts.add(post.getId());
1105 post.setKnown(true);
1106 } else if (!knownPosts.contains(post.getId())) {
1107 eventBus.post(new NewPostFoundEvent(post));
1110 posts.put(post.getId(), post);
1114 synchronized (replies) {
1115 if (!soneRescueMode) {
1116 for (PostReply reply : storedSone.getReplies()) {
1117 replies.remove(reply.getId());
1118 if (!sone.getReplies().contains(reply)) {
1119 eventBus.post(new PostReplyRemovedEvent(reply));
1123 Set<PostReply> storedReplies = storedSone.getReplies();
1124 synchronized (knownReplies) {
1125 for (PostReply reply : sone.getReplies()) {
1126 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1127 if (!storedReplies.contains(reply)) {
1128 if (reply.getTime() < getSoneFollowingTime(sone)) {
1129 knownReplies.add(reply.getId());
1130 reply.setKnown(true);
1131 } else if (!knownReplies.contains(reply.getId())) {
1132 eventBus.post(new NewPostReplyFoundEvent(reply));
1135 replies.put(reply.getId(), reply);
1139 synchronized (albums) {
1140 synchronized (images) {
1141 for (Album album : storedSone.getAlbums()) {
1142 albums.remove(album.getId());
1143 for (Image image : album.getImages()) {
1144 images.remove(image.getId());
1147 for (Album album : sone.getAlbums()) {
1148 albums.put(album.getId(), album);
1149 for (Image image : album.getImages()) {
1150 images.put(image.getId(), image);
1155 synchronized (storedSone) {
1156 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1157 storedSone.setTime(sone.getTime());
1159 storedSone.setClient(sone.getClient());
1160 storedSone.setProfile(sone.getProfile());
1161 if (soneRescueMode) {
1162 for (Post post : sone.getPosts()) {
1163 storedSone.addPost(post);
1165 for (PostReply reply : sone.getReplies()) {
1166 storedSone.addReply(reply);
1168 for (String likedPostId : sone.getLikedPostIds()) {
1169 storedSone.addLikedPostId(likedPostId);
1171 for (String likedReplyId : sone.getLikedReplyIds()) {
1172 storedSone.addLikedReplyId(likedReplyId);
1174 for (Album album : sone.getAlbums()) {
1175 storedSone.addAlbum(album);
1178 storedSone.setPosts(sone.getPosts());
1179 storedSone.setReplies(sone.getReplies());
1180 storedSone.setLikePostIds(sone.getLikedPostIds());
1181 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1182 storedSone.setAlbums(sone.getAlbums());
1184 storedSone.setLatestEdition(sone.getLatestEdition());
1190 * Deletes the given Sone. This will remove the Sone from the
1191 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1192 * remove the context from its identity.
1195 * The Sone to delete
1197 public void deleteSone(Sone sone) {
1198 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1199 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1202 synchronized (sones) {
1203 if (!getLocalSones().contains(sone)) {
1204 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1207 sones.remove(sone.getId());
1208 SoneInserter soneInserter = soneInserters.remove(sone);
1209 soneInserter.stop();
1211 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1212 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1214 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1215 } catch (ConfigurationException ce1) {
1216 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1221 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1222 * known} before, a {@link MarkSoneKnownEvent} is fired.
1225 * The Sone to mark as known
1227 public void markSoneKnown(Sone sone) {
1228 if (!sone.isKnown()) {
1229 sone.setKnown(true);
1230 synchronized (knownSones) {
1231 knownSones.add(sone.getId());
1233 eventBus.post(new MarkSoneKnownEvent(sone));
1234 touchConfiguration();
1239 * Loads and updates the given Sone from the configuration. If any error is
1240 * encountered, loading is aborted and the given Sone is not changed.
1243 * The Sone to load and update
1245 public void loadSone(Sone sone) {
1246 if (!sone.isLocal()) {
1247 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1251 /* initialize options. */
1252 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1253 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1254 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1255 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1256 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1257 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1260 String sonePrefix = "Sone/" + sone.getId();
1261 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1262 if (soneTime == null) {
1263 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1266 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1269 Profile profile = new Profile(sone);
1270 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1271 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1272 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1273 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1274 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1275 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1277 /* load profile fields. */
1279 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1280 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1281 if (fieldName == null) {
1284 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1285 profile.addField(fieldName).setValue(fieldValue);
1289 Set<Post> posts = new HashSet<Post>();
1291 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1292 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1293 if (postId == null) {
1296 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1297 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1298 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1299 if ((postTime == 0) || (postText == null)) {
1300 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1303 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1304 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1305 post.setRecipient(getSone(postRecipientId));
1311 Set<PostReply> replies = new HashSet<PostReply>();
1313 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1314 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1315 if (replyId == null) {
1318 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1319 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1320 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1321 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1322 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1325 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1328 /* load post likes. */
1329 Set<String> likedPostIds = new HashSet<String>();
1331 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1332 if (likedPostId == null) {
1335 likedPostIds.add(likedPostId);
1338 /* load reply likes. */
1339 Set<String> likedReplyIds = new HashSet<String>();
1341 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1342 if (likedReplyId == null) {
1345 likedReplyIds.add(likedReplyId);
1349 Set<String> friends = new HashSet<String>();
1351 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1352 if (friendId == null) {
1355 friends.add(friendId);
1359 List<Album> topLevelAlbums = new ArrayList<Album>();
1360 int albumCounter = 0;
1362 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1363 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1364 if (albumId == null) {
1367 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1368 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1369 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1370 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1371 if ((albumTitle == null) || (albumDescription == null)) {
1372 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1375 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1376 if (albumParentId != null) {
1377 Album parentAlbum = getAlbum(albumParentId, false);
1378 if (parentAlbum == null) {
1379 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1382 parentAlbum.addAlbum(album);
1384 if (!topLevelAlbums.contains(album)) {
1385 topLevelAlbums.add(album);
1391 int imageCounter = 0;
1393 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1394 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1395 if (imageId == null) {
1398 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1399 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1400 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1401 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1402 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1403 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1404 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1405 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1406 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1409 Album album = getAlbum(albumId, false);
1410 if (album == null) {
1411 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1414 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1415 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1416 album.addImage(image);
1420 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1421 if (avatarId != null) {
1422 profile.setAvatar(getImage(avatarId, false));
1426 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1427 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1428 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1429 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1430 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1431 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1433 /* if we’re still here, Sone was loaded successfully. */
1434 synchronized (sone) {
1435 sone.setTime(soneTime);
1436 sone.setProfile(profile);
1437 sone.setPosts(posts);
1438 sone.setReplies(replies);
1439 sone.setLikePostIds(likedPostIds);
1440 sone.setLikeReplyIds(likedReplyIds);
1441 for (String friendId : friends) {
1442 followSone(sone, friendId);
1444 sone.setAlbums(topLevelAlbums);
1445 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1447 synchronized (knownSones) {
1448 for (String friend : friends) {
1449 knownSones.add(friend);
1452 synchronized (knownPosts) {
1453 for (Post post : posts) {
1454 knownPosts.add(post.getId());
1457 synchronized (knownReplies) {
1458 for (PostReply reply : replies) {
1459 knownReplies.add(reply.getId());
1465 * Creates a new post.
1468 * The Sone that creates the post
1470 * The text of the post
1471 * @return The created post
1473 public Post createPost(Sone sone, String text) {
1474 return createPost(sone, System.currentTimeMillis(), text);
1478 * Creates a new post.
1481 * The Sone that creates the post
1483 * The time of the post
1485 * The text of the post
1486 * @return The created post
1488 public Post createPost(Sone sone, long time, String text) {
1489 return createPost(sone, null, time, text);
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The recipient Sone, or {@code null} if this post does not have
1501 * The text of the post
1502 * @return The created post
1504 public Post createPost(Sone sone, Sone recipient, String text) {
1505 return createPost(sone, recipient, System.currentTimeMillis(), text);
1509 * Creates a new post.
1512 * The Sone that creates the post
1514 * The recipient Sone, or {@code null} if this post does not have
1517 * The time of the post
1519 * The text of the post
1520 * @return The created post
1522 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1523 checkNotNull(text, "text must not be null");
1524 checkArgument(text.trim().length() > 0, "text must not be empty");
1525 if (!sone.isLocal()) {
1526 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1529 final Post post = new PostImpl(sone, time, text.trim());
1530 if (recipient != null) {
1531 post.setRecipient(recipient);
1533 synchronized (posts) {
1534 posts.put(post.getId(), post);
1536 eventBus.post(new NewPostFoundEvent(post));
1538 touchConfiguration();
1539 localElementTicker.schedule(new Runnable() {
1546 markPostKnown(post);
1548 }, 10, TimeUnit.SECONDS);
1553 * Deletes the given post.
1556 * The post to delete
1558 public void deletePost(Post post) {
1559 if (!post.getSone().isLocal()) {
1560 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1563 post.getSone().removePost(post);
1564 synchronized (posts) {
1565 posts.remove(post.getId());
1567 eventBus.post(new PostRemovedEvent(post));
1568 markPostKnown(post);
1569 touchConfiguration();
1573 * Marks the given post as known, if it is currently not a known post
1574 * (according to {@link Post#isKnown()}).
1577 * The post to mark as known
1579 public void markPostKnown(Post post) {
1580 post.setKnown(true);
1581 synchronized (knownPosts) {
1582 eventBus.post(new MarkPostKnownEvent(post));
1583 if (knownPosts.add(post.getId())) {
1584 touchConfiguration();
1587 for (PostReply reply : getReplies(post)) {
1588 markReplyKnown(reply);
1593 * Bookmarks the given post.
1596 * The post to bookmark
1598 public void bookmark(Post post) {
1599 bookmarkPost(post.getId());
1603 * Bookmarks the post with the given ID.
1606 * The ID of the post to bookmark
1608 public void bookmarkPost(String id) {
1609 synchronized (bookmarkedPosts) {
1610 bookmarkedPosts.add(id);
1615 * Removes the given post from the bookmarks.
1618 * The post to unbookmark
1620 public void unbookmark(Post post) {
1621 unbookmarkPost(post.getId());
1625 * Removes the post with the given ID from the bookmarks.
1628 * The ID of the post to unbookmark
1630 public void unbookmarkPost(String id) {
1631 synchronized (bookmarkedPosts) {
1632 bookmarkedPosts.remove(id);
1637 * Creates a new reply.
1640 * The Sone that creates the reply
1642 * The post that this reply refers to
1644 * The text of the reply
1645 * @return The created reply
1647 public PostReply createReply(Sone sone, Post post, String text) {
1648 return createReply(sone, post, System.currentTimeMillis(), text);
1652 * Creates a new reply.
1655 * The Sone that creates the reply
1657 * The post that this reply refers to
1659 * The time of the reply
1661 * The text of the reply
1662 * @return The created reply
1664 public PostReply createReply(Sone sone, Post post, long time, String text) {
1665 checkNotNull(text, "text must not be null");
1666 checkArgument(text.trim().length() > 0, "text must not be empty");
1667 if (!sone.isLocal()) {
1668 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1671 final PostReply reply = new PostReplyImpl(sone, post, System.currentTimeMillis(), text.trim());
1672 synchronized (replies) {
1673 replies.put(reply.getId(), reply);
1675 synchronized (knownReplies) {
1676 eventBus.post(new NewPostReplyFoundEvent(reply));
1678 sone.addReply(reply);
1679 touchConfiguration();
1680 localElementTicker.schedule(new Runnable() {
1687 markReplyKnown(reply);
1689 }, 10, TimeUnit.SECONDS);
1694 * Deletes the given reply.
1697 * The reply to delete
1699 public void deleteReply(PostReply reply) {
1700 Sone sone = reply.getSone();
1701 if (!sone.isLocal()) {
1702 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1705 synchronized (replies) {
1706 replies.remove(reply.getId());
1708 synchronized (knownReplies) {
1709 markReplyKnown(reply);
1710 knownReplies.remove(reply.getId());
1712 sone.removeReply(reply);
1713 touchConfiguration();
1717 * Marks the given reply as known, if it is currently not a known reply
1718 * (according to {@link Reply#isKnown()}).
1721 * The reply to mark as known
1723 public void markReplyKnown(PostReply reply) {
1724 reply.setKnown(true);
1725 synchronized (knownReplies) {
1726 eventBus.post(new MarkPostReplyKnownEvent(reply));
1727 if (knownReplies.add(reply.getId())) {
1728 touchConfiguration();
1734 * Creates a new top-level album for the given Sone.
1737 * The Sone to create the album for
1738 * @return The new album
1740 public Album createAlbum(Sone sone) {
1741 return createAlbum(sone, null);
1745 * Creates a new album for the given Sone.
1748 * The Sone to create the album for
1750 * The parent of the album (may be {@code null} to create a
1752 * @return The new album
1754 public Album createAlbum(Sone sone, Album parent) {
1755 Album album = new Album();
1756 synchronized (albums) {
1757 albums.put(album.getId(), album);
1759 album.setSone(sone);
1760 if (parent != null) {
1761 parent.addAlbum(album);
1763 sone.addAlbum(album);
1769 * Deletes the given album. The owner of the album has to be a local Sone,
1770 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1773 * The album to remove
1775 public void deleteAlbum(Album album) {
1776 checkNotNull(album, "album must not be null");
1777 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1778 if (!album.isEmpty()) {
1781 if (album.getParent() == null) {
1782 album.getSone().removeAlbum(album);
1784 album.getParent().removeAlbum(album);
1786 synchronized (albums) {
1787 albums.remove(album.getId());
1789 touchConfiguration();
1793 * Creates a new image.
1796 * The Sone creating the image
1798 * The album the image will be inserted into
1799 * @param temporaryImage
1800 * The temporary image to create the image from
1801 * @return The newly created image
1803 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1804 checkNotNull(sone, "sone must not be null");
1805 checkNotNull(album, "album must not be null");
1806 checkNotNull(temporaryImage, "temporaryImage must not be null");
1807 checkArgument(sone.isLocal(), "sone must be a local Sone");
1808 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1809 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1810 album.addImage(image);
1811 synchronized (images) {
1812 images.put(image.getId(), image);
1814 imageInserter.insertImage(temporaryImage, image);
1819 * Deletes the given image. This method will also delete a matching
1822 * @see #deleteTemporaryImage(TemporaryImage)
1824 * The image to delete
1826 public void deleteImage(Image image) {
1827 checkNotNull(image, "image must not be null");
1828 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1829 deleteTemporaryImage(image.getId());
1830 image.getAlbum().removeImage(image);
1831 synchronized (images) {
1832 images.remove(image.getId());
1834 touchConfiguration();
1838 * Creates a new temporary image.
1841 * The MIME type of the temporary image
1843 * The encoded data of the image
1844 * @return The temporary image
1846 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1847 TemporaryImage temporaryImage = new TemporaryImage();
1848 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1849 synchronized (temporaryImages) {
1850 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1852 return temporaryImage;
1856 * Deletes the given temporary image.
1858 * @param temporaryImage
1859 * The temporary image to delete
1861 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1862 checkNotNull(temporaryImage, "temporaryImage must not be null");
1863 deleteTemporaryImage(temporaryImage.getId());
1867 * Deletes the temporary image with the given ID.
1870 * The ID of the temporary image to delete
1872 public void deleteTemporaryImage(String imageId) {
1873 checkNotNull(imageId, "imageId must not be null");
1874 synchronized (temporaryImages) {
1875 temporaryImages.remove(imageId);
1877 Image image = getImage(imageId, false);
1878 if (image != null) {
1879 imageInserter.cancelImageInsert(image);
1884 * Notifies the core that the configuration, either of the core or of a
1885 * single local Sone, has changed, and that the configuration should be
1888 public void touchConfiguration() {
1889 lastConfigurationUpdate = System.currentTimeMillis();
1900 public void serviceStart() {
1901 loadConfiguration();
1902 updateChecker.start();
1903 identityManager.start();
1904 webOfTrustUpdater.init();
1905 webOfTrustUpdater.start();
1912 public void serviceRun() {
1913 long lastSaved = System.currentTimeMillis();
1914 while (!shouldStop()) {
1916 long now = System.currentTimeMillis();
1917 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1918 for (Sone localSone : getLocalSones()) {
1919 saveSone(localSone);
1921 saveConfiguration();
1931 public void serviceStop() {
1932 localElementTicker.shutdownNow();
1933 synchronized (sones) {
1934 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1935 soneInserter.getValue().stop();
1936 saveSone(soneInserter.getKey());
1939 saveConfiguration();
1940 webOfTrustUpdater.stop();
1941 updateChecker.stop();
1942 soneDownloader.stop();
1943 identityManager.stop();
1951 * Saves the given Sone. This will persist all local settings for the given
1952 * Sone, such as the friends list and similar, private options.
1957 private synchronized void saveSone(Sone sone) {
1958 if (!sone.isLocal()) {
1959 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1962 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1963 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1967 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1969 /* save Sone into configuration. */
1970 String sonePrefix = "Sone/" + sone.getId();
1971 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1972 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1975 Profile profile = sone.getProfile();
1976 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1977 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1978 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1979 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1980 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1981 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1982 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1984 /* save profile fields. */
1985 int fieldCounter = 0;
1986 for (Field profileField : profile.getFields()) {
1987 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1988 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1989 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1991 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1994 int postCounter = 0;
1995 for (Post post : sone.getPosts()) {
1996 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1997 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1998 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1999 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2000 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2002 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2005 int replyCounter = 0;
2006 for (PostReply reply : sone.getReplies()) {
2007 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2008 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2009 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2010 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2011 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2013 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2015 /* save post likes. */
2016 int postLikeCounter = 0;
2017 for (String postId : sone.getLikedPostIds()) {
2018 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2020 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2022 /* save reply likes. */
2023 int replyLikeCounter = 0;
2024 for (String replyId : sone.getLikedReplyIds()) {
2025 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2027 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2030 int friendCounter = 0;
2031 for (String friendId : sone.getFriends()) {
2032 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2034 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2036 /* save albums. first, collect in a flat structure, top-level first. */
2037 List<Album> albums = sone.getAllAlbums();
2039 int albumCounter = 0;
2040 for (Album album : albums) {
2041 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2042 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2043 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2044 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2045 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2046 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2048 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2051 int imageCounter = 0;
2052 for (Album album : albums) {
2053 for (Image image : album.getImages()) {
2054 if (!image.isInserted()) {
2057 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2058 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2059 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2060 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2061 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2062 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2063 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2064 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2065 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2068 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2071 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2072 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2074 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2075 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2076 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2078 configuration.save();
2080 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2082 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2083 } catch (ConfigurationException ce1) {
2084 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2089 * Saves the current options.
2091 private void saveConfiguration() {
2092 synchronized (configuration) {
2093 if (storingConfiguration) {
2094 logger.log(Level.FINE, "Already storing configuration…");
2097 storingConfiguration = true;
2100 /* store the options first. */
2102 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2103 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2104 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2105 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2106 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2107 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2108 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2109 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2110 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2111 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2112 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2113 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2115 /* save known Sones. */
2116 int soneCounter = 0;
2117 synchronized (knownSones) {
2118 for (String knownSoneId : knownSones) {
2119 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2121 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2124 /* save Sone following times. */
2126 synchronized (soneFollowingTimes) {
2127 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2128 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2129 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2132 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2135 /* save known posts. */
2136 int postCounter = 0;
2137 synchronized (knownPosts) {
2138 for (String knownPostId : knownPosts) {
2139 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2141 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2144 /* save known replies. */
2145 int replyCounter = 0;
2146 synchronized (knownReplies) {
2147 for (String knownReplyId : knownReplies) {
2148 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2150 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2153 /* save bookmarked posts. */
2154 int bookmarkedPostCounter = 0;
2155 synchronized (bookmarkedPosts) {
2156 for (String bookmarkedPostId : bookmarkedPosts) {
2157 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2160 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2163 configuration.save();
2165 } catch (ConfigurationException ce1) {
2166 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2168 synchronized (configuration) {
2169 storingConfiguration = false;
2175 * Loads the configuration.
2177 @SuppressWarnings("unchecked")
2178 private void loadConfiguration() {
2179 /* create options. */
2180 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2183 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2184 SoneInserter.setInsertionDelay(newValue);
2188 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2189 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2190 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2191 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2192 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2193 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2194 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2195 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2196 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2199 @SuppressWarnings("synthetic-access")
2200 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2201 fcpInterface.setActive(newValue);
2204 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2207 @SuppressWarnings("synthetic-access")
2208 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2209 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2214 loadConfigurationValue("InsertionDelay");
2215 loadConfigurationValue("PostsPerPage");
2216 loadConfigurationValue("ImagesPerPage");
2217 loadConfigurationValue("CharactersPerPost");
2218 loadConfigurationValue("PostCutOffLength");
2219 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2220 loadConfigurationValue("PositiveTrust");
2221 loadConfigurationValue("NegativeTrust");
2222 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2223 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2224 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2226 /* load known Sones. */
2227 int soneCounter = 0;
2229 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2230 if (knownSoneId == null) {
2233 synchronized (knownSones) {
2234 knownSones.add(knownSoneId);
2238 /* load Sone following times. */
2241 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2242 if (soneId == null) {
2245 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2246 Sone followedSone = getSone(soneId);
2247 if (followedSone == null) {
2248 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2250 synchronized (soneFollowingTimes) {
2251 soneFollowingTimes.put(getSone(soneId), time);
2257 /* load known posts. */
2258 int postCounter = 0;
2260 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2261 if (knownPostId == null) {
2264 synchronized (knownPosts) {
2265 knownPosts.add(knownPostId);
2269 /* load known replies. */
2270 int replyCounter = 0;
2272 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2273 if (knownReplyId == null) {
2276 synchronized (knownReplies) {
2277 knownReplies.add(knownReplyId);
2281 /* load bookmarked posts. */
2282 int bookmarkedPostCounter = 0;
2284 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2285 if (bookmarkedPostId == null) {
2288 synchronized (bookmarkedPosts) {
2289 bookmarkedPosts.add(bookmarkedPostId);
2296 * Loads an {@link Integer} configuration value for the option with the
2297 * given name, logging validation failures.
2300 * The name of the option to load
2302 private void loadConfigurationValue(String optionName) {
2304 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2305 } catch (IllegalArgumentException iae1) {
2306 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2311 * Generate a Sone URI from the given URI and latest edition.
2314 * The URI to derive the Sone URI from
2315 * @return The derived URI
2317 private static FreenetURI getSoneUri(String uriString) {
2319 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2321 } catch (MalformedURLException mue1) {
2322 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2328 * Notifies the core that a new {@link OwnIdentity} was added.
2330 * @param ownIdentityAddedEvent
2334 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2335 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2336 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2337 if (ownIdentity.hasContext("Sone")) {
2338 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2339 addLocalSone(ownIdentity);
2344 * Notifies the core that an {@link OwnIdentity} was removed.
2346 * @param ownIdentityRemovedEvent
2350 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2351 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2352 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2353 trustedIdentities.remove(ownIdentity);
2357 * Notifies the core that a new {@link Identity} was added.
2359 * @param identityAddedEvent
2363 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2364 Identity identity = identityAddedEvent.identity();
2365 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2366 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2367 addRemoteSone(identity);
2371 * Notifies the core that an {@link Identity} was updated.
2373 * @param identityUpdatedEvent
2377 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2378 final Identity identity = identityUpdatedEvent.identity();
2379 soneDownloaders.execute(new Runnable() {
2382 @SuppressWarnings("synthetic-access")
2384 Sone sone = getRemoteSone(identity.getId(), false);
2385 sone.setIdentity(identity);
2386 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2387 soneDownloader.addSone(sone);
2388 soneDownloader.fetchSone(sone);
2394 * Notifies the core that an {@link Identity} was removed.
2396 * @param identityRemovedEvent
2400 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2401 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2402 Identity identity = identityRemovedEvent.identity();
2403 trustedIdentities.get(ownIdentity).remove(identity);
2404 boolean foundIdentity = false;
2405 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2406 if (trustedIdentity.getKey().equals(ownIdentity)) {
2409 if (trustedIdentity.getValue().contains(identity)) {
2410 foundIdentity = true;
2413 if (foundIdentity) {
2414 /* some local identity still trusts this identity, don’t remove. */
2417 Sone sone = getSone(identity.getId(), false);
2419 /* TODO - we don’t have the Sone anymore. should this happen? */
2422 synchronized (posts) {
2423 synchronized (knownPosts) {
2424 for (Post post : sone.getPosts()) {
2425 posts.remove(post.getId());
2426 eventBus.post(new PostRemovedEvent(post));
2430 synchronized (replies) {
2431 synchronized (knownReplies) {
2432 for (PostReply reply : sone.getReplies()) {
2433 replies.remove(reply.getId());
2434 eventBus.post(new PostReplyRemovedEvent(reply));
2438 synchronized (sones) {
2439 sones.remove(identity.getId());
2441 eventBus.post(new SoneRemovedEvent(sone));
2445 * Deletes the temporary image.
2447 * @param imageInsertFinishedEvent
2451 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2452 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2453 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2454 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2455 touchConfiguration();