2 * Sone - Core.java - Copyright © 2010–2012 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 java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
39 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
40 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
41 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
42 import net.pterodactylus.sone.data.Album;
43 import net.pterodactylus.sone.data.Client;
44 import net.pterodactylus.sone.data.Image;
45 import net.pterodactylus.sone.data.Post;
46 import net.pterodactylus.sone.data.PostReply;
47 import net.pterodactylus.sone.data.Profile;
48 import net.pterodactylus.sone.data.Profile.Field;
49 import net.pterodactylus.sone.data.Reply;
50 import net.pterodactylus.sone.data.Sone;
51 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
52 import net.pterodactylus.sone.data.Sone.SoneStatus;
53 import net.pterodactylus.sone.data.TemporaryImage;
54 import net.pterodactylus.sone.data.impl.PostImpl;
55 import net.pterodactylus.sone.fcp.FcpInterface;
56 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
57 import net.pterodactylus.sone.freenet.wot.Identity;
58 import net.pterodactylus.sone.freenet.wot.IdentityListener;
59 import net.pterodactylus.sone.freenet.wot.IdentityManager;
60 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
61 import net.pterodactylus.sone.main.SonePlugin;
62 import net.pterodactylus.util.config.Configuration;
63 import net.pterodactylus.util.config.ConfigurationException;
64 import net.pterodactylus.util.logging.Logging;
65 import net.pterodactylus.util.number.Numbers;
66 import net.pterodactylus.util.service.AbstractService;
67 import net.pterodactylus.util.thread.NamedThreadFactory;
68 import net.pterodactylus.util.thread.Ticker;
69 import net.pterodactylus.util.validation.EqualityValidator;
70 import net.pterodactylus.util.validation.IntegerRangeValidator;
71 import net.pterodactylus.util.validation.OrValidator;
72 import net.pterodactylus.util.validation.Validation;
73 import net.pterodactylus.util.version.Version;
75 import com.google.common.base.Predicate;
76 import com.google.common.collect.Collections2;
77 import com.google.common.eventbus.EventBus;
78 import com.google.inject.Inject;
80 import freenet.keys.FreenetURI;
85 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
87 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
90 private static final Logger logger = Logging.getLogger(Core.class);
92 /** The start time. */
93 private final long startupTime = System.currentTimeMillis();
96 private final Options options = new Options();
98 /** The preferences. */
99 private final Preferences preferences = new Preferences(options);
101 /** The core listener manager. */
102 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
104 /** The event bus. */
105 private final EventBus eventBus;
107 /** The configuration. */
108 private Configuration configuration;
110 /** Whether we’re currently saving the configuration. */
111 private boolean storingConfiguration = false;
113 /** The identity manager. */
114 private final IdentityManager identityManager;
116 /** Interface to freenet. */
117 private final FreenetInterface freenetInterface;
119 /** The Sone downloader. */
120 private final SoneDownloader soneDownloader;
122 /** The image inserter. */
123 private final ImageInserter imageInserter;
125 /** Sone downloader thread-pool. */
126 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
128 /** The update checker. */
129 private final UpdateChecker updateChecker;
131 /** The trust updater. */
132 private final WebOfTrustUpdater webOfTrustUpdater;
134 /** The FCP interface. */
135 private volatile FcpInterface fcpInterface;
137 /** The times Sones were followed. */
138 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
140 /** Locked local Sones. */
141 /* synchronize on itself. */
142 private final Set<Sone> lockedSones = new HashSet<Sone>();
144 /** Sone inserters. */
145 /* synchronize access on this on sones. */
146 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
148 /** Sone rescuers. */
149 /* synchronize access on this on sones. */
150 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
153 /* synchronize access on this on itself. */
154 private final Map<String, Sone> sones = new HashMap<String, Sone>();
156 /** All known Sones. */
157 private final Set<String> knownSones = new HashSet<String>();
160 private final Map<String, Post> posts = new HashMap<String, Post>();
162 /** All known posts. */
163 private final Set<String> knownPosts = new HashSet<String>();
166 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
168 /** All known replies. */
169 private final Set<String> knownReplies = new HashSet<String>();
171 /** All bookmarked posts. */
172 /* synchronize access on itself. */
173 private final Set<String> bookmarkedPosts = new HashSet<String>();
175 /** Trusted identities, sorted by own identities. */
176 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
178 /** All known albums. */
179 private final Map<String, Album> albums = new HashMap<String, Album>();
181 /** All known images. */
182 private final Map<String, Image> images = new HashMap<String, Image>();
184 /** All temporary images. */
185 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
187 /** Ticker for threads that mark own elements as known. */
188 private final Ticker localElementTicker = new Ticker();
190 /** The time the configuration was last touched. */
191 private volatile long lastConfigurationUpdate;
194 * Creates a new core.
196 * @param configuration
197 * The configuration of the core
198 * @param freenetInterface
199 * The freenet interface
200 * @param identityManager
201 * The identity manager
202 * @param webOfTrustUpdater
203 * The WebOfTrust updater
208 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
210 this.configuration = configuration;
211 this.freenetInterface = freenetInterface;
212 this.identityManager = identityManager;
213 this.soneDownloader = new SoneDownloader(this, freenetInterface);
214 this.imageInserter = new ImageInserter(this, freenetInterface);
215 this.updateChecker = new UpdateChecker(freenetInterface);
216 this.webOfTrustUpdater = webOfTrustUpdater;
217 this.eventBus = eventBus;
221 // LISTENER MANAGEMENT
225 * Adds a new core listener.
227 * @param coreListener
228 * The listener to add
230 public void addCoreListener(CoreListener coreListener) {
231 coreListenerManager.addListener(coreListener);
235 * Removes a core listener.
237 * @param coreListener
238 * The listener to remove
240 public void removeCoreListener(CoreListener coreListener) {
241 coreListenerManager.removeListener(coreListener);
249 * Returns the time Sone was started.
251 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
253 public long getStartupTime() {
258 * Sets the configuration to use. This will automatically save the current
259 * configuration to the given configuration.
261 * @param configuration
262 * The new configuration to use
264 public void setConfiguration(Configuration configuration) {
265 this.configuration = configuration;
266 touchConfiguration();
270 * Returns the options used by the core.
272 * @return The options of the core
274 public Preferences getPreferences() {
279 * Returns the identity manager used by the core.
281 * @return The identity manager
283 public IdentityManager getIdentityManager() {
284 return identityManager;
288 * Returns the update checker.
290 * @return The update checker
292 public UpdateChecker getUpdateChecker() {
293 return updateChecker;
297 * Sets the FCP interface to use.
299 * @param fcpInterface
300 * The FCP interface to use
302 public void setFcpInterface(FcpInterface fcpInterface) {
303 this.fcpInterface = fcpInterface;
307 * Returns the Sone rescuer for the given local Sone.
310 * The local Sone to get the rescuer for
311 * @return The Sone rescuer for the given Sone
313 public SoneRescuer getSoneRescuer(Sone sone) {
314 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
315 synchronized (sones) {
316 SoneRescuer soneRescuer = soneRescuers.get(sone);
317 if (soneRescuer == null) {
318 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
319 soneRescuers.put(sone, soneRescuer);
327 * Returns whether the given Sone is currently locked.
331 * @return {@code true} if the Sone is locked, {@code false} if it is not
333 public boolean isLocked(Sone sone) {
334 synchronized (lockedSones) {
335 return lockedSones.contains(sone);
340 * Returns all Sones, remote and local.
344 public Set<Sone> getSones() {
345 return new HashSet<Sone>(sones.values());
349 * Returns the Sone with the given ID, regardless whether it’s local or
353 * The ID of the Sone to get
354 * @return The Sone with the given ID, or {@code null} if there is no such
357 public Sone getSone(String id) {
358 return getSone(id, true);
362 * Returns the Sone with the given ID, regardless whether it’s local or
366 * The ID of the Sone to get
368 * {@code true} to create a new Sone if none exists,
369 * {@code false} to return {@code null} if a Sone with the given
371 * @return The Sone with the given ID, or {@code null} if there is no such
375 public Sone getSone(String id, boolean create) {
376 synchronized (sones) {
377 if (!sones.containsKey(id)) {
378 Sone sone = new Sone(id, false);
381 return sones.get(id);
386 * Checks whether the core knows a Sone with the given ID.
390 * @return {@code true} if there is a Sone with the given ID, {@code false}
393 public boolean hasSone(String id) {
394 synchronized (sones) {
395 return sones.containsKey(id);
400 * Returns all local Sones.
402 * @return All local Sones
404 public Collection<Sone> getLocalSones() {
405 synchronized (sones) {
406 return Collections2.filter(sones.values(), new Predicate<Sone>() {
409 public boolean apply(Sone sone) {
410 return sone.isLocal();
417 * Returns the local Sone with the given ID, optionally creating a new Sone.
422 * {@code true} to create a new Sone if none exists,
423 * {@code false} to return null if none exists
424 * @return The Sone with the given ID, or {@code null}
426 public Sone getLocalSone(String id, boolean create) {
427 synchronized (sones) {
428 Sone sone = sones.get(id);
429 if ((sone == null) && create) {
430 sone = new Sone(id, true);
433 if ((sone != null) && !sone.isLocal()) {
434 sone = new Sone(id, true);
442 * Returns all remote Sones.
444 * @return All remote Sones
446 public Collection<Sone> getRemoteSones() {
447 synchronized (sones) {
448 return Collections2.filter(sones.values(), new Predicate<Sone>() {
451 public boolean apply(Sone sone) {
452 return !sone.isLocal();
459 * Returns the remote Sone with the given ID.
462 * The ID of the remote Sone to get
464 * {@code true} to always create a Sone, {@code false} to return
465 * {@code null} if no Sone with the given ID exists
466 * @return The Sone with the given ID
468 public Sone getRemoteSone(String id, boolean create) {
469 synchronized (sones) {
470 Sone sone = sones.get(id);
471 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
472 sone = new Sone(id, false);
480 * Returns whether the given Sone has been modified.
483 * The Sone to check for modifications
484 * @return {@code true} if a modification has been detected in the Sone,
485 * {@code false} otherwise
487 public boolean isModifiedSone(Sone sone) {
488 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
492 * Returns the time when the given was first followed by any local Sone.
495 * The Sone to get the time for
496 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
497 * been followed, or {@link Long#MAX_VALUE}
499 public long getSoneFollowingTime(Sone sone) {
500 synchronized (soneFollowingTimes) {
501 if (soneFollowingTimes.containsKey(sone)) {
502 return soneFollowingTimes.get(sone);
504 return Long.MAX_VALUE;
509 * Returns whether the target Sone is trusted by the origin Sone.
515 * @return {@code true} if the target Sone is trusted by the origin Sone
517 public boolean isSoneTrusted(Sone origin, Sone target) {
518 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
519 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
523 * Returns the post with the given ID.
526 * The ID of the post to get
527 * @return The post with the given ID, or a new post with the given ID
529 public Post getPost(String postId) {
530 return getPost(postId, true);
534 * Returns the post with the given ID, optionally creating a new post.
537 * The ID of the post to get
539 * {@code true} it create a new post if no post with the given ID
540 * exists, {@code false} to return {@code null}
541 * @return The post, or {@code null} if there is no such post
544 public Post getPost(String postId, boolean create) {
545 synchronized (posts) {
546 Post post = posts.get(postId);
547 if ((post == null) && create) {
548 post = new PostImpl(postId);
549 posts.put(postId, post);
556 * Returns all posts that have the given Sone as recipient.
558 * @see Post#getRecipient()
560 * The recipient of the posts
561 * @return All posts that have the given Sone as recipient
563 public Set<Post> getDirectedPosts(Sone recipient) {
564 Validation.begin().isNotNull("Recipient", recipient).check();
565 Set<Post> directedPosts = new HashSet<Post>();
566 synchronized (posts) {
567 for (Post post : posts.values()) {
568 if (recipient.equals(post.getRecipient())) {
569 directedPosts.add(post);
573 return directedPosts;
577 * Returns the reply with the given ID. If there is no reply with the given
578 * ID yet, a new one is created, unless {@code create} is false in which
579 * case {@code null} is returned.
582 * The ID of the reply to get
584 * {@code true} to always return a {@link Reply}, {@code false}
585 * to return {@code null} if no reply can be found
586 * @return The reply, or {@code null} if there is no such reply
588 public PostReply getPostReply(String replyId, boolean create) {
589 synchronized (replies) {
590 PostReply reply = replies.get(replyId);
591 if (create && (reply == null)) {
592 reply = new PostReply(replyId);
593 replies.put(replyId, reply);
600 * Returns all replies for the given post, order ascending by time.
603 * The post to get all replies for
604 * @return All replies for the given post
606 public List<PostReply> getReplies(Post post) {
607 Set<Sone> sones = getSones();
608 List<PostReply> replies = new ArrayList<PostReply>();
609 for (Sone sone : sones) {
610 for (PostReply reply : sone.getReplies()) {
611 if (reply.getPost().equals(post)) {
616 Collections.sort(replies, Reply.TIME_COMPARATOR);
621 * Returns all Sones that have liked the given post.
624 * The post to get the liking Sones for
625 * @return The Sones that like the given post
627 public Set<Sone> getLikes(Post post) {
628 Set<Sone> sones = new HashSet<Sone>();
629 for (Sone sone : getSones()) {
630 if (sone.getLikedPostIds().contains(post.getId())) {
638 * Returns all Sones that have liked the given reply.
641 * The reply to get the liking Sones for
642 * @return The Sones that like the given reply
644 public Set<Sone> getLikes(PostReply reply) {
645 Set<Sone> sones = new HashSet<Sone>();
646 for (Sone sone : getSones()) {
647 if (sone.getLikedReplyIds().contains(reply.getId())) {
655 * Returns whether the given post is bookmarked.
659 * @return {@code true} if the given post is bookmarked, {@code false}
662 public boolean isBookmarked(Post post) {
663 return isPostBookmarked(post.getId());
667 * Returns whether the post with the given ID is bookmarked.
670 * The ID of the post to check
671 * @return {@code true} if the post with the given ID is bookmarked,
672 * {@code false} otherwise
674 public boolean isPostBookmarked(String id) {
675 synchronized (bookmarkedPosts) {
676 return bookmarkedPosts.contains(id);
681 * Returns all currently known bookmarked posts.
683 * @return All bookmarked posts
685 public Set<Post> getBookmarkedPosts() {
686 Set<Post> posts = new HashSet<Post>();
687 synchronized (bookmarkedPosts) {
688 for (String bookmarkedPostId : bookmarkedPosts) {
689 Post post = getPost(bookmarkedPostId, false);
699 * Returns the album with the given ID, creating a new album if no album
700 * with the given ID can be found.
703 * The ID of the album
704 * @return The album with the given ID
706 public Album getAlbum(String albumId) {
707 return getAlbum(albumId, true);
711 * Returns the album with the given ID, optionally creating a new album if
712 * an album with the given ID can not be found.
715 * The ID of the album
717 * {@code true} to create a new album if none exists for the
719 * @return The album with the given ID, or {@code null} if no album with the
720 * given ID exists and {@code create} is {@code false}
722 public Album getAlbum(String albumId, boolean create) {
723 synchronized (albums) {
724 Album album = albums.get(albumId);
725 if (create && (album == null)) {
726 album = new Album(albumId);
727 albums.put(albumId, album);
734 * Returns the image with the given ID, creating it if necessary.
737 * The ID of the image
738 * @return The image with the given ID
740 public Image getImage(String imageId) {
741 return getImage(imageId, true);
745 * Returns the image with the given ID, optionally creating it if it does
749 * The ID of the image
751 * {@code true} to create an image if none exists with the given
753 * @return The image with the given ID, or {@code null} if none exists and
756 public Image getImage(String imageId, boolean create) {
757 synchronized (images) {
758 Image image = images.get(imageId);
759 if (create && (image == null)) {
760 image = new Image(imageId);
761 images.put(imageId, image);
768 * Returns the temporary image with the given ID.
771 * The ID of the temporary image
772 * @return The temporary image, or {@code null} if there is no temporary
773 * image with the given ID
775 public TemporaryImage getTemporaryImage(String imageId) {
776 synchronized (temporaryImages) {
777 return temporaryImages.get(imageId);
786 * Locks the given Sone. A locked Sone will not be inserted by
787 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
793 public void lockSone(Sone sone) {
794 synchronized (lockedSones) {
795 if (lockedSones.add(sone)) {
796 coreListenerManager.fireSoneLocked(sone);
802 * Unlocks the given Sone.
804 * @see #lockSone(Sone)
808 public void unlockSone(Sone sone) {
809 synchronized (lockedSones) {
810 if (lockedSones.remove(sone)) {
811 coreListenerManager.fireSoneUnlocked(sone);
817 * Adds a local Sone from the given own identity.
820 * The own identity to create a Sone from
821 * @return The added (or already existing) Sone
823 public Sone addLocalSone(OwnIdentity ownIdentity) {
824 if (ownIdentity == null) {
825 logger.log(Level.WARNING, "Given OwnIdentity is null!");
828 synchronized (sones) {
831 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
832 } catch (MalformedURLException mue1) {
833 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
836 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
837 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
839 /* TODO - load posts ’n stuff */
840 sones.put(ownIdentity.getId(), sone);
841 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
842 soneInserter.addSoneInsertListener(this);
843 soneInserters.put(sone, soneInserter);
844 sone.setStatus(SoneStatus.idle);
846 soneInserter.start();
852 * Creates a new Sone for the given own identity.
855 * The own identity to create a Sone for
856 * @return The created Sone
858 public Sone createSone(OwnIdentity ownIdentity) {
859 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
860 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
863 Sone sone = addLocalSone(ownIdentity);
864 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
865 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
866 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
867 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
868 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
869 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
871 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
872 touchConfiguration();
877 * Adds the Sone of the given identity.
880 * The identity whose Sone to add
881 * @return The added or already existing Sone
883 public Sone addRemoteSone(Identity identity) {
884 if (identity == null) {
885 logger.log(Level.WARNING, "Given Identity is null!");
888 synchronized (sones) {
889 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
890 boolean newSone = sone.getRequestUri() == null;
891 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
892 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
894 synchronized (knownSones) {
895 newSone = !knownSones.contains(sone.getId());
897 sone.setKnown(!newSone);
899 eventBus.post(new NewSoneFoundEvent(sone));
900 for (Sone localSone : getLocalSones()) {
901 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
902 followSone(localSone, sone);
907 soneDownloader.addSone(sone);
908 soneDownloaders.execute(new Runnable() {
911 @SuppressWarnings("synthetic-access")
913 soneDownloader.fetchSone(sone, sone.getRequestUri());
922 * Lets the given local Sone follow the Sone with the given ID.
925 * The local Sone that should follow another Sone
927 * The ID of the Sone to follow
929 public void followSone(Sone sone, String soneId) {
930 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
931 Sone followedSone = getSone(soneId, true);
932 if (followedSone == null) {
933 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
936 followSone(sone, getSone(soneId));
940 * Lets the given local Sone follow the other given Sone. If the given Sone
941 * was not followed by any local Sone before, this will mark all elements of
942 * the followed Sone as read that have been created before the current
946 * The local Sone that should follow the other Sone
947 * @param followedSone
948 * The Sone that should be followed
950 public void followSone(Sone sone, Sone followedSone) {
951 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
952 sone.addFriend(followedSone.getId());
953 synchronized (soneFollowingTimes) {
954 if (!soneFollowingTimes.containsKey(followedSone)) {
955 long now = System.currentTimeMillis();
956 soneFollowingTimes.put(followedSone, now);
957 for (Post post : followedSone.getPosts()) {
958 if (post.getTime() < now) {
962 for (PostReply reply : followedSone.getReplies()) {
963 if (reply.getTime() < now) {
964 markReplyKnown(reply);
969 touchConfiguration();
973 * Lets the given local Sone unfollow the Sone with the given ID.
976 * The local Sone that should unfollow another Sone
978 * The ID of the Sone being unfollowed
980 public void unfollowSone(Sone sone, String soneId) {
981 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
982 unfollowSone(sone, getSone(soneId, false));
986 * Lets the given local Sone unfollow the other given Sone. If the given
987 * local Sone is the last local Sone that followed the given Sone, its
988 * following time will be removed.
991 * The local Sone that should unfollow another Sone
992 * @param unfollowedSone
993 * The Sone being unfollowed
995 public void unfollowSone(Sone sone, Sone unfollowedSone) {
996 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
997 sone.removeFriend(unfollowedSone.getId());
998 boolean unfollowedSoneStillFollowed = false;
999 for (Sone localSone : getLocalSones()) {
1000 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1002 if (!unfollowedSoneStillFollowed) {
1003 synchronized (soneFollowingTimes) {
1004 soneFollowingTimes.remove(unfollowedSone);
1007 touchConfiguration();
1011 * Sets the trust value of the given origin Sone for the target Sone.
1018 * The trust value (from {@code -100} to {@code 100})
1020 public void setTrust(Sone origin, Sone target, int trustValue) {
1021 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
1022 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1026 * Removes any trust assignment for the given target Sone.
1033 public void removeTrust(Sone origin, Sone target) {
1034 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1035 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1039 * Assigns the configured positive trust value for the given target.
1046 public void trustSone(Sone origin, Sone target) {
1047 setTrust(origin, target, preferences.getPositiveTrust());
1051 * Assigns the configured negative trust value for the given target.
1058 public void distrustSone(Sone origin, Sone target) {
1059 setTrust(origin, target, preferences.getNegativeTrust());
1063 * Removes the trust assignment for the given target.
1070 public void untrustSone(Sone origin, Sone target) {
1071 removeTrust(origin, target);
1075 * Updates the stored Sone with the given Sone.
1080 public void updateSone(Sone sone) {
1081 updateSone(sone, false);
1085 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1086 * {@code true}, an older Sone than the current Sone can be given to restore
1090 * The Sone to update
1091 * @param soneRescueMode
1092 * {@code true} if the stored Sone should be updated regardless
1093 * of the age of the given Sone
1095 public void updateSone(Sone sone, boolean soneRescueMode) {
1096 if (hasSone(sone.getId())) {
1097 Sone storedSone = getSone(sone.getId());
1098 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1099 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1102 synchronized (posts) {
1103 if (!soneRescueMode) {
1104 for (Post post : storedSone.getPosts()) {
1105 posts.remove(post.getId());
1106 if (!sone.getPosts().contains(post)) {
1107 coreListenerManager.firePostRemoved(post);
1111 List<Post> storedPosts = storedSone.getPosts();
1112 synchronized (knownPosts) {
1113 for (Post post : sone.getPosts()) {
1114 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1115 if (!storedPosts.contains(post)) {
1116 if (post.getTime() < getSoneFollowingTime(sone)) {
1117 knownPosts.add(post.getId());
1118 post.setKnown(true);
1119 } else if (!knownPosts.contains(post.getId())) {
1120 eventBus.post(new NewPostFoundEvent(post));
1123 posts.put(post.getId(), post);
1127 synchronized (replies) {
1128 if (!soneRescueMode) {
1129 for (PostReply reply : storedSone.getReplies()) {
1130 replies.remove(reply.getId());
1131 if (!sone.getReplies().contains(reply)) {
1132 coreListenerManager.fireReplyRemoved(reply);
1136 Set<PostReply> storedReplies = storedSone.getReplies();
1137 synchronized (knownReplies) {
1138 for (PostReply reply : sone.getReplies()) {
1139 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1140 if (!storedReplies.contains(reply)) {
1141 if (reply.getTime() < getSoneFollowingTime(sone)) {
1142 knownReplies.add(reply.getId());
1143 reply.setKnown(true);
1144 } else if (!knownReplies.contains(reply.getId())) {
1145 eventBus.post(new NewPostReplyFoundEvent(reply));
1148 replies.put(reply.getId(), reply);
1152 synchronized (albums) {
1153 synchronized (images) {
1154 for (Album album : storedSone.getAlbums()) {
1155 albums.remove(album.getId());
1156 for (Image image : album.getImages()) {
1157 images.remove(image.getId());
1160 for (Album album : sone.getAlbums()) {
1161 albums.put(album.getId(), album);
1162 for (Image image : album.getImages()) {
1163 images.put(image.getId(), image);
1168 synchronized (storedSone) {
1169 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1170 storedSone.setTime(sone.getTime());
1172 storedSone.setClient(sone.getClient());
1173 storedSone.setProfile(sone.getProfile());
1174 if (soneRescueMode) {
1175 for (Post post : sone.getPosts()) {
1176 storedSone.addPost(post);
1178 for (PostReply reply : sone.getReplies()) {
1179 storedSone.addReply(reply);
1181 for (String likedPostId : sone.getLikedPostIds()) {
1182 storedSone.addLikedPostId(likedPostId);
1184 for (String likedReplyId : sone.getLikedReplyIds()) {
1185 storedSone.addLikedReplyId(likedReplyId);
1187 for (Album album : sone.getAlbums()) {
1188 storedSone.addAlbum(album);
1191 storedSone.setPosts(sone.getPosts());
1192 storedSone.setReplies(sone.getReplies());
1193 storedSone.setLikePostIds(sone.getLikedPostIds());
1194 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1195 storedSone.setAlbums(sone.getAlbums());
1197 storedSone.setLatestEdition(sone.getLatestEdition());
1203 * Deletes the given Sone. This will remove the Sone from the
1204 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1205 * remove the context from its identity.
1208 * The Sone to delete
1210 public void deleteSone(Sone sone) {
1211 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1212 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1215 synchronized (sones) {
1216 if (!getLocalSones().contains(sone)) {
1217 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1220 sones.remove(sone.getId());
1221 SoneInserter soneInserter = soneInserters.remove(sone);
1222 soneInserter.removeSoneInsertListener(this);
1223 soneInserter.stop();
1225 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1226 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1228 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1229 } catch (ConfigurationException ce1) {
1230 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1235 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1236 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1239 * The Sone to mark as known
1241 public void markSoneKnown(Sone sone) {
1242 if (!sone.isKnown()) {
1243 sone.setKnown(true);
1244 synchronized (knownSones) {
1245 knownSones.add(sone.getId());
1247 eventBus.post(new MarkSoneKnownEvent(sone));
1248 touchConfiguration();
1253 * Loads and updates the given Sone from the configuration. If any error is
1254 * encountered, loading is aborted and the given Sone is not changed.
1257 * The Sone to load and update
1259 public void loadSone(Sone sone) {
1260 if (!sone.isLocal()) {
1261 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1265 /* initialize options. */
1266 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1267 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1268 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1269 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1270 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1271 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1274 String sonePrefix = "Sone/" + sone.getId();
1275 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1276 if (soneTime == null) {
1277 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1280 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1283 Profile profile = new Profile(sone);
1284 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1285 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1286 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1287 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1288 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1289 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1291 /* load profile fields. */
1293 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1294 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1295 if (fieldName == null) {
1298 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1299 profile.addField(fieldName).setValue(fieldValue);
1303 Set<Post> posts = new HashSet<Post>();
1305 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1306 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1307 if (postId == null) {
1310 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1311 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1312 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1313 if ((postTime == 0) || (postText == null)) {
1314 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1317 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1318 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1319 post.setRecipient(getSone(postRecipientId));
1325 Set<PostReply> replies = new HashSet<PostReply>();
1327 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1328 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1329 if (replyId == null) {
1332 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1333 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1334 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1335 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1336 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1339 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1342 /* load post likes. */
1343 Set<String> likedPostIds = new HashSet<String>();
1345 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1346 if (likedPostId == null) {
1349 likedPostIds.add(likedPostId);
1352 /* load reply likes. */
1353 Set<String> likedReplyIds = new HashSet<String>();
1355 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1356 if (likedReplyId == null) {
1359 likedReplyIds.add(likedReplyId);
1363 Set<String> friends = new HashSet<String>();
1365 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1366 if (friendId == null) {
1369 friends.add(friendId);
1373 List<Album> topLevelAlbums = new ArrayList<Album>();
1374 int albumCounter = 0;
1376 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1377 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1378 if (albumId == null) {
1381 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1382 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1383 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1384 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1385 if ((albumTitle == null) || (albumDescription == null)) {
1386 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1389 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1390 if (albumParentId != null) {
1391 Album parentAlbum = getAlbum(albumParentId, false);
1392 if (parentAlbum == null) {
1393 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1396 parentAlbum.addAlbum(album);
1398 if (!topLevelAlbums.contains(album)) {
1399 topLevelAlbums.add(album);
1405 int imageCounter = 0;
1407 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1408 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1409 if (imageId == null) {
1412 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1413 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1414 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1415 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1416 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1417 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1418 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1419 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1420 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1423 Album album = getAlbum(albumId, false);
1424 if (album == null) {
1425 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1428 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1429 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1430 album.addImage(image);
1434 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1435 if (avatarId != null) {
1436 profile.setAvatar(getImage(avatarId, false));
1440 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1441 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1443 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1444 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1445 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1447 /* if we’re still here, Sone was loaded successfully. */
1448 synchronized (sone) {
1449 sone.setTime(soneTime);
1450 sone.setProfile(profile);
1451 sone.setPosts(posts);
1452 sone.setReplies(replies);
1453 sone.setLikePostIds(likedPostIds);
1454 sone.setLikeReplyIds(likedReplyIds);
1455 for (String friendId : friends) {
1456 followSone(sone, friendId);
1458 sone.setAlbums(topLevelAlbums);
1459 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1461 synchronized (knownSones) {
1462 for (String friend : friends) {
1463 knownSones.add(friend);
1466 synchronized (knownPosts) {
1467 for (Post post : posts) {
1468 knownPosts.add(post.getId());
1471 synchronized (knownReplies) {
1472 for (PostReply reply : replies) {
1473 knownReplies.add(reply.getId());
1479 * Creates a new post.
1482 * The Sone that creates the post
1484 * The text of the post
1485 * @return The created post
1487 public Post createPost(Sone sone, String text) {
1488 return createPost(sone, System.currentTimeMillis(), text);
1492 * Creates a new post.
1495 * The Sone that creates the post
1497 * The time of the post
1499 * The text of the post
1500 * @return The created post
1502 public Post createPost(Sone sone, long time, String text) {
1503 return createPost(sone, null, time, text);
1507 * Creates a new post.
1510 * The Sone that creates the post
1512 * The recipient Sone, or {@code null} if this post does not have
1515 * The text of the post
1516 * @return The created post
1518 public Post createPost(Sone sone, Sone recipient, String text) {
1519 return createPost(sone, recipient, System.currentTimeMillis(), text);
1523 * Creates a new post.
1526 * The Sone that creates the post
1528 * The recipient Sone, or {@code null} if this post does not have
1531 * The time of the post
1533 * The text of the post
1534 * @return The created post
1536 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1537 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1538 if (!sone.isLocal()) {
1539 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1542 final Post post = new PostImpl(sone, time, text);
1543 if (recipient != null) {
1544 post.setRecipient(recipient);
1546 synchronized (posts) {
1547 posts.put(post.getId(), post);
1549 eventBus.post(new NewPostFoundEvent(post));
1551 touchConfiguration();
1552 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1559 markPostKnown(post);
1561 }, "Mark " + post + " read.");
1566 * Deletes the given post.
1569 * The post to delete
1571 public void deletePost(Post post) {
1572 if (!post.getSone().isLocal()) {
1573 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1576 post.getSone().removePost(post);
1577 synchronized (posts) {
1578 posts.remove(post.getId());
1580 coreListenerManager.firePostRemoved(post);
1581 markPostKnown(post);
1582 touchConfiguration();
1586 * Marks the given post as known, if it is currently not a known post
1587 * (according to {@link Post#isKnown()}).
1590 * The post to mark as known
1592 public void markPostKnown(Post post) {
1593 post.setKnown(true);
1594 synchronized (knownPosts) {
1595 coreListenerManager.fireMarkPostKnown(post);
1596 if (knownPosts.add(post.getId())) {
1597 touchConfiguration();
1600 for (PostReply reply : getReplies(post)) {
1601 markReplyKnown(reply);
1606 * Bookmarks the given post.
1609 * The post to bookmark
1611 public void bookmark(Post post) {
1612 bookmarkPost(post.getId());
1616 * Bookmarks the post with the given ID.
1619 * The ID of the post to bookmark
1621 public void bookmarkPost(String id) {
1622 synchronized (bookmarkedPosts) {
1623 bookmarkedPosts.add(id);
1628 * Removes the given post from the bookmarks.
1631 * The post to unbookmark
1633 public void unbookmark(Post post) {
1634 unbookmarkPost(post.getId());
1638 * Removes the post with the given ID from the bookmarks.
1641 * The ID of the post to unbookmark
1643 public void unbookmarkPost(String id) {
1644 synchronized (bookmarkedPosts) {
1645 bookmarkedPosts.remove(id);
1650 * Creates a new reply.
1653 * The Sone that creates the reply
1655 * The post that this reply refers to
1657 * The text of the reply
1658 * @return The created reply
1660 public PostReply createReply(Sone sone, Post post, String text) {
1661 return createReply(sone, post, System.currentTimeMillis(), text);
1665 * Creates a new reply.
1668 * The Sone that creates the reply
1670 * The post that this reply refers to
1672 * The time of the reply
1674 * The text of the reply
1675 * @return The created reply
1677 public PostReply createReply(Sone sone, Post post, long time, String text) {
1678 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
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 PostReply(sone, post, System.currentTimeMillis(), text);
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 coreListenerManager.fireMarkReplyKnown(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 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1789 if (!album.isEmpty()) {
1792 if (album.getParent() == null) {
1793 album.getSone().removeAlbum(album);
1795 album.getParent().removeAlbum(album);
1797 synchronized (albums) {
1798 albums.remove(album.getId());
1800 touchConfiguration();
1804 * Creates a new image.
1807 * The Sone creating the image
1809 * The album the image will be inserted into
1810 * @param temporaryImage
1811 * The temporary image to create the image from
1812 * @return The newly created image
1814 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1815 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1816 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1817 album.addImage(image);
1818 synchronized (images) {
1819 images.put(image.getId(), image);
1821 imageInserter.insertImage(temporaryImage, image);
1826 * Deletes the given image. This method will also delete a matching
1829 * @see #deleteTemporaryImage(TemporaryImage)
1831 * The image to delete
1833 public void deleteImage(Image image) {
1834 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1835 deleteTemporaryImage(image.getId());
1836 image.getAlbum().removeImage(image);
1837 synchronized (images) {
1838 images.remove(image.getId());
1840 touchConfiguration();
1844 * Creates a new temporary image.
1847 * The MIME type of the temporary image
1849 * The encoded data of the image
1850 * @return The temporary image
1852 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1853 TemporaryImage temporaryImage = new TemporaryImage();
1854 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1855 synchronized (temporaryImages) {
1856 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1858 return temporaryImage;
1862 * Deletes the given temporary image.
1864 * @param temporaryImage
1865 * The temporary image to delete
1867 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1868 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1869 deleteTemporaryImage(temporaryImage.getId());
1873 * Deletes the temporary image with the given ID.
1876 * The ID of the temporary image to delete
1878 public void deleteTemporaryImage(String imageId) {
1879 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1880 synchronized (temporaryImages) {
1881 temporaryImages.remove(imageId);
1883 Image image = getImage(imageId, false);
1884 if (image != null) {
1885 imageInserter.cancelImageInsert(image);
1890 * Notifies the core that the configuration, either of the core or of a
1891 * single local Sone, has changed, and that the configuration should be
1894 public void touchConfiguration() {
1895 lastConfigurationUpdate = System.currentTimeMillis();
1906 public void serviceStart() {
1907 loadConfiguration();
1908 updateChecker.addUpdateListener(this);
1909 updateChecker.start();
1910 identityManager.addIdentityListener(this);
1911 identityManager.start();
1912 webOfTrustUpdater.init();
1913 webOfTrustUpdater.start();
1920 public void serviceRun() {
1921 long lastSaved = System.currentTimeMillis();
1922 while (!shouldStop()) {
1924 long now = System.currentTimeMillis();
1925 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1926 for (Sone localSone : getLocalSones()) {
1927 saveSone(localSone);
1929 saveConfiguration();
1939 public void serviceStop() {
1940 synchronized (sones) {
1941 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1942 soneInserter.getValue().removeSoneInsertListener(this);
1943 soneInserter.getValue().stop();
1944 saveSone(soneInserter.getKey());
1947 saveConfiguration();
1948 webOfTrustUpdater.stop();
1949 updateChecker.stop();
1950 updateChecker.removeUpdateListener(this);
1951 soneDownloader.stop();
1952 identityManager.removeIdentityListener(this);
1953 identityManager.stop();
1961 * Saves the given Sone. This will persist all local settings for the given
1962 * Sone, such as the friends list and similar, private options.
1967 private synchronized void saveSone(Sone sone) {
1968 if (!sone.isLocal()) {
1969 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1972 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1973 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1977 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1979 /* save Sone into configuration. */
1980 String sonePrefix = "Sone/" + sone.getId();
1981 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1982 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1985 Profile profile = sone.getProfile();
1986 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1987 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1988 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1989 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1990 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1991 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1992 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1994 /* save profile fields. */
1995 int fieldCounter = 0;
1996 for (Field profileField : profile.getFields()) {
1997 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1998 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1999 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2001 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2004 int postCounter = 0;
2005 for (Post post : sone.getPosts()) {
2006 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2007 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2008 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2009 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2010 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2012 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2015 int replyCounter = 0;
2016 for (PostReply reply : sone.getReplies()) {
2017 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2018 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2019 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2020 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2021 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2023 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2025 /* save post likes. */
2026 int postLikeCounter = 0;
2027 for (String postId : sone.getLikedPostIds()) {
2028 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2030 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2032 /* save reply likes. */
2033 int replyLikeCounter = 0;
2034 for (String replyId : sone.getLikedReplyIds()) {
2035 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2037 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2040 int friendCounter = 0;
2041 for (String friendId : sone.getFriends()) {
2042 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2044 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2046 /* save albums. first, collect in a flat structure, top-level first. */
2047 List<Album> albums = sone.getAllAlbums();
2049 int albumCounter = 0;
2050 for (Album album : albums) {
2051 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2052 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2053 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2054 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2055 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2056 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2058 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2061 int imageCounter = 0;
2062 for (Album album : albums) {
2063 for (Image image : album.getImages()) {
2064 if (!image.isInserted()) {
2067 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2068 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2069 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2070 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2071 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2072 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2073 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2074 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2075 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2078 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2081 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2082 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2083 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2084 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2085 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2086 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2088 configuration.save();
2090 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2092 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2093 } catch (ConfigurationException ce1) {
2094 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2099 * Saves the current options.
2101 private void saveConfiguration() {
2102 synchronized (configuration) {
2103 if (storingConfiguration) {
2104 logger.log(Level.FINE, "Already storing configuration…");
2107 storingConfiguration = true;
2110 /* store the options first. */
2112 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2113 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2114 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2115 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2116 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2117 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2118 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2119 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2120 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2121 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2122 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2123 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2125 /* save known Sones. */
2126 int soneCounter = 0;
2127 synchronized (knownSones) {
2128 for (String knownSoneId : knownSones) {
2129 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2131 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2134 /* save Sone following times. */
2136 synchronized (soneFollowingTimes) {
2137 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2138 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2139 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2142 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2145 /* save known posts. */
2146 int postCounter = 0;
2147 synchronized (knownPosts) {
2148 for (String knownPostId : knownPosts) {
2149 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2151 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2154 /* save known replies. */
2155 int replyCounter = 0;
2156 synchronized (knownReplies) {
2157 for (String knownReplyId : knownReplies) {
2158 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2160 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2163 /* save bookmarked posts. */
2164 int bookmarkedPostCounter = 0;
2165 synchronized (bookmarkedPosts) {
2166 for (String bookmarkedPostId : bookmarkedPosts) {
2167 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2170 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2173 configuration.save();
2175 } catch (ConfigurationException ce1) {
2176 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2178 synchronized (configuration) {
2179 storingConfiguration = false;
2185 * Loads the configuration.
2187 @SuppressWarnings("unchecked")
2188 private void loadConfiguration() {
2189 /* create options. */
2190 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2193 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2194 SoneInserter.setInsertionDelay(newValue);
2198 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2199 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2200 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2201 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2202 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2203 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2204 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2205 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2206 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2209 @SuppressWarnings("synthetic-access")
2210 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2211 fcpInterface.setActive(newValue);
2214 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2217 @SuppressWarnings("synthetic-access")
2218 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2219 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2224 loadConfigurationValue("InsertionDelay");
2225 loadConfigurationValue("PostsPerPage");
2226 loadConfigurationValue("ImagesPerPage");
2227 loadConfigurationValue("CharactersPerPost");
2228 loadConfigurationValue("PostCutOffLength");
2229 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2230 loadConfigurationValue("PositiveTrust");
2231 loadConfigurationValue("NegativeTrust");
2232 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2233 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2234 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2236 /* load known Sones. */
2237 int soneCounter = 0;
2239 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2240 if (knownSoneId == null) {
2243 synchronized (knownSones) {
2244 knownSones.add(knownSoneId);
2248 /* load Sone following times. */
2251 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2252 if (soneId == null) {
2255 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2256 Sone followedSone = getSone(soneId);
2257 if (followedSone == null) {
2258 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2260 synchronized (soneFollowingTimes) {
2261 soneFollowingTimes.put(getSone(soneId), time);
2267 /* load known posts. */
2268 int postCounter = 0;
2270 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2271 if (knownPostId == null) {
2274 synchronized (knownPosts) {
2275 knownPosts.add(knownPostId);
2279 /* load known replies. */
2280 int replyCounter = 0;
2282 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2283 if (knownReplyId == null) {
2286 synchronized (knownReplies) {
2287 knownReplies.add(knownReplyId);
2291 /* load bookmarked posts. */
2292 int bookmarkedPostCounter = 0;
2294 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2295 if (bookmarkedPostId == null) {
2298 synchronized (bookmarkedPosts) {
2299 bookmarkedPosts.add(bookmarkedPostId);
2306 * Loads an {@link Integer} configuration value for the option with the
2307 * given name, logging validation failures.
2310 * The name of the option to load
2312 private void loadConfigurationValue(String optionName) {
2314 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2315 } catch (IllegalArgumentException iae1) {
2316 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2321 * Generate a Sone URI from the given URI and latest edition.
2324 * The URI to derive the Sone URI from
2325 * @return The derived URI
2327 private static FreenetURI getSoneUri(String uriString) {
2329 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2331 } catch (MalformedURLException mue1) {
2332 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2338 // INTERFACE IdentityListener
2345 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2346 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2347 if (ownIdentity.hasContext("Sone")) {
2348 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2349 addLocalSone(ownIdentity);
2357 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2358 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2359 trustedIdentities.remove(ownIdentity);
2366 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2367 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2368 trustedIdentities.get(ownIdentity).add(identity);
2369 addRemoteSone(identity);
2376 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2377 soneDownloaders.execute(new Runnable() {
2380 @SuppressWarnings("synthetic-access")
2382 Sone sone = getRemoteSone(identity.getId(), false);
2383 sone.setIdentity(identity);
2384 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2385 soneDownloader.addSone(sone);
2386 soneDownloader.fetchSone(sone);
2395 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2396 trustedIdentities.get(ownIdentity).remove(identity);
2397 boolean foundIdentity = false;
2398 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2399 if (trustedIdentity.getKey().equals(ownIdentity)) {
2402 if (trustedIdentity.getValue().contains(identity)) {
2403 foundIdentity = true;
2406 if (foundIdentity) {
2407 /* some local identity still trusts this identity, don’t remove. */
2410 Sone sone = getSone(identity.getId(), false);
2412 /* TODO - we don’t have the Sone anymore. should this happen? */
2415 synchronized (posts) {
2416 synchronized (knownPosts) {
2417 for (Post post : sone.getPosts()) {
2418 posts.remove(post.getId());
2419 coreListenerManager.firePostRemoved(post);
2423 synchronized (replies) {
2424 synchronized (knownReplies) {
2425 for (PostReply reply : sone.getReplies()) {
2426 replies.remove(reply.getId());
2427 coreListenerManager.fireReplyRemoved(reply);
2431 synchronized (sones) {
2432 sones.remove(identity.getId());
2434 coreListenerManager.fireSoneRemoved(sone);
2438 // INTERFACE UpdateListener
2445 public void updateFound(Version version, long releaseTime, long latestEdition) {
2446 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2450 // INTERFACE ImageInsertListener
2457 public void insertStarted(Sone sone) {
2458 coreListenerManager.fireSoneInserting(sone);
2465 public void insertFinished(Sone sone, long insertDuration) {
2466 coreListenerManager.fireSoneInserted(sone, insertDuration);
2473 public void insertAborted(Sone sone, Throwable cause) {
2474 coreListenerManager.fireSoneInsertAborted(sone, cause);
2478 // SONEINSERTLISTENER METHODS
2485 public void imageInsertStarted(Image image) {
2486 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2487 coreListenerManager.fireImageInsertStarted(image);
2494 public void imageInsertAborted(Image image) {
2495 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2496 coreListenerManager.fireImageInsertAborted(image);
2503 public void imageInsertFinished(Image image, FreenetURI key) {
2504 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2505 image.setKey(key.toString());
2506 deleteTemporaryImage(image.getId());
2507 touchConfiguration();
2508 coreListenerManager.fireImageInsertFinished(image);
2515 public void imageInsertFailed(Image image, Throwable cause) {
2516 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2517 coreListenerManager.fireImageInsertFailed(image, cause);
2521 * Convenience interface for external classes that want to access the core’s
2524 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2526 public static class Preferences {
2528 /** The wrapped options. */
2529 private final Options options;
2532 * Creates a new preferences object wrapped around the given options.
2535 * The options to wrap
2537 public Preferences(Options options) {
2538 this.options = options;
2542 * Returns the insertion delay.
2544 * @return The insertion delay
2546 public int getInsertionDelay() {
2547 return options.getIntegerOption("InsertionDelay").get();
2551 * Validates the given insertion delay.
2553 * @param insertionDelay
2554 * The insertion delay to validate
2555 * @return {@code true} if the given insertion delay was valid,
2556 * {@code false} otherwise
2558 public boolean validateInsertionDelay(Integer insertionDelay) {
2559 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2563 * Sets the insertion delay
2565 * @param insertionDelay
2566 * The new insertion delay, or {@code null} to restore it to
2568 * @return This preferences
2570 public Preferences setInsertionDelay(Integer insertionDelay) {
2571 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2576 * Returns the number of posts to show per page.
2578 * @return The number of posts to show per page
2580 public int getPostsPerPage() {
2581 return options.getIntegerOption("PostsPerPage").get();
2585 * Validates the number of posts per page.
2587 * @param postsPerPage
2588 * The number of posts per page
2589 * @return {@code true} if the number of posts per page was valid,
2590 * {@code false} otherwise
2592 public boolean validatePostsPerPage(Integer postsPerPage) {
2593 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2597 * Sets the number of posts to show per page.
2599 * @param postsPerPage
2600 * The number of posts to show per page
2601 * @return This preferences object
2603 public Preferences setPostsPerPage(Integer postsPerPage) {
2604 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2609 * Returns the number of images to show per page.
2611 * @return The number of images to show per page
2613 public int getImagesPerPage() {
2614 return options.getIntegerOption("ImagesPerPage").get();
2618 * Validates the number of images per page.
2620 * @param imagesPerPage
2621 * The number of images per page
2622 * @return {@code true} if the number of images per page was valid,
2623 * {@code false} otherwise
2625 public boolean validateImagesPerPage(Integer imagesPerPage) {
2626 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2630 * Sets the number of images per page.
2632 * @param imagesPerPage
2633 * The number of images per page
2634 * @return This preferences object
2636 public Preferences setImagesPerPage(Integer imagesPerPage) {
2637 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2642 * Returns the number of characters per post, or <code>-1</code> if the
2643 * posts should not be cut off.
2645 * @return The numbers of characters per post
2647 public int getCharactersPerPost() {
2648 return options.getIntegerOption("CharactersPerPost").get();
2652 * Validates the number of characters per post.
2654 * @param charactersPerPost
2655 * The number of characters per post
2656 * @return {@code true} if the number of characters per post was valid,
2657 * {@code false} otherwise
2659 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2660 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2664 * Sets the number of characters per post.
2666 * @param charactersPerPost
2667 * The number of characters per post, or <code>-1</code> to
2668 * not cut off the posts
2669 * @return This preferences objects
2671 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2672 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2677 * Returns the number of characters the shortened post should have.
2679 * @return The number of characters of the snippet
2681 public int getPostCutOffLength() {
2682 return options.getIntegerOption("PostCutOffLength").get();
2686 * Validates the number of characters after which to cut off the post.
2688 * @param postCutOffLength
2689 * The number of characters of the snippet
2690 * @return {@code true} if the number of characters of the snippet is
2691 * valid, {@code false} otherwise
2693 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2694 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2698 * Sets the number of characters the shortened post should have.
2700 * @param postCutOffLength
2701 * The number of characters of the snippet
2702 * @return This preferences
2704 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2705 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2710 * Returns whether Sone requires full access to be even visible.
2712 * @return {@code true} if Sone requires full access, {@code false}
2715 public boolean isRequireFullAccess() {
2716 return options.getBooleanOption("RequireFullAccess").get();
2720 * Sets whether Sone requires full access to be even visible.
2722 * @param requireFullAccess
2723 * {@code true} if Sone requires full access, {@code false}
2726 public void setRequireFullAccess(Boolean requireFullAccess) {
2727 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2731 * Returns the positive trust.
2733 * @return The positive trust
2735 public int getPositiveTrust() {
2736 return options.getIntegerOption("PositiveTrust").get();
2740 * Validates the positive trust.
2742 * @param positiveTrust
2743 * The positive trust to validate
2744 * @return {@code true} if the positive trust was valid, {@code false}
2747 public boolean validatePositiveTrust(Integer positiveTrust) {
2748 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2752 * Sets the positive trust.
2754 * @param positiveTrust
2755 * The new positive trust, or {@code null} to restore it to
2757 * @return This preferences
2759 public Preferences setPositiveTrust(Integer positiveTrust) {
2760 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2765 * Returns the negative trust.
2767 * @return The negative trust
2769 public int getNegativeTrust() {
2770 return options.getIntegerOption("NegativeTrust").get();
2774 * Validates the negative trust.
2776 * @param negativeTrust
2777 * The negative trust to validate
2778 * @return {@code true} if the negative trust was valid, {@code false}
2781 public boolean validateNegativeTrust(Integer negativeTrust) {
2782 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2786 * Sets the negative trust.
2788 * @param negativeTrust
2789 * The negative trust, or {@code null} to restore it to the
2791 * @return The preferences
2793 public Preferences setNegativeTrust(Integer negativeTrust) {
2794 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2799 * Returns the trust comment. This is the comment that is set in the web
2800 * of trust when a trust value is assigned to an identity.
2802 * @return The trust comment
2804 public String getTrustComment() {
2805 return options.getStringOption("TrustComment").get();
2809 * Sets the trust comment.
2811 * @param trustComment
2812 * The trust comment, or {@code null} to restore it to the
2814 * @return This preferences
2816 public Preferences setTrustComment(String trustComment) {
2817 options.getStringOption("TrustComment").set(trustComment);
2822 * Returns whether the {@link FcpInterface FCP interface} is currently
2825 * @see FcpInterface#setActive(boolean)
2826 * @return {@code true} if the FCP interface is currently active,
2827 * {@code false} otherwise
2829 public boolean isFcpInterfaceActive() {
2830 return options.getBooleanOption("ActivateFcpInterface").get();
2834 * Sets whether the {@link FcpInterface FCP interface} is currently
2837 * @see FcpInterface#setActive(boolean)
2838 * @param fcpInterfaceActive
2839 * {@code true} to activate the FCP interface, {@code false}
2840 * to deactivate the FCP interface
2841 * @return This preferences object
2843 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2844 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2849 * Returns the action level for which full access to the FCP interface
2852 * @return The action level for which full access to the FCP interface
2855 public FullAccessRequired getFcpFullAccessRequired() {
2856 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2860 * Sets the action level for which full access to the FCP interface is
2863 * @param fcpFullAccessRequired
2865 * @return This preferences
2867 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2868 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);