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.logging.Level;
36 import java.util.logging.Logger;
38 import net.pterodactylus.sone.core.Options.DefaultOption;
39 import net.pterodactylus.sone.core.Options.Option;
40 import net.pterodactylus.sone.core.Options.OptionWatcher;
41 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
42 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
45 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
46 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
47 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
48 import net.pterodactylus.sone.core.event.PostRemovedEvent;
49 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneLockedEvent;
51 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
53 import net.pterodactylus.sone.data.Album;
54 import net.pterodactylus.sone.data.Client;
55 import net.pterodactylus.sone.data.Image;
56 import net.pterodactylus.sone.data.Post;
57 import net.pterodactylus.sone.data.PostReply;
58 import net.pterodactylus.sone.data.Profile;
59 import net.pterodactylus.sone.data.Profile.Field;
60 import net.pterodactylus.sone.data.Reply;
61 import net.pterodactylus.sone.data.Sone;
62 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.TemporaryImage;
65 import net.pterodactylus.sone.data.impl.PostImpl;
66 import net.pterodactylus.sone.data.impl.PostReplyImpl;
67 import net.pterodactylus.sone.fcp.FcpInterface;
68 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
69 import net.pterodactylus.sone.freenet.wot.Identity;
70 import net.pterodactylus.sone.freenet.wot.IdentityManager;
71 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
72 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
73 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
74 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
75 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
76 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
77 import net.pterodactylus.sone.main.SonePlugin;
78 import net.pterodactylus.sone.utils.IntegerRangePredicate;
79 import net.pterodactylus.util.config.Configuration;
80 import net.pterodactylus.util.config.ConfigurationException;
81 import net.pterodactylus.util.logging.Logging;
82 import net.pterodactylus.util.service.AbstractService;
83 import net.pterodactylus.util.thread.NamedThreadFactory;
84 import net.pterodactylus.util.thread.Ticker;
86 import com.google.common.base.Optional;
87 import com.google.common.base.Predicate;
88 import com.google.common.base.Predicates;
89 import com.google.common.collect.Collections2;
90 import com.google.common.eventbus.EventBus;
91 import com.google.common.eventbus.Subscribe;
92 import com.google.common.primitives.Longs;
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 Ticker localElementTicker = new Ticker();
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);
525 * Returns the post with the given ID, optionally creating a new post.
528 * The ID of the post to get
530 * {@code true} it create a new post if no post with the given ID
531 * exists, {@code false} to return {@code null}
532 * @return The post, or {@code null} if there is no such post
535 public Post getPost(String postId, boolean create) {
536 synchronized (posts) {
537 Post post = posts.get(postId);
538 if ((post == null) && create) {
539 post = new PostImpl(postId);
540 posts.put(postId, post);
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 the reply with the given ID. If there is no reply with the given
569 * ID yet, a new one is created, unless {@code create} is false in which
570 * case {@code null} is returned.
573 * The ID of the reply to get
575 * {@code true} to always return a {@link Reply}, {@code false}
576 * to return {@code null} if no reply can be found
577 * @return The reply, or {@code null} if there is no such reply
579 public PostReply getPostReply(String replyId, boolean create) {
580 synchronized (replies) {
581 PostReply reply = replies.get(replyId);
582 if (create && (reply == null)) {
583 reply = new PostReplyImpl(replyId);
584 replies.put(replyId, reply);
591 * Returns all replies for the given post, order ascending by time.
594 * The post to get all replies for
595 * @return All replies for the given post
597 public List<PostReply> getReplies(Post post) {
598 Set<Sone> sones = getSones();
599 List<PostReply> replies = new ArrayList<PostReply>();
600 for (Sone sone : sones) {
601 for (PostReply reply : sone.getReplies()) {
602 if (reply.getPost().equals(post)) {
607 Collections.sort(replies, Reply.TIME_COMPARATOR);
612 * Returns all Sones that have liked the given post.
615 * The post to get the liking Sones for
616 * @return The Sones that like the given post
618 public Set<Sone> getLikes(Post post) {
619 Set<Sone> sones = new HashSet<Sone>();
620 for (Sone sone : getSones()) {
621 if (sone.getLikedPostIds().contains(post.getId())) {
629 * Returns all Sones that have liked the given reply.
632 * The reply to get the liking Sones for
633 * @return The Sones that like the given reply
635 public Set<Sone> getLikes(PostReply reply) {
636 Set<Sone> sones = new HashSet<Sone>();
637 for (Sone sone : getSones()) {
638 if (sone.getLikedReplyIds().contains(reply.getId())) {
646 * Returns whether the given post is bookmarked.
650 * @return {@code true} if the given post is bookmarked, {@code false}
653 public boolean isBookmarked(Post post) {
654 return isPostBookmarked(post.getId());
658 * Returns whether the post with the given ID is bookmarked.
661 * The ID of the post to check
662 * @return {@code true} if the post with the given ID is bookmarked,
663 * {@code false} otherwise
665 public boolean isPostBookmarked(String id) {
666 synchronized (bookmarkedPosts) {
667 return bookmarkedPosts.contains(id);
672 * Returns all currently known bookmarked posts.
674 * @return All bookmarked posts
676 public Set<Post> getBookmarkedPosts() {
677 Set<Post> posts = new HashSet<Post>();
678 synchronized (bookmarkedPosts) {
679 for (String bookmarkedPostId : bookmarkedPosts) {
680 Post post = getPost(bookmarkedPostId, false);
690 * Returns the album with the given ID, creating a new album if no album
691 * with the given ID can be found.
694 * The ID of the album
695 * @return The album with the given ID
697 public Album getAlbum(String albumId) {
698 return getAlbum(albumId, true);
702 * Returns the album with the given ID, optionally creating a new album if
703 * an album with the given ID can not be found.
706 * The ID of the album
708 * {@code true} to create a new album if none exists for the
710 * @return The album with the given ID, or {@code null} if no album with the
711 * given ID exists and {@code create} is {@code false}
713 public Album getAlbum(String albumId, boolean create) {
714 synchronized (albums) {
715 Album album = albums.get(albumId);
716 if (create && (album == null)) {
717 album = new Album(albumId);
718 albums.put(albumId, album);
725 * Returns the image with the given ID, creating it if necessary.
728 * The ID of the image
729 * @return The image with the given ID
731 public Image getImage(String imageId) {
732 return getImage(imageId, true);
736 * Returns the image with the given ID, optionally creating it if it does
740 * The ID of the image
742 * {@code true} to create an image if none exists with the given
744 * @return The image with the given ID, or {@code null} if none exists and
747 public Image getImage(String imageId, boolean create) {
748 synchronized (images) {
749 Image image = images.get(imageId);
750 if (create && (image == null)) {
751 image = new Image(imageId);
752 images.put(imageId, image);
759 * Returns the temporary image with the given ID.
762 * The ID of the temporary image
763 * @return The temporary image, or {@code null} if there is no temporary
764 * image with the given ID
766 public TemporaryImage getTemporaryImage(String imageId) {
767 synchronized (temporaryImages) {
768 return temporaryImages.get(imageId);
777 * Locks the given Sone. A locked Sone will not be inserted by
778 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
784 public void lockSone(Sone sone) {
785 synchronized (lockedSones) {
786 if (lockedSones.add(sone)) {
787 eventBus.post(new SoneLockedEvent(sone));
793 * Unlocks the given Sone.
795 * @see #lockSone(Sone)
799 public void unlockSone(Sone sone) {
800 synchronized (lockedSones) {
801 if (lockedSones.remove(sone)) {
802 eventBus.post(new SoneUnlockedEvent(sone));
808 * Adds a local Sone from the given own identity.
811 * The own identity to create a Sone from
812 * @return The added (or already existing) Sone
814 public Sone addLocalSone(OwnIdentity ownIdentity) {
815 if (ownIdentity == null) {
816 logger.log(Level.WARNING, "Given OwnIdentity is null!");
819 synchronized (sones) {
822 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
823 } catch (MalformedURLException mue1) {
824 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
827 sone.setLatestEdition(Optional.fromNullable(Longs.tryParse(ownIdentity.getProperty("Sone.LatestEdition"))).or(0L));
828 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
830 /* TODO - load posts ’n stuff */
831 sones.put(ownIdentity.getId(), sone);
832 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
833 soneInserters.put(sone, soneInserter);
834 sone.setStatus(SoneStatus.idle);
836 soneInserter.start();
842 * Creates a new Sone for the given own identity.
845 * The own identity to create a Sone for
846 * @return The created Sone
848 public Sone createSone(OwnIdentity ownIdentity) {
849 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
850 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
853 Sone sone = addLocalSone(ownIdentity);
854 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
855 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
856 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
857 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
858 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
859 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
861 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
862 touchConfiguration();
867 * Adds the Sone of the given identity.
870 * The identity whose Sone to add
871 * @return The added or already existing Sone
873 public Sone addRemoteSone(Identity identity) {
874 if (identity == null) {
875 logger.log(Level.WARNING, "Given Identity is null!");
878 synchronized (sones) {
879 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
880 boolean newSone = sone.getRequestUri() == null;
881 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
882 sone.setLatestEdition(Optional.fromNullable(Longs.tryParse(identity.getProperty("Sone.LatestEdition"))).or(0L));
884 synchronized (knownSones) {
885 newSone = !knownSones.contains(sone.getId());
887 sone.setKnown(!newSone);
889 eventBus.post(new NewSoneFoundEvent(sone));
890 for (Sone localSone : getLocalSones()) {
891 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
892 followSone(localSone, sone);
897 soneDownloader.addSone(sone);
898 soneDownloaders.execute(new Runnable() {
901 @SuppressWarnings("synthetic-access")
903 soneDownloader.fetchSone(sone, sone.getRequestUri());
912 * Lets the given local Sone follow the Sone with the given ID.
915 * The local Sone that should follow another Sone
917 * The ID of the Sone to follow
919 public void followSone(Sone sone, String soneId) {
920 checkNotNull(sone, "sone must not be null");
921 checkNotNull(soneId, "soneId must not be null");
922 Sone followedSone = getSone(soneId, true);
923 if (followedSone == null) {
924 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
927 followSone(sone, getSone(soneId));
931 * Lets the given local Sone follow the other given Sone. If the given Sone
932 * was not followed by any local Sone before, this will mark all elements of
933 * the followed Sone as read that have been created before the current
937 * The local Sone that should follow the other Sone
938 * @param followedSone
939 * The Sone that should be followed
941 public void followSone(Sone sone, Sone followedSone) {
942 checkNotNull(sone, "sone must not be null");
943 checkNotNull(followedSone, "followedSone must not be null");
944 sone.addFriend(followedSone.getId());
945 synchronized (soneFollowingTimes) {
946 if (!soneFollowingTimes.containsKey(followedSone)) {
947 long now = System.currentTimeMillis();
948 soneFollowingTimes.put(followedSone, now);
949 for (Post post : followedSone.getPosts()) {
950 if (post.getTime() < now) {
954 for (PostReply reply : followedSone.getReplies()) {
955 if (reply.getTime() < now) {
956 markReplyKnown(reply);
961 touchConfiguration();
965 * Lets the given local Sone unfollow the Sone with the given ID.
968 * The local Sone that should unfollow another Sone
970 * The ID of the Sone being unfollowed
972 public void unfollowSone(Sone sone, String soneId) {
973 checkNotNull(sone, "sone must not be null");
974 checkNotNull(soneId, "soneId must not be null");
975 unfollowSone(sone, getSone(soneId, false));
979 * Lets the given local Sone unfollow the other given Sone. If the given
980 * local Sone is the last local Sone that followed the given Sone, its
981 * following time will be removed.
984 * The local Sone that should unfollow another Sone
985 * @param unfollowedSone
986 * The Sone being unfollowed
988 public void unfollowSone(Sone sone, Sone unfollowedSone) {
989 checkNotNull(sone, "sone must not be null");
990 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
991 sone.removeFriend(unfollowedSone.getId());
992 boolean unfollowedSoneStillFollowed = false;
993 for (Sone localSone : getLocalSones()) {
994 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
996 if (!unfollowedSoneStillFollowed) {
997 synchronized (soneFollowingTimes) {
998 soneFollowingTimes.remove(unfollowedSone);
1001 touchConfiguration();
1005 * Sets the trust value of the given origin Sone for the target Sone.
1012 * The trust value (from {@code -100} to {@code 100})
1014 public void setTrust(Sone origin, Sone target, int trustValue) {
1015 checkNotNull(origin, "origin must not be null");
1016 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1017 checkNotNull(target, "target must not be null");
1018 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1019 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1023 * Removes any trust assignment for the given target Sone.
1030 public void removeTrust(Sone origin, Sone target) {
1031 checkNotNull(origin, "origin must not be null");
1032 checkNotNull(target, "target must not be null");
1033 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1034 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1038 * Assigns the configured positive trust value for the given target.
1045 public void trustSone(Sone origin, Sone target) {
1046 setTrust(origin, target, preferences.getPositiveTrust());
1050 * Assigns the configured negative trust value for the given target.
1057 public void distrustSone(Sone origin, Sone target) {
1058 setTrust(origin, target, preferences.getNegativeTrust());
1062 * Removes the trust assignment for the given target.
1069 public void untrustSone(Sone origin, Sone target) {
1070 removeTrust(origin, target);
1074 * Updates the stored Sone with the given Sone.
1079 public void updateSone(Sone sone) {
1080 updateSone(sone, false);
1084 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1085 * {@code true}, an older Sone than the current Sone can be given to restore
1089 * The Sone to update
1090 * @param soneRescueMode
1091 * {@code true} if the stored Sone should be updated regardless
1092 * of the age of the given Sone
1094 public void updateSone(Sone sone, boolean soneRescueMode) {
1095 if (hasSone(sone.getId())) {
1096 Sone storedSone = getSone(sone.getId());
1097 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1098 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1101 synchronized (posts) {
1102 if (!soneRescueMode) {
1103 for (Post post : storedSone.getPosts()) {
1104 posts.remove(post.getId());
1105 if (!sone.getPosts().contains(post)) {
1106 eventBus.post(new PostRemovedEvent(post));
1110 List<Post> storedPosts = storedSone.getPosts();
1111 synchronized (knownPosts) {
1112 for (Post post : sone.getPosts()) {
1113 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1114 if (!storedPosts.contains(post)) {
1115 if (post.getTime() < getSoneFollowingTime(sone)) {
1116 knownPosts.add(post.getId());
1117 post.setKnown(true);
1118 } else if (!knownPosts.contains(post.getId())) {
1119 eventBus.post(new NewPostFoundEvent(post));
1122 posts.put(post.getId(), post);
1126 synchronized (replies) {
1127 if (!soneRescueMode) {
1128 for (PostReply reply : storedSone.getReplies()) {
1129 replies.remove(reply.getId());
1130 if (!sone.getReplies().contains(reply)) {
1131 eventBus.post(new PostReplyRemovedEvent(reply));
1135 Set<PostReply> storedReplies = storedSone.getReplies();
1136 synchronized (knownReplies) {
1137 for (PostReply reply : sone.getReplies()) {
1138 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1139 if (!storedReplies.contains(reply)) {
1140 if (reply.getTime() < getSoneFollowingTime(sone)) {
1141 knownReplies.add(reply.getId());
1142 reply.setKnown(true);
1143 } else if (!knownReplies.contains(reply.getId())) {
1144 eventBus.post(new NewPostReplyFoundEvent(reply));
1147 replies.put(reply.getId(), reply);
1151 synchronized (albums) {
1152 synchronized (images) {
1153 for (Album album : storedSone.getAlbums()) {
1154 albums.remove(album.getId());
1155 for (Image image : album.getImages()) {
1156 images.remove(image.getId());
1159 for (Album album : sone.getAlbums()) {
1160 albums.put(album.getId(), album);
1161 for (Image image : album.getImages()) {
1162 images.put(image.getId(), image);
1167 synchronized (storedSone) {
1168 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1169 storedSone.setTime(sone.getTime());
1171 storedSone.setClient(sone.getClient());
1172 storedSone.setProfile(sone.getProfile());
1173 if (soneRescueMode) {
1174 for (Post post : sone.getPosts()) {
1175 storedSone.addPost(post);
1177 for (PostReply reply : sone.getReplies()) {
1178 storedSone.addReply(reply);
1180 for (String likedPostId : sone.getLikedPostIds()) {
1181 storedSone.addLikedPostId(likedPostId);
1183 for (String likedReplyId : sone.getLikedReplyIds()) {
1184 storedSone.addLikedReplyId(likedReplyId);
1186 for (Album album : sone.getAlbums()) {
1187 storedSone.addAlbum(album);
1190 storedSone.setPosts(sone.getPosts());
1191 storedSone.setReplies(sone.getReplies());
1192 storedSone.setLikePostIds(sone.getLikedPostIds());
1193 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1194 storedSone.setAlbums(sone.getAlbums());
1196 storedSone.setLatestEdition(sone.getLatestEdition());
1202 * Deletes the given Sone. This will remove the Sone from the
1203 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1204 * remove the context from its identity.
1207 * The Sone to delete
1209 public void deleteSone(Sone sone) {
1210 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1211 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1214 synchronized (sones) {
1215 if (!getLocalSones().contains(sone)) {
1216 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1219 sones.remove(sone.getId());
1220 SoneInserter soneInserter = soneInserters.remove(sone);
1221 soneInserter.stop();
1223 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1224 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1226 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1227 } catch (ConfigurationException ce1) {
1228 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1233 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1234 * known} before, a {@link MarkSoneKnownEvent} is fired.
1237 * The Sone to mark as known
1239 public void markSoneKnown(Sone sone) {
1240 if (!sone.isKnown()) {
1241 sone.setKnown(true);
1242 synchronized (knownSones) {
1243 knownSones.add(sone.getId());
1245 eventBus.post(new MarkSoneKnownEvent(sone));
1246 touchConfiguration();
1251 * Loads and updates the given Sone from the configuration. If any error is
1252 * encountered, loading is aborted and the given Sone is not changed.
1255 * The Sone to load and update
1257 public void loadSone(Sone sone) {
1258 if (!sone.isLocal()) {
1259 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1263 /* initialize options. */
1264 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1265 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1266 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1267 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1268 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1269 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1272 String sonePrefix = "Sone/" + sone.getId();
1273 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1274 if (soneTime == null) {
1275 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1278 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1281 Profile profile = new Profile(sone);
1282 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1283 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1284 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1285 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1286 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1287 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1289 /* load profile fields. */
1291 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1292 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1293 if (fieldName == null) {
1296 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1297 profile.addField(fieldName).setValue(fieldValue);
1301 Set<Post> posts = new HashSet<Post>();
1303 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1304 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1305 if (postId == null) {
1308 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1309 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1310 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1311 if ((postTime == 0) || (postText == null)) {
1312 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1315 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1316 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1317 post.setRecipient(getSone(postRecipientId));
1323 Set<PostReply> replies = new HashSet<PostReply>();
1325 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1326 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1327 if (replyId == null) {
1330 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1331 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1332 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1333 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1334 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1337 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1340 /* load post likes. */
1341 Set<String> likedPostIds = new HashSet<String>();
1343 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1344 if (likedPostId == null) {
1347 likedPostIds.add(likedPostId);
1350 /* load reply likes. */
1351 Set<String> likedReplyIds = new HashSet<String>();
1353 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1354 if (likedReplyId == null) {
1357 likedReplyIds.add(likedReplyId);
1361 Set<String> friends = new HashSet<String>();
1363 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1364 if (friendId == null) {
1367 friends.add(friendId);
1371 List<Album> topLevelAlbums = new ArrayList<Album>();
1372 int albumCounter = 0;
1374 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1375 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1376 if (albumId == null) {
1379 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1380 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1381 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1382 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1383 if ((albumTitle == null) || (albumDescription == null)) {
1384 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1387 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1388 if (albumParentId != null) {
1389 Album parentAlbum = getAlbum(albumParentId, false);
1390 if (parentAlbum == null) {
1391 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1394 parentAlbum.addAlbum(album);
1396 if (!topLevelAlbums.contains(album)) {
1397 topLevelAlbums.add(album);
1403 int imageCounter = 0;
1405 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1406 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1407 if (imageId == null) {
1410 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1411 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1412 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1413 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1414 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1415 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1416 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1417 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1418 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1421 Album album = getAlbum(albumId, false);
1422 if (album == null) {
1423 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1426 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1427 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1428 album.addImage(image);
1432 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1433 if (avatarId != null) {
1434 profile.setAvatar(getImage(avatarId, false));
1438 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1439 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1440 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1441 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1443 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1445 /* if we’re still here, Sone was loaded successfully. */
1446 synchronized (sone) {
1447 sone.setTime(soneTime);
1448 sone.setProfile(profile);
1449 sone.setPosts(posts);
1450 sone.setReplies(replies);
1451 sone.setLikePostIds(likedPostIds);
1452 sone.setLikeReplyIds(likedReplyIds);
1453 for (String friendId : friends) {
1454 followSone(sone, friendId);
1456 sone.setAlbums(topLevelAlbums);
1457 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1459 synchronized (knownSones) {
1460 for (String friend : friends) {
1461 knownSones.add(friend);
1464 synchronized (knownPosts) {
1465 for (Post post : posts) {
1466 knownPosts.add(post.getId());
1469 synchronized (knownReplies) {
1470 for (PostReply reply : replies) {
1471 knownReplies.add(reply.getId());
1477 * Creates a new post.
1480 * The Sone that creates the post
1482 * The text of the post
1483 * @return The created post
1485 public Post createPost(Sone sone, String text) {
1486 return createPost(sone, System.currentTimeMillis(), text);
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The time of the post
1497 * The text of the post
1498 * @return The created post
1500 public Post createPost(Sone sone, long time, String text) {
1501 return createPost(sone, null, time, text);
1505 * Creates a new post.
1508 * The Sone that creates the post
1510 * The recipient Sone, or {@code null} if this post does not have
1513 * The text of the post
1514 * @return The created post
1516 public Post createPost(Sone sone, Sone recipient, String text) {
1517 return createPost(sone, recipient, System.currentTimeMillis(), text);
1521 * Creates a new post.
1524 * The Sone that creates the post
1526 * The recipient Sone, or {@code null} if this post does not have
1529 * The time of the post
1531 * The text of the post
1532 * @return The created post
1534 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1535 checkNotNull(text, "text must not be null");
1536 checkArgument(text.trim().length() > 0, "text must not be empty");
1537 if (!sone.isLocal()) {
1538 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1541 final Post post = new PostImpl(sone, time, text.trim());
1542 if (recipient != null) {
1543 post.setRecipient(recipient);
1545 synchronized (posts) {
1546 posts.put(post.getId(), post);
1548 eventBus.post(new NewPostFoundEvent(post));
1550 touchConfiguration();
1551 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1558 markPostKnown(post);
1560 }, "Mark " + post + " read.");
1565 * Deletes the given post.
1568 * The post to delete
1570 public void deletePost(Post post) {
1571 if (!post.getSone().isLocal()) {
1572 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1575 post.getSone().removePost(post);
1576 synchronized (posts) {
1577 posts.remove(post.getId());
1579 eventBus.post(new PostRemovedEvent(post));
1580 markPostKnown(post);
1581 touchConfiguration();
1585 * Marks the given post as known, if it is currently not a known post
1586 * (according to {@link Post#isKnown()}).
1589 * The post to mark as known
1591 public void markPostKnown(Post post) {
1592 post.setKnown(true);
1593 synchronized (knownPosts) {
1594 eventBus.post(new MarkPostKnownEvent(post));
1595 if (knownPosts.add(post.getId())) {
1596 touchConfiguration();
1599 for (PostReply reply : getReplies(post)) {
1600 markReplyKnown(reply);
1605 * Bookmarks the given post.
1608 * The post to bookmark
1610 public void bookmark(Post post) {
1611 bookmarkPost(post.getId());
1615 * Bookmarks the post with the given ID.
1618 * The ID of the post to bookmark
1620 public void bookmarkPost(String id) {
1621 synchronized (bookmarkedPosts) {
1622 bookmarkedPosts.add(id);
1627 * Removes the given post from the bookmarks.
1630 * The post to unbookmark
1632 public void unbookmark(Post post) {
1633 unbookmarkPost(post.getId());
1637 * Removes the post with the given ID from the bookmarks.
1640 * The ID of the post to unbookmark
1642 public void unbookmarkPost(String id) {
1643 synchronized (bookmarkedPosts) {
1644 bookmarkedPosts.remove(id);
1649 * Creates a new reply.
1652 * The Sone that creates the reply
1654 * The post that this reply refers to
1656 * The text of the reply
1657 * @return The created reply
1659 public PostReply createReply(Sone sone, Post post, String text) {
1660 return createReply(sone, post, System.currentTimeMillis(), text);
1664 * Creates a new reply.
1667 * The Sone that creates the reply
1669 * The post that this reply refers to
1671 * The time of the reply
1673 * The text of the reply
1674 * @return The created reply
1676 public PostReply createReply(Sone sone, Post post, long time, String text) {
1677 checkNotNull(text, "text must not be null");
1678 checkArgument(text.trim().length() > 0, "text must not be empty");
1679 if (!sone.isLocal()) {
1680 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1683 final PostReply reply = new PostReplyImpl(sone, post, System.currentTimeMillis(), text.trim());
1684 synchronized (replies) {
1685 replies.put(reply.getId(), reply);
1687 synchronized (knownReplies) {
1688 eventBus.post(new NewPostReplyFoundEvent(reply));
1690 sone.addReply(reply);
1691 touchConfiguration();
1692 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1699 markReplyKnown(reply);
1701 }, "Mark " + reply + " read.");
1706 * Deletes the given reply.
1709 * The reply to delete
1711 public void deleteReply(PostReply reply) {
1712 Sone sone = reply.getSone();
1713 if (!sone.isLocal()) {
1714 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1717 synchronized (replies) {
1718 replies.remove(reply.getId());
1720 synchronized (knownReplies) {
1721 markReplyKnown(reply);
1722 knownReplies.remove(reply.getId());
1724 sone.removeReply(reply);
1725 touchConfiguration();
1729 * Marks the given reply as known, if it is currently not a known reply
1730 * (according to {@link Reply#isKnown()}).
1733 * The reply to mark as known
1735 public void markReplyKnown(PostReply reply) {
1736 reply.setKnown(true);
1737 synchronized (knownReplies) {
1738 eventBus.post(new MarkPostReplyKnownEvent(reply));
1739 if (knownReplies.add(reply.getId())) {
1740 touchConfiguration();
1746 * Creates a new top-level album for the given Sone.
1749 * The Sone to create the album for
1750 * @return The new album
1752 public Album createAlbum(Sone sone) {
1753 return createAlbum(sone, null);
1757 * Creates a new album for the given Sone.
1760 * The Sone to create the album for
1762 * The parent of the album (may be {@code null} to create a
1764 * @return The new album
1766 public Album createAlbum(Sone sone, Album parent) {
1767 Album album = new Album();
1768 synchronized (albums) {
1769 albums.put(album.getId(), album);
1771 album.setSone(sone);
1772 if (parent != null) {
1773 parent.addAlbum(album);
1775 sone.addAlbum(album);
1781 * Deletes the given album. The owner of the album has to be a local Sone,
1782 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1785 * The album to remove
1787 public void deleteAlbum(Album album) {
1788 checkNotNull(album, "album must not be null");
1789 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1790 if (!album.isEmpty()) {
1793 if (album.getParent() == null) {
1794 album.getSone().removeAlbum(album);
1796 album.getParent().removeAlbum(album);
1798 synchronized (albums) {
1799 albums.remove(album.getId());
1801 touchConfiguration();
1805 * Creates a new image.
1808 * The Sone creating the image
1810 * The album the image will be inserted into
1811 * @param temporaryImage
1812 * The temporary image to create the image from
1813 * @return The newly created image
1815 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1816 checkNotNull(sone, "sone must not be null");
1817 checkNotNull(album, "album must not be null");
1818 checkNotNull(temporaryImage, "temporaryImage must not be null");
1819 checkArgument(sone.isLocal(), "sone must be a local Sone");
1820 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1821 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1822 album.addImage(image);
1823 synchronized (images) {
1824 images.put(image.getId(), image);
1826 imageInserter.insertImage(temporaryImage, image);
1831 * Deletes the given image. This method will also delete a matching
1834 * @see #deleteTemporaryImage(TemporaryImage)
1836 * The image to delete
1838 public void deleteImage(Image image) {
1839 checkNotNull(image, "image must not be null");
1840 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1841 deleteTemporaryImage(image.getId());
1842 image.getAlbum().removeImage(image);
1843 synchronized (images) {
1844 images.remove(image.getId());
1846 touchConfiguration();
1850 * Creates a new temporary image.
1853 * The MIME type of the temporary image
1855 * The encoded data of the image
1856 * @return The temporary image
1858 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1859 TemporaryImage temporaryImage = new TemporaryImage();
1860 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1861 synchronized (temporaryImages) {
1862 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1864 return temporaryImage;
1868 * Deletes the given temporary image.
1870 * @param temporaryImage
1871 * The temporary image to delete
1873 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1874 checkNotNull(temporaryImage, "temporaryImage must not be null");
1875 deleteTemporaryImage(temporaryImage.getId());
1879 * Deletes the temporary image with the given ID.
1882 * The ID of the temporary image to delete
1884 public void deleteTemporaryImage(String imageId) {
1885 checkNotNull(imageId, "imageId must not be null");
1886 synchronized (temporaryImages) {
1887 temporaryImages.remove(imageId);
1889 Image image = getImage(imageId, false);
1890 if (image != null) {
1891 imageInserter.cancelImageInsert(image);
1896 * Notifies the core that the configuration, either of the core or of a
1897 * single local Sone, has changed, and that the configuration should be
1900 public void touchConfiguration() {
1901 lastConfigurationUpdate = System.currentTimeMillis();
1912 public void serviceStart() {
1913 loadConfiguration();
1914 updateChecker.start();
1915 identityManager.start();
1916 webOfTrustUpdater.init();
1917 webOfTrustUpdater.start();
1924 public void serviceRun() {
1925 long lastSaved = System.currentTimeMillis();
1926 while (!shouldStop()) {
1928 long now = System.currentTimeMillis();
1929 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1930 for (Sone localSone : getLocalSones()) {
1931 saveSone(localSone);
1933 saveConfiguration();
1943 public void serviceStop() {
1944 synchronized (sones) {
1945 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1946 soneInserter.getValue().stop();
1947 saveSone(soneInserter.getKey());
1950 saveConfiguration();
1951 webOfTrustUpdater.stop();
1952 updateChecker.stop();
1953 soneDownloader.stop();
1954 identityManager.stop();
1962 * Saves the given Sone. This will persist all local settings for the given
1963 * Sone, such as the friends list and similar, private options.
1968 private synchronized void saveSone(Sone sone) {
1969 if (!sone.isLocal()) {
1970 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1973 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1974 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1978 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1980 /* save Sone into configuration. */
1981 String sonePrefix = "Sone/" + sone.getId();
1982 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1983 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1986 Profile profile = sone.getProfile();
1987 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1988 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1989 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1990 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1991 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1992 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1993 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1995 /* save profile fields. */
1996 int fieldCounter = 0;
1997 for (Field profileField : profile.getFields()) {
1998 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1999 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2000 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2002 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2005 int postCounter = 0;
2006 for (Post post : sone.getPosts()) {
2007 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2008 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2009 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2010 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2011 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2013 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2016 int replyCounter = 0;
2017 for (PostReply reply : sone.getReplies()) {
2018 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2019 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2020 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2021 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2022 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2024 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2026 /* save post likes. */
2027 int postLikeCounter = 0;
2028 for (String postId : sone.getLikedPostIds()) {
2029 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2031 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2033 /* save reply likes. */
2034 int replyLikeCounter = 0;
2035 for (String replyId : sone.getLikedReplyIds()) {
2036 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2038 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2041 int friendCounter = 0;
2042 for (String friendId : sone.getFriends()) {
2043 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2045 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2047 /* save albums. first, collect in a flat structure, top-level first. */
2048 List<Album> albums = sone.getAllAlbums();
2050 int albumCounter = 0;
2051 for (Album album : albums) {
2052 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2053 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2054 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2055 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2056 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2057 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2059 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2062 int imageCounter = 0;
2063 for (Album album : albums) {
2064 for (Image image : album.getImages()) {
2065 if (!image.isInserted()) {
2068 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2069 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2070 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2071 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2072 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2073 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2074 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2075 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2076 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2079 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2082 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2083 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2084 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2085 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2087 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2089 configuration.save();
2091 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2093 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2094 } catch (ConfigurationException ce1) {
2095 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2100 * Saves the current options.
2102 private void saveConfiguration() {
2103 synchronized (configuration) {
2104 if (storingConfiguration) {
2105 logger.log(Level.FINE, "Already storing configuration…");
2108 storingConfiguration = true;
2111 /* store the options first. */
2113 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2114 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2115 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2116 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2117 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2118 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2119 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2120 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2121 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2122 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2123 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2124 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2126 /* save known Sones. */
2127 int soneCounter = 0;
2128 synchronized (knownSones) {
2129 for (String knownSoneId : knownSones) {
2130 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2132 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2135 /* save Sone following times. */
2137 synchronized (soneFollowingTimes) {
2138 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2139 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2140 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2143 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2146 /* save known posts. */
2147 int postCounter = 0;
2148 synchronized (knownPosts) {
2149 for (String knownPostId : knownPosts) {
2150 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2152 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2155 /* save known replies. */
2156 int replyCounter = 0;
2157 synchronized (knownReplies) {
2158 for (String knownReplyId : knownReplies) {
2159 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2161 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2164 /* save bookmarked posts. */
2165 int bookmarkedPostCounter = 0;
2166 synchronized (bookmarkedPosts) {
2167 for (String bookmarkedPostId : bookmarkedPosts) {
2168 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2171 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2174 configuration.save();
2176 } catch (ConfigurationException ce1) {
2177 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2179 synchronized (configuration) {
2180 storingConfiguration = false;
2186 * Loads the configuration.
2188 @SuppressWarnings("unchecked")
2189 private void loadConfiguration() {
2190 /* create options. */
2191 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2194 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2195 SoneInserter.setInsertionDelay(newValue);
2199 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2200 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2201 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2202 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2203 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2204 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2205 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2206 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2207 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2210 @SuppressWarnings("synthetic-access")
2211 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2212 fcpInterface.setActive(newValue);
2215 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2218 @SuppressWarnings("synthetic-access")
2219 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2220 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2225 loadConfigurationValue("InsertionDelay");
2226 loadConfigurationValue("PostsPerPage");
2227 loadConfigurationValue("ImagesPerPage");
2228 loadConfigurationValue("CharactersPerPost");
2229 loadConfigurationValue("PostCutOffLength");
2230 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2231 loadConfigurationValue("PositiveTrust");
2232 loadConfigurationValue("NegativeTrust");
2233 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2234 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2235 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2237 /* load known Sones. */
2238 int soneCounter = 0;
2240 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2241 if (knownSoneId == null) {
2244 synchronized (knownSones) {
2245 knownSones.add(knownSoneId);
2249 /* load Sone following times. */
2252 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2253 if (soneId == null) {
2256 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2257 Sone followedSone = getSone(soneId);
2258 if (followedSone == null) {
2259 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2261 synchronized (soneFollowingTimes) {
2262 soneFollowingTimes.put(getSone(soneId), time);
2268 /* load known posts. */
2269 int postCounter = 0;
2271 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2272 if (knownPostId == null) {
2275 synchronized (knownPosts) {
2276 knownPosts.add(knownPostId);
2280 /* load known replies. */
2281 int replyCounter = 0;
2283 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2284 if (knownReplyId == null) {
2287 synchronized (knownReplies) {
2288 knownReplies.add(knownReplyId);
2292 /* load bookmarked posts. */
2293 int bookmarkedPostCounter = 0;
2295 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2296 if (bookmarkedPostId == null) {
2299 synchronized (bookmarkedPosts) {
2300 bookmarkedPosts.add(bookmarkedPostId);
2307 * Loads an {@link Integer} configuration value for the option with the
2308 * given name, logging validation failures.
2311 * The name of the option to load
2313 private void loadConfigurationValue(String optionName) {
2315 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2316 } catch (IllegalArgumentException iae1) {
2317 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2322 * Generate a Sone URI from the given URI and latest edition.
2325 * The URI to derive the Sone URI from
2326 * @return The derived URI
2328 private static FreenetURI getSoneUri(String uriString) {
2330 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2332 } catch (MalformedURLException mue1) {
2333 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2339 * Notifies the core that a new {@link OwnIdentity} was added.
2341 * @param ownIdentityAddedEvent
2345 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2346 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2347 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2348 if (ownIdentity.hasContext("Sone")) {
2349 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2350 addLocalSone(ownIdentity);
2355 * Notifies the core that an {@link OwnIdentity} was removed.
2357 * @param ownIdentityRemovedEvent
2361 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2362 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2363 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2364 trustedIdentities.remove(ownIdentity);
2368 * Notifies the core that a new {@link Identity} was added.
2370 * @param identityAddedEvent
2374 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2375 Identity identity = identityAddedEvent.identity();
2376 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2377 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2378 addRemoteSone(identity);
2382 * Notifies the core that an {@link Identity} was updated.
2384 * @param identityUpdatedEvent
2388 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2389 final Identity identity = identityUpdatedEvent.identity();
2390 soneDownloaders.execute(new Runnable() {
2393 @SuppressWarnings("synthetic-access")
2395 Sone sone = getRemoteSone(identity.getId(), false);
2396 sone.setIdentity(identity);
2397 sone.setLatestEdition(Optional.fromNullable(Longs.tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
2398 soneDownloader.addSone(sone);
2399 soneDownloader.fetchSone(sone);
2405 * Notifies the core that an {@link Identity} was removed.
2407 * @param identityRemovedEvent
2411 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2412 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2413 Identity identity = identityRemovedEvent.identity();
2414 trustedIdentities.get(ownIdentity).remove(identity);
2415 boolean foundIdentity = false;
2416 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2417 if (trustedIdentity.getKey().equals(ownIdentity)) {
2420 if (trustedIdentity.getValue().contains(identity)) {
2421 foundIdentity = true;
2424 if (foundIdentity) {
2425 /* some local identity still trusts this identity, don’t remove. */
2428 Sone sone = getSone(identity.getId(), false);
2430 /* TODO - we don’t have the Sone anymore. should this happen? */
2433 synchronized (posts) {
2434 synchronized (knownPosts) {
2435 for (Post post : sone.getPosts()) {
2436 posts.remove(post.getId());
2437 eventBus.post(new PostRemovedEvent(post));
2441 synchronized (replies) {
2442 synchronized (knownReplies) {
2443 for (PostReply reply : sone.getReplies()) {
2444 replies.remove(reply.getId());
2445 eventBus.post(new PostReplyRemovedEvent(reply));
2449 synchronized (sones) {
2450 sones.remove(identity.getId());
2452 eventBus.post(new SoneRemovedEvent(sone));
2456 * Deletes the temporary image.
2458 * @param imageInsertFinishedEvent
2462 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2463 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2464 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2465 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2466 touchConfiguration();