2 * Sone - Core.java - Copyright © 2010 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.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Client;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Profile.Field;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.fcp.FcpInterface;
44 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.IdentityListener;
47 import net.pterodactylus.sone.freenet.wot.IdentityManager;
48 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
49 import net.pterodactylus.sone.freenet.wot.Trust;
50 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
51 import net.pterodactylus.sone.main.SonePlugin;
52 import net.pterodactylus.util.collection.Pair;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
55 import net.pterodactylus.util.logging.Logging;
56 import net.pterodactylus.util.number.Numbers;
57 import net.pterodactylus.util.thread.Ticker;
58 import net.pterodactylus.util.validation.IntegerRangeValidator;
59 import net.pterodactylus.util.validation.Validation;
60 import net.pterodactylus.util.version.Version;
61 import freenet.client.FetchResult;
62 import freenet.keys.FreenetURI;
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class Core implements IdentityListener, UpdateListener, SoneProvider, PostProvider {
72 * Enumeration for the possible states of a {@link Sone}.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public enum SoneStatus {
78 /** The Sone is unknown, i.e. not yet downloaded. */
81 /** The Sone is idle, i.e. not being downloaded or inserted. */
84 /** The Sone is currently being inserted. */
87 /** The Sone is currently being downloaded. */
92 private static final Logger logger = Logging.getLogger(Core.class);
95 private final Options options = new Options();
97 /** The preferences. */
98 private final Preferences preferences = new Preferences(options);
100 /** The core listener manager. */
101 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
103 /** The configuration. */
104 private Configuration configuration;
106 /** Whether we’re currently saving the configuration. */
107 private boolean storingConfiguration = false;
109 /** The identity manager. */
110 private final IdentityManager identityManager;
112 /** Interface to freenet. */
113 private final FreenetInterface freenetInterface;
115 /** The Sone downloader. */
116 private final SoneDownloader soneDownloader;
118 /** Sone downloader thread-pool. */
119 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
121 /** The update checker. */
122 private final UpdateChecker updateChecker;
124 /** The FCP interface. */
125 private volatile FcpInterface fcpInterface;
127 /** Whether the core has been stopped. */
128 private volatile boolean stopped;
130 /** The Sones’ statuses. */
131 /* synchronize access on itself. */
132 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
134 /** Locked local Sones. */
135 /* synchronize on itself. */
136 private final Set<Sone> lockedSones = new HashSet<Sone>();
138 /** Sone inserters. */
139 /* synchronize access on this on localSones. */
140 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
142 /** All local Sones. */
143 /* synchronize access on this on itself. */
144 private Map<String, Sone> localSones = new HashMap<String, Sone>();
146 /** All remote Sones. */
147 /* synchronize access on this on itself. */
148 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
150 /** All new Sones. */
151 private Set<String> newSones = new HashSet<String>();
153 /** All known Sones. */
154 /* synchronize access on {@link #newSones}. */
155 private Set<String> knownSones = new HashSet<String>();
158 private Map<String, Post> posts = new HashMap<String, Post>();
160 /** All new posts. */
161 private Set<String> newPosts = new HashSet<String>();
163 /** All known posts. */
164 /* synchronize access on {@link #newPosts}. */
165 private Set<String> knownPosts = new HashSet<String>();
168 private Map<String, Reply> replies = new HashMap<String, Reply>();
170 /** All new replies. */
171 private Set<String> newReplies = new HashSet<String>();
173 /** All known replies. */
174 private Set<String> knownReplies = new HashSet<String>();
176 /** All bookmarked posts. */
177 /* synchronize access on itself. */
178 private Set<String> bookmarkedPosts = new HashSet<String>();
180 /** Trusted identities, sorted by own identities. */
181 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
183 /** Ticker for threads that mark own elements as known. */
184 private Ticker localElementTicker = new Ticker();
187 * Creates a new core.
189 * @param configuration
190 * The configuration of the core
191 * @param freenetInterface
192 * The freenet interface
193 * @param identityManager
194 * The identity manager
196 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
197 this.configuration = configuration;
198 this.freenetInterface = freenetInterface;
199 this.identityManager = identityManager;
200 this.soneDownloader = new SoneDownloader(this, freenetInterface);
201 this.updateChecker = new UpdateChecker(freenetInterface);
205 // LISTENER MANAGEMENT
209 * Adds a new core listener.
211 * @param coreListener
212 * The listener to add
214 public void addCoreListener(CoreListener coreListener) {
215 coreListenerManager.addListener(coreListener);
219 * Removes a core listener.
221 * @param coreListener
222 * The listener to remove
224 public void removeCoreListener(CoreListener coreListener) {
225 coreListenerManager.removeListener(coreListener);
233 * Sets the configuration to use. This will automatically save the current
234 * configuration to the given configuration.
236 * @param configuration
237 * The new configuration to use
239 public void setConfiguration(Configuration configuration) {
240 this.configuration = configuration;
245 * Returns the options used by the core.
247 * @return The options of the core
249 public Preferences getPreferences() {
254 * Returns the identity manager used by the core.
256 * @return The identity manager
258 public IdentityManager getIdentityManager() {
259 return identityManager;
263 * Returns the update checker.
265 * @return The update checker
267 public UpdateChecker getUpdateChecker() {
268 return updateChecker;
272 * Sets the FCP interface to use.
274 * @param fcpInterface
275 * The FCP interface to use
277 public void setFcpInterface(FcpInterface fcpInterface) {
278 this.fcpInterface = fcpInterface;
282 * Returns the status of the given Sone.
285 * The Sone to get the status for
286 * @return The status of the Sone
288 public SoneStatus getSoneStatus(Sone sone) {
289 synchronized (soneStatuses) {
290 return soneStatuses.get(sone);
295 * Sets the status of the given Sone.
298 * The Sone to set the status of
302 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
303 synchronized (soneStatuses) {
304 soneStatuses.put(sone, soneStatus);
309 * Returns whether the given Sone is currently locked.
313 * @return {@code true} if the Sone is locked, {@code false} if it is not
315 public boolean isLocked(Sone sone) {
316 synchronized (lockedSones) {
317 return lockedSones.contains(sone);
322 * Returns all Sones, remote and local.
326 public Set<Sone> getSones() {
327 Set<Sone> allSones = new HashSet<Sone>();
328 allSones.addAll(getLocalSones());
329 allSones.addAll(getRemoteSones());
334 * Returns the Sone with the given ID, regardless whether it’s local or
338 * The ID of the Sone to get
339 * @return The Sone with the given ID, or {@code null} if there is no such
342 public Sone getSone(String id) {
343 return getSone(id, true);
347 * Returns the Sone with the given ID, regardless whether it’s local or
351 * The ID of the Sone to get
353 * {@code true} to create a new Sone if none exists,
354 * {@code false} to return {@code null} if a Sone with the given
356 * @return The Sone with the given ID, or {@code null} if there is no such
360 public Sone getSone(String id, boolean create) {
361 if (isLocalSone(id)) {
362 return getLocalSone(id);
364 return getRemoteSone(id, create);
368 * Checks whether the core knows a Sone with the given ID.
372 * @return {@code true} if there is a Sone with the given ID, {@code false}
375 public boolean hasSone(String id) {
376 return isLocalSone(id) || isRemoteSone(id);
380 * Returns whether the given Sone is a local Sone.
383 * The Sone to check for its locality
384 * @return {@code true} if the given Sone is local, {@code false} otherwise
386 public boolean isLocalSone(Sone sone) {
387 synchronized (localSones) {
388 return localSones.containsKey(sone.getId());
393 * Returns whether the given ID is the ID of a local Sone.
396 * The Sone ID to check for its locality
397 * @return {@code true} if the given ID is a local Sone, {@code false}
400 public boolean isLocalSone(String id) {
401 synchronized (localSones) {
402 return localSones.containsKey(id);
407 * Returns all local Sones.
409 * @return All local Sones
411 public Set<Sone> getLocalSones() {
412 synchronized (localSones) {
413 return new HashSet<Sone>(localSones.values());
418 * Returns the local Sone with the given ID.
421 * The ID of the Sone to get
422 * @return The Sone with the given ID
424 public Sone getLocalSone(String id) {
425 return getLocalSone(id, true);
429 * Returns the local Sone with the given ID, optionally creating a new Sone.
434 * {@code true} to create a new Sone if none exists,
435 * {@code false} to return null if none exists
436 * @return The Sone with the given ID, or {@code null}
438 public Sone getLocalSone(String id, boolean create) {
439 synchronized (localSones) {
440 Sone sone = localSones.get(id);
441 if ((sone == null) && create) {
443 localSones.put(id, sone);
444 setSoneStatus(sone, SoneStatus.unknown);
451 * Returns all remote Sones.
453 * @return All remote Sones
455 public Set<Sone> getRemoteSones() {
456 synchronized (remoteSones) {
457 return new HashSet<Sone>(remoteSones.values());
462 * Returns the remote Sone with the given ID.
465 * The ID of the remote Sone to get
466 * @return The Sone with the given ID
468 public Sone getRemoteSone(String id) {
469 return getRemoteSone(id, true);
473 * Returns the remote Sone with the given ID.
476 * The ID of the remote Sone to get
478 * {@code true} to always create a Sone, {@code false} to return
479 * {@code null} if no Sone with the given ID exists
480 * @return The Sone with the given ID
482 public Sone getRemoteSone(String id, boolean create) {
483 synchronized (remoteSones) {
484 Sone sone = remoteSones.get(id);
485 if ((sone == null) && create) {
487 remoteSones.put(id, sone);
488 setSoneStatus(sone, SoneStatus.unknown);
495 * Returns whether the given Sone is a remote Sone.
499 * @return {@code true} if the given Sone is a remote Sone, {@code false}
502 public boolean isRemoteSone(Sone sone) {
503 synchronized (remoteSones) {
504 return remoteSones.containsKey(sone.getId());
509 * Returns whether the Sone with the given ID is a remote Sone.
512 * The ID of the Sone to check
513 * @return {@code true} if the Sone with the given ID is a remote Sone,
514 * {@code false} otherwise
516 public boolean isRemoteSone(String id) {
517 synchronized (remoteSones) {
518 return remoteSones.containsKey(id);
523 * Returns whether the Sone with the given ID is a new Sone.
526 * The ID of the sone to check for
527 * @return {@code true} if the given Sone is new, false otherwise
529 public boolean isNewSone(String soneId) {
530 synchronized (newSones) {
531 return !knownSones.contains(soneId) && newSones.contains(soneId);
536 * Returns whether the given Sone has been modified.
539 * The Sone to check for modifications
540 * @return {@code true} if a modification has been detected in the Sone,
541 * {@code false} otherwise
543 public boolean isModifiedSone(Sone sone) {
544 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
548 * Returns whether the target Sone is trusted by the origin Sone.
554 * @return {@code true} if the target Sone is trusted by the origin Sone
556 public boolean isSoneTrusted(Sone origin, Sone target) {
557 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
558 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
562 * Returns the post with the given ID.
565 * The ID of the post to get
566 * @return The post with the given ID, or a new post with the given ID
568 public Post getPost(String postId) {
569 return getPost(postId, true);
573 * Returns the post with the given ID, optionally creating a new post.
576 * The ID of the post to get
578 * {@code true} it create a new post if no post with the given ID
579 * exists, {@code false} to return {@code null}
580 * @return The post, or {@code null} if there is no such post
583 public Post getPost(String postId, boolean create) {
584 synchronized (posts) {
585 Post post = posts.get(postId);
586 if ((post == null) && create) {
587 post = new Post(postId);
588 posts.put(postId, post);
595 * Returns whether the given post ID is new.
599 * @return {@code true} if the post is considered to be new, {@code false}
602 public boolean isNewPost(String postId) {
603 synchronized (newPosts) {
604 return !knownPosts.contains(postId) && newPosts.contains(postId);
609 * Returns all posts that have the given Sone as recipient.
611 * @see Post#getRecipient()
613 * The recipient of the posts
614 * @return All posts that have the given Sone as recipient
616 public Set<Post> getDirectedPosts(Sone recipient) {
617 Validation.begin().isNotNull("Recipient", recipient).check();
618 Set<Post> directedPosts = new HashSet<Post>();
619 synchronized (posts) {
620 for (Post post : posts.values()) {
621 if (recipient.equals(post.getRecipient())) {
622 directedPosts.add(post);
626 return directedPosts;
630 * Returns the reply with the given ID. If there is no reply with the given
631 * ID yet, a new one is created.
634 * The ID of the reply to get
637 public Reply getReply(String replyId) {
638 return getReply(replyId, true);
642 * Returns the reply with the given ID. If there is no reply with the given
643 * ID yet, a new one is created, unless {@code create} is false in which
644 * case {@code null} is returned.
647 * The ID of the reply to get
649 * {@code true} to always return a {@link Reply}, {@code false}
650 * to return {@code null} if no reply can be found
651 * @return The reply, or {@code null} if there is no such reply
653 public Reply getReply(String replyId, boolean create) {
654 synchronized (replies) {
655 Reply reply = replies.get(replyId);
656 if (create && (reply == null)) {
657 reply = new Reply(replyId);
658 replies.put(replyId, reply);
665 * Returns all replies for the given post, order ascending by time.
668 * The post to get all replies for
669 * @return All replies for the given post
671 public List<Reply> getReplies(Post post) {
672 Set<Sone> sones = getSones();
673 List<Reply> replies = new ArrayList<Reply>();
674 for (Sone sone : sones) {
675 for (Reply reply : sone.getReplies()) {
676 if (reply.getPost().equals(post)) {
681 Collections.sort(replies, Reply.TIME_COMPARATOR);
686 * Returns whether the reply with the given ID is new.
689 * The ID of the reply to check
690 * @return {@code true} if the reply is considered to be new, {@code false}
693 public boolean isNewReply(String replyId) {
694 synchronized (newReplies) {
695 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
700 * Returns all Sones that have liked the given post.
703 * The post to get the liking Sones for
704 * @return The Sones that like the given post
706 public Set<Sone> getLikes(Post post) {
707 Set<Sone> sones = new HashSet<Sone>();
708 for (Sone sone : getSones()) {
709 if (sone.getLikedPostIds().contains(post.getId())) {
717 * Returns all Sones that have liked the given reply.
720 * The reply to get the liking Sones for
721 * @return The Sones that like the given reply
723 public Set<Sone> getLikes(Reply reply) {
724 Set<Sone> sones = new HashSet<Sone>();
725 for (Sone sone : getSones()) {
726 if (sone.getLikedReplyIds().contains(reply.getId())) {
734 * Returns whether the given post is bookmarked.
738 * @return {@code true} if the given post is bookmarked, {@code false}
741 public boolean isBookmarked(Post post) {
742 return isPostBookmarked(post.getId());
746 * Returns whether the post with the given ID is bookmarked.
749 * The ID of the post to check
750 * @return {@code true} if the post with the given ID is bookmarked,
751 * {@code false} otherwise
753 public boolean isPostBookmarked(String id) {
754 synchronized (bookmarkedPosts) {
755 return bookmarkedPosts.contains(id);
760 * Returns all currently known bookmarked posts.
762 * @return All bookmarked posts
764 public Set<Post> getBookmarkedPosts() {
765 Set<Post> posts = new HashSet<Post>();
766 synchronized (bookmarkedPosts) {
767 for (String bookmarkedPostId : bookmarkedPosts) {
768 Post post = getPost(bookmarkedPostId, false);
782 * Locks the given Sone. A locked Sone will not be inserted by
783 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
789 public void lockSone(Sone sone) {
790 synchronized (lockedSones) {
791 if (lockedSones.add(sone)) {
792 coreListenerManager.fireSoneLocked(sone);
798 * Unlocks the given Sone.
800 * @see #lockSone(Sone)
804 public void unlockSone(Sone sone) {
805 synchronized (lockedSones) {
806 if (lockedSones.remove(sone)) {
807 coreListenerManager.fireSoneUnlocked(sone);
813 * Adds a local Sone from the given ID which has to be the ID of an own
817 * The ID of an own identity to add a Sone for
818 * @return The added (or already existing) Sone
820 public Sone addLocalSone(String id) {
821 synchronized (localSones) {
822 if (localSones.containsKey(id)) {
823 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
824 return localSones.get(id);
826 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
827 if (ownIdentity == null) {
828 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
831 return addLocalSone(ownIdentity);
836 * Adds a local Sone from the given own identity.
839 * The own identity to create a Sone from
840 * @return The added (or already existing) Sone
842 public Sone addLocalSone(OwnIdentity ownIdentity) {
843 if (ownIdentity == null) {
844 logger.log(Level.WARNING, "Given OwnIdentity is null!");
847 synchronized (localSones) {
850 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
851 } catch (MalformedURLException mue1) {
852 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
855 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
856 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
857 /* TODO - load posts ’n stuff */
858 localSones.put(ownIdentity.getId(), sone);
859 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
860 soneInserters.put(sone, soneInserter);
861 setSoneStatus(sone, SoneStatus.idle);
863 if (!preferences.isSoneRescueMode()) {
864 soneInserter.start();
866 new Thread(new Runnable() {
869 @SuppressWarnings("synthetic-access")
871 if (!preferences.isSoneRescueMode()) {
874 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
875 coreListenerManager.fireRescuingSone(sone);
877 long edition = sone.getLatestEdition();
878 /* find the latest edition the node knows about. */
879 Pair<FreenetURI, FetchResult> currentUri = freenetInterface.fetchUri(sone.getRequestUri());
880 if (currentUri != null) {
881 long currentEdition = currentUri.getLeft().getEdition();
882 if (currentEdition > edition) {
883 edition = currentEdition;
886 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
887 logger.log(Level.FINE, "Downloading edition " + edition + "…");
888 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
891 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
893 coreListenerManager.fireRescuedSone(sone);
894 soneInserter.start();
897 }, "Sone Downloader").start();
903 * Creates a new Sone for the given own identity.
906 * The own identity to create a Sone for
907 * @return The created Sone
909 public Sone createSone(OwnIdentity ownIdentity) {
911 ownIdentity.addContext("Sone");
912 } catch (WebOfTrustException wote1) {
913 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
916 Sone sone = addLocalSone(ownIdentity);
917 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
918 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
924 * Adds the Sone of the given identity.
927 * The identity whose Sone to add
928 * @return The added or already existing Sone
930 public Sone addRemoteSone(Identity identity) {
931 if (identity == null) {
932 logger.log(Level.WARNING, "Given Identity is null!");
935 synchronized (remoteSones) {
936 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
937 boolean newSone = sone.getRequestUri() == null;
938 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
939 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
941 synchronized (newSones) {
942 newSone = !knownSones.contains(sone.getId());
944 newSones.add(sone.getId());
948 coreListenerManager.fireNewSoneFound(sone);
949 for (Sone localSone : getLocalSones()) {
950 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
951 localSone.addFriend(sone.getId());
957 remoteSones.put(identity.getId(), sone);
958 soneDownloader.addSone(sone);
959 setSoneStatus(sone, SoneStatus.unknown);
960 soneDownloaders.execute(new Runnable() {
963 @SuppressWarnings("synthetic-access")
965 soneDownloader.fetchSone(sone, sone.getRequestUri());
974 * Retrieves the trust relationship from the origin to the target. If the
975 * trust relationship can not be retrieved, {@code null} is returned.
977 * @see Identity#getTrust(OwnIdentity)
979 * The origin of the trust tree
981 * The target of the trust
982 * @return The trust relationship
984 public Trust getTrust(Sone origin, Sone target) {
985 if (!isLocalSone(origin)) {
986 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
989 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
993 * Sets the trust value of the given origin Sone for the target Sone.
1000 * The trust value (from {@code -100} to {@code 100})
1002 public void setTrust(Sone origin, Sone target, int trustValue) {
1003 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();
1005 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1006 } catch (WebOfTrustException wote1) {
1007 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1012 * Removes any trust assignment for the given target Sone.
1019 public void removeTrust(Sone origin, Sone target) {
1020 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1022 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1023 } catch (WebOfTrustException wote1) {
1024 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1029 * Assigns the configured positive trust value for the given target.
1036 public void trustSone(Sone origin, Sone target) {
1037 setTrust(origin, target, preferences.getPositiveTrust());
1041 * Assigns the configured negative trust value for the given target.
1048 public void distrustSone(Sone origin, Sone target) {
1049 setTrust(origin, target, preferences.getNegativeTrust());
1053 * Removes the trust assignment for the given target.
1060 public void untrustSone(Sone origin, Sone target) {
1061 removeTrust(origin, target);
1065 * Updates the stores Sone with the given Sone.
1070 public void updateSone(Sone sone) {
1071 if (hasSone(sone.getId())) {
1072 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1073 Sone storedSone = getSone(sone.getId());
1074 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1075 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1078 synchronized (posts) {
1079 if (!soneRescueMode) {
1080 for (Post post : storedSone.getPosts()) {
1081 posts.remove(post.getId());
1082 if (!sone.getPosts().contains(post)) {
1083 coreListenerManager.firePostRemoved(post);
1087 List<Post> storedPosts = storedSone.getPosts();
1088 synchronized (newPosts) {
1089 for (Post post : sone.getPosts()) {
1090 post.setSone(storedSone);
1091 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1092 newPosts.add(post.getId());
1093 coreListenerManager.fireNewPostFound(post);
1095 posts.put(post.getId(), post);
1099 synchronized (replies) {
1100 if (!soneRescueMode) {
1101 for (Reply reply : storedSone.getReplies()) {
1102 replies.remove(reply.getId());
1103 if (!sone.getReplies().contains(reply)) {
1104 coreListenerManager.fireReplyRemoved(reply);
1108 Set<Reply> storedReplies = storedSone.getReplies();
1109 synchronized (newReplies) {
1110 for (Reply reply : sone.getReplies()) {
1111 reply.setSone(storedSone);
1112 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1113 newReplies.add(reply.getId());
1114 coreListenerManager.fireNewReplyFound(reply);
1116 replies.put(reply.getId(), reply);
1120 synchronized (storedSone) {
1121 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1122 storedSone.setTime(sone.getTime());
1124 storedSone.setClient(sone.getClient());
1125 storedSone.setProfile(sone.getProfile());
1126 if (soneRescueMode) {
1127 for (Post post : sone.getPosts()) {
1128 storedSone.addPost(post);
1130 for (Reply reply : sone.getReplies()) {
1131 storedSone.addReply(reply);
1133 for (String likedPostId : sone.getLikedPostIds()) {
1134 storedSone.addLikedPostId(likedPostId);
1136 for (String likedReplyId : sone.getLikedReplyIds()) {
1137 storedSone.addLikedReplyId(likedReplyId);
1140 storedSone.setPosts(sone.getPosts());
1141 storedSone.setReplies(sone.getReplies());
1142 storedSone.setLikePostIds(sone.getLikedPostIds());
1143 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1145 storedSone.setLatestEdition(sone.getLatestEdition());
1151 * Deletes the given Sone. This will remove the Sone from the
1152 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1153 * and remove the context from its identity.
1156 * The Sone to delete
1158 public void deleteSone(Sone sone) {
1159 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1160 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1163 synchronized (localSones) {
1164 if (!localSones.containsKey(sone.getId())) {
1165 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1168 localSones.remove(sone.getId());
1169 soneInserters.remove(sone).stop();
1172 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1173 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1174 } catch (WebOfTrustException wote1) {
1175 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1178 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1179 } catch (ConfigurationException ce1) {
1180 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1185 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1186 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1189 * The Sone to mark as known
1191 public void markSoneKnown(Sone sone) {
1192 synchronized (newSones) {
1193 if (newSones.remove(sone.getId())) {
1194 knownSones.add(sone.getId());
1195 coreListenerManager.fireMarkSoneKnown(sone);
1196 saveConfiguration();
1202 * Loads and updates the given Sone from the configuration. If any error is
1203 * encountered, loading is aborted and the given Sone is not changed.
1206 * The Sone to load and update
1208 public void loadSone(Sone sone) {
1209 if (!isLocalSone(sone)) {
1210 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1214 /* initialize options. */
1215 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1218 String sonePrefix = "Sone/" + sone.getId();
1219 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1220 if (soneTime == null) {
1221 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1224 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1227 Profile profile = new Profile();
1228 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1229 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1230 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1231 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1232 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1233 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1235 /* load profile fields. */
1237 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1238 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1239 if (fieldName == null) {
1242 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1243 profile.addField(fieldName).setValue(fieldValue);
1247 Set<Post> posts = new HashSet<Post>();
1249 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1250 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1251 if (postId == null) {
1254 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1255 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1256 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1257 if ((postTime == 0) || (postText == null)) {
1258 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1261 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1262 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1263 post.setRecipient(getSone(postRecipientId));
1269 Set<Reply> replies = new HashSet<Reply>();
1271 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1272 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1273 if (replyId == null) {
1276 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1277 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1278 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1279 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1280 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1283 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1286 /* load post likes. */
1287 Set<String> likedPostIds = new HashSet<String>();
1289 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1290 if (likedPostId == null) {
1293 likedPostIds.add(likedPostId);
1296 /* load reply likes. */
1297 Set<String> likedReplyIds = new HashSet<String>();
1299 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1300 if (likedReplyId == null) {
1303 likedReplyIds.add(likedReplyId);
1307 Set<String> friends = new HashSet<String>();
1309 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1310 if (friendId == null) {
1313 friends.add(friendId);
1317 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1319 /* if we’re still here, Sone was loaded successfully. */
1320 synchronized (sone) {
1321 sone.setTime(soneTime);
1322 sone.setProfile(profile);
1323 sone.setPosts(posts);
1324 sone.setReplies(replies);
1325 sone.setLikePostIds(likedPostIds);
1326 sone.setLikeReplyIds(likedReplyIds);
1327 sone.setFriends(friends);
1328 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1330 synchronized (newSones) {
1331 for (String friend : friends) {
1332 knownSones.add(friend);
1335 synchronized (newPosts) {
1336 for (Post post : posts) {
1337 knownPosts.add(post.getId());
1340 synchronized (newReplies) {
1341 for (Reply reply : replies) {
1342 knownReplies.add(reply.getId());
1348 * Saves the given Sone. This will persist all local settings for the given
1349 * Sone, such as the friends list and similar, private options.
1354 public synchronized void saveSone(Sone sone) {
1355 if (!isLocalSone(sone)) {
1356 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1359 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1360 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1364 logger.log(Level.INFO, "Saving Sone: %s", sone);
1366 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1368 /* save Sone into configuration. */
1369 String sonePrefix = "Sone/" + sone.getId();
1370 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1371 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1374 Profile profile = sone.getProfile();
1375 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1376 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1377 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1378 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1379 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1380 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1382 /* save profile fields. */
1383 int fieldCounter = 0;
1384 for (Field profileField : profile.getFields()) {
1385 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1386 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1387 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1389 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1392 int postCounter = 0;
1393 for (Post post : sone.getPosts()) {
1394 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1395 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1396 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1397 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1398 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1400 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1403 int replyCounter = 0;
1404 for (Reply reply : sone.getReplies()) {
1405 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1406 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1407 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1408 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1409 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1411 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1413 /* save post likes. */
1414 int postLikeCounter = 0;
1415 for (String postId : sone.getLikedPostIds()) {
1416 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1418 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1420 /* save reply likes. */
1421 int replyLikeCounter = 0;
1422 for (String replyId : sone.getLikedReplyIds()) {
1423 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1425 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1428 int friendCounter = 0;
1429 for (String friendId : sone.getFriends()) {
1430 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1432 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1435 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1437 configuration.save();
1438 logger.log(Level.INFO, "Sone %s saved.", sone);
1439 } catch (ConfigurationException ce1) {
1440 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1441 } catch (WebOfTrustException wote1) {
1442 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1447 * Creates a new post.
1450 * The Sone that creates the post
1452 * The text of the post
1453 * @return The created post
1455 public Post createPost(Sone sone, String text) {
1456 return createPost(sone, System.currentTimeMillis(), text);
1460 * Creates a new post.
1463 * The Sone that creates the post
1465 * The time of the post
1467 * The text of the post
1468 * @return The created post
1470 public Post createPost(Sone sone, long time, String text) {
1471 return createPost(sone, null, time, text);
1475 * Creates a new post.
1478 * The Sone that creates the post
1480 * The recipient Sone, or {@code null} if this post does not have
1483 * The text of the post
1484 * @return The created post
1486 public Post createPost(Sone sone, Sone recipient, String text) {
1487 return createPost(sone, recipient, System.currentTimeMillis(), text);
1491 * Creates a new post.
1494 * The Sone that creates the post
1496 * The recipient Sone, or {@code null} if this post does not have
1499 * The time of the post
1501 * The text of the post
1502 * @return The created post
1504 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1505 if (!isLocalSone(sone)) {
1506 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1509 final Post post = new Post(sone, time, text);
1510 if (recipient != null) {
1511 post.setRecipient(recipient);
1513 synchronized (posts) {
1514 posts.put(post.getId(), post);
1516 synchronized (newPosts) {
1517 newPosts.add(post.getId());
1518 coreListenerManager.fireNewPostFound(post);
1522 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1529 markPostKnown(post);
1531 }, "Mark " + post + " read.");
1536 * Deletes the given post.
1539 * The post to delete
1541 public void deletePost(Post post) {
1542 if (!isLocalSone(post.getSone())) {
1543 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1546 post.getSone().removePost(post);
1547 synchronized (posts) {
1548 posts.remove(post.getId());
1550 coreListenerManager.firePostRemoved(post);
1551 synchronized (newPosts) {
1552 markPostKnown(post);
1553 knownPosts.remove(post.getId());
1555 saveSone(post.getSone());
1559 * Marks the given post as known, if it is currently a new post (according
1560 * to {@link #isNewPost(String)}).
1563 * The post to mark as known
1565 public void markPostKnown(Post post) {
1566 synchronized (newPosts) {
1567 if (newPosts.remove(post.getId())) {
1568 knownPosts.add(post.getId());
1569 coreListenerManager.fireMarkPostKnown(post);
1570 saveConfiguration();
1576 * Bookmarks the given post.
1579 * The post to bookmark
1581 public void bookmark(Post post) {
1582 bookmarkPost(post.getId());
1586 * Bookmarks the post with the given ID.
1589 * The ID of the post to bookmark
1591 public void bookmarkPost(String id) {
1592 synchronized (bookmarkedPosts) {
1593 bookmarkedPosts.add(id);
1598 * Removes the given post from the bookmarks.
1601 * The post to unbookmark
1603 public void unbookmark(Post post) {
1604 unbookmarkPost(post.getId());
1608 * Removes the post with the given ID from the bookmarks.
1611 * The ID of the post to unbookmark
1613 public void unbookmarkPost(String id) {
1614 synchronized (bookmarkedPosts) {
1615 bookmarkedPosts.remove(id);
1620 * Creates a new reply.
1623 * The Sone that creates the reply
1625 * The post that this reply refers to
1627 * The text of the reply
1628 * @return The created reply
1630 public Reply createReply(Sone sone, Post post, String text) {
1631 return createReply(sone, post, System.currentTimeMillis(), text);
1635 * Creates a new reply.
1638 * The Sone that creates the reply
1640 * The post that this reply refers to
1642 * The time of the reply
1644 * The text of the reply
1645 * @return The created reply
1647 public Reply createReply(Sone sone, Post post, long time, String text) {
1648 if (!isLocalSone(sone)) {
1649 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1652 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1653 synchronized (replies) {
1654 replies.put(reply.getId(), reply);
1656 synchronized (newReplies) {
1657 newReplies.add(reply.getId());
1658 coreListenerManager.fireNewReplyFound(reply);
1660 sone.addReply(reply);
1662 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1669 markReplyKnown(reply);
1671 }, "Mark " + reply + " read.");
1676 * Deletes the given reply.
1679 * The reply to delete
1681 public void deleteReply(Reply reply) {
1682 Sone sone = reply.getSone();
1683 if (!isLocalSone(sone)) {
1684 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1687 synchronized (replies) {
1688 replies.remove(reply.getId());
1690 synchronized (newReplies) {
1691 markReplyKnown(reply);
1692 knownReplies.remove(reply.getId());
1694 sone.removeReply(reply);
1699 * Marks the given reply as known, if it is currently a new reply (according
1700 * to {@link #isNewReply(String)}).
1703 * The reply to mark as known
1705 public void markReplyKnown(Reply reply) {
1706 synchronized (newReplies) {
1707 if (newReplies.remove(reply.getId())) {
1708 knownReplies.add(reply.getId());
1709 coreListenerManager.fireMarkReplyKnown(reply);
1710 saveConfiguration();
1718 public void start() {
1719 loadConfiguration();
1720 updateChecker.addUpdateListener(this);
1721 updateChecker.start();
1727 public void stop() {
1728 synchronized (localSones) {
1729 for (SoneInserter soneInserter : soneInserters.values()) {
1730 soneInserter.stop();
1732 for (Sone localSone : localSones.values()) {
1733 saveSone(localSone);
1736 updateChecker.stop();
1737 updateChecker.removeUpdateListener(this);
1738 soneDownloader.stop();
1739 saveConfiguration();
1744 * Saves the current options.
1746 public void saveConfiguration() {
1747 synchronized (configuration) {
1748 if (storingConfiguration) {
1749 logger.log(Level.FINE, "Already storing configuration…");
1752 storingConfiguration = true;
1755 /* store the options first. */
1757 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1758 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1759 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1760 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1761 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1762 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1763 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1764 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1765 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1766 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1767 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1768 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1770 /* save known Sones. */
1771 int soneCounter = 0;
1772 synchronized (newSones) {
1773 for (String knownSoneId : knownSones) {
1774 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1776 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1779 /* save known posts. */
1780 int postCounter = 0;
1781 synchronized (newPosts) {
1782 for (String knownPostId : knownPosts) {
1783 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1785 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1788 /* save known replies. */
1789 int replyCounter = 0;
1790 synchronized (newReplies) {
1791 for (String knownReplyId : knownReplies) {
1792 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1794 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1797 /* save bookmarked posts. */
1798 int bookmarkedPostCounter = 0;
1799 synchronized (bookmarkedPosts) {
1800 for (String bookmarkedPostId : bookmarkedPosts) {
1801 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1804 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1807 configuration.save();
1809 } catch (ConfigurationException ce1) {
1810 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1812 synchronized (configuration) {
1813 storingConfiguration = false;
1823 * Loads the configuration.
1825 @SuppressWarnings("unchecked")
1826 private void loadConfiguration() {
1827 /* create options. */
1828 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1831 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1832 SoneInserter.setInsertionDelay(newValue);
1836 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1837 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1838 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1839 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1840 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1841 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1844 @SuppressWarnings("synthetic-access")
1845 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1846 fcpInterface.setActive(newValue);
1849 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1852 @SuppressWarnings("synthetic-access")
1853 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1854 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1858 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1859 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1860 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1862 /* read options from configuration. */
1863 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1864 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1865 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1866 options.getBooleanOption("ClearOnNextRestart").set(null);
1867 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1868 if (clearConfiguration) {
1869 /* stop loading the configuration. */
1873 loadConfigurationValue("InsertionDelay");
1874 loadConfigurationValue("PostsPerPage");
1875 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1876 loadConfigurationValue("PositiveTrust");
1877 loadConfigurationValue("NegativeTrust");
1878 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1879 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1880 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1881 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1883 /* load known Sones. */
1884 int soneCounter = 0;
1886 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1887 if (knownSoneId == null) {
1890 synchronized (newSones) {
1891 knownSones.add(knownSoneId);
1895 /* load known posts. */
1896 int postCounter = 0;
1898 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1899 if (knownPostId == null) {
1902 synchronized (newPosts) {
1903 knownPosts.add(knownPostId);
1907 /* load known replies. */
1908 int replyCounter = 0;
1910 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1911 if (knownReplyId == null) {
1914 synchronized (newReplies) {
1915 knownReplies.add(knownReplyId);
1919 /* load bookmarked posts. */
1920 int bookmarkedPostCounter = 0;
1922 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1923 if (bookmarkedPostId == null) {
1926 synchronized (bookmarkedPosts) {
1927 bookmarkedPosts.add(bookmarkedPostId);
1934 * Loads an {@link Integer} configuration value for the option with the
1935 * given name, logging validation failures.
1938 * The name of the option to load
1940 private void loadConfigurationValue(String optionName) {
1942 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1943 } catch (IllegalArgumentException iae1) {
1944 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1949 * Generate a Sone URI from the given URI and latest edition.
1952 * The URI to derive the Sone URI from
1953 * @return The derived URI
1955 private FreenetURI getSoneUri(String uriString) {
1957 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1959 } catch (MalformedURLException mue1) {
1960 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1966 // INTERFACE IdentityListener
1973 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1974 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1975 if (ownIdentity.hasContext("Sone")) {
1976 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1977 addLocalSone(ownIdentity);
1985 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1986 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1987 trustedIdentities.remove(ownIdentity);
1994 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1995 logger.log(Level.FINEST, "Adding Identity: " + identity);
1996 trustedIdentities.get(ownIdentity).add(identity);
1997 addRemoteSone(identity);
2004 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2005 new Thread(new Runnable() {
2008 @SuppressWarnings("synthetic-access")
2010 Sone sone = getRemoteSone(identity.getId());
2011 sone.setIdentity(identity);
2012 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2013 soneDownloader.addSone(sone);
2014 soneDownloader.fetchSone(sone);
2023 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2024 trustedIdentities.get(ownIdentity).remove(identity);
2025 boolean foundIdentity = false;
2026 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2027 if (trustedIdentity.getKey().equals(ownIdentity)) {
2030 if (trustedIdentity.getValue().contains(identity)) {
2031 foundIdentity = true;
2034 if (foundIdentity) {
2035 /* some local identity still trusts this identity, don’t remove. */
2038 Sone sone = getSone(identity.getId(), false);
2040 /* TODO - we don’t have the Sone anymore. should this happen? */
2043 synchronized (posts) {
2044 synchronized (newPosts) {
2045 for (Post post : sone.getPosts()) {
2046 posts.remove(post.getId());
2047 newPosts.remove(post.getId());
2048 coreListenerManager.firePostRemoved(post);
2052 synchronized (replies) {
2053 synchronized (newReplies) {
2054 for (Reply reply : sone.getReplies()) {
2055 replies.remove(reply.getId());
2056 newReplies.remove(reply.getId());
2057 coreListenerManager.fireReplyRemoved(reply);
2061 synchronized (remoteSones) {
2062 remoteSones.remove(identity.getId());
2064 synchronized (newSones) {
2065 newSones.remove(identity.getId());
2066 coreListenerManager.fireSoneRemoved(sone);
2071 // INTERFACE UpdateListener
2078 public void updateFound(Version version, long releaseTime, long latestEdition) {
2079 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2083 * Convenience interface for external classes that want to access the core’s
2086 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2088 public static class Preferences {
2090 /** The wrapped options. */
2091 private final Options options;
2094 * Creates a new preferences object wrapped around the given options.
2097 * The options to wrap
2099 public Preferences(Options options) {
2100 this.options = options;
2104 * Returns the insertion delay.
2106 * @return The insertion delay
2108 public int getInsertionDelay() {
2109 return options.getIntegerOption("InsertionDelay").get();
2113 * Validates the given insertion delay.
2115 * @param insertionDelay
2116 * The insertion delay to validate
2117 * @return {@code true} if the given insertion delay was valid, {@code
2120 public boolean validateInsertionDelay(Integer insertionDelay) {
2121 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2125 * Sets the insertion delay
2127 * @param insertionDelay
2128 * The new insertion delay, or {@code null} to restore it to
2130 * @return This preferences
2132 public Preferences setInsertionDelay(Integer insertionDelay) {
2133 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2138 * Returns the number of posts to show per page.
2140 * @return The number of posts to show per page
2142 public int getPostsPerPage() {
2143 return options.getIntegerOption("PostsPerPage").get();
2147 * Validates the number of posts per page.
2149 * @param postsPerPage
2150 * The number of posts per page
2151 * @return {@code true} if the number of posts per page was valid,
2152 * {@code false} otherwise
2154 public boolean validatePostsPerPage(Integer postsPerPage) {
2155 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2159 * Sets the number of posts to show per page.
2161 * @param postsPerPage
2162 * The number of posts to show per page
2163 * @return This preferences object
2165 public Preferences setPostsPerPage(Integer postsPerPage) {
2166 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2171 * Returns whether Sone requires full access to be even visible.
2173 * @return {@code true} if Sone requires full access, {@code false}
2176 public boolean isRequireFullAccess() {
2177 return options.getBooleanOption("RequireFullAccess").get();
2181 * Sets whether Sone requires full access to be even visible.
2183 * @param requireFullAccess
2184 * {@code true} if Sone requires full access, {@code false}
2187 public void setRequireFullAccess(Boolean requireFullAccess) {
2188 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2192 * Returns the positive trust.
2194 * @return The positive trust
2196 public int getPositiveTrust() {
2197 return options.getIntegerOption("PositiveTrust").get();
2201 * Validates the positive trust.
2203 * @param positiveTrust
2204 * The positive trust to validate
2205 * @return {@code true} if the positive trust was valid, {@code false}
2208 public boolean validatePositiveTrust(Integer positiveTrust) {
2209 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2213 * Sets the positive trust.
2215 * @param positiveTrust
2216 * The new positive trust, or {@code null} to restore it to
2218 * @return This preferences
2220 public Preferences setPositiveTrust(Integer positiveTrust) {
2221 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2226 * Returns the negative trust.
2228 * @return The negative trust
2230 public int getNegativeTrust() {
2231 return options.getIntegerOption("NegativeTrust").get();
2235 * Validates the negative trust.
2237 * @param negativeTrust
2238 * The negative trust to validate
2239 * @return {@code true} if the negative trust was valid, {@code false}
2242 public boolean validateNegativeTrust(Integer negativeTrust) {
2243 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2247 * Sets the negative trust.
2249 * @param negativeTrust
2250 * The negative trust, or {@code null} to restore it to the
2252 * @return The preferences
2254 public Preferences setNegativeTrust(Integer negativeTrust) {
2255 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2260 * Returns the trust comment. This is the comment that is set in the web
2261 * of trust when a trust value is assigned to an identity.
2263 * @return The trust comment
2265 public String getTrustComment() {
2266 return options.getStringOption("TrustComment").get();
2270 * Sets the trust comment.
2272 * @param trustComment
2273 * The trust comment, or {@code null} to restore it to the
2275 * @return This preferences
2277 public Preferences setTrustComment(String trustComment) {
2278 options.getStringOption("TrustComment").set(trustComment);
2283 * Returns whether the {@link FcpInterface FCP interface} is currently
2286 * @see FcpInterface#setActive(boolean)
2287 * @return {@code true} if the FCP interface is currently active,
2288 * {@code false} otherwise
2290 public boolean isFcpInterfaceActive() {
2291 return options.getBooleanOption("ActivateFcpInterface").get();
2295 * Sets whether the {@link FcpInterface FCP interface} is currently
2298 * @see FcpInterface#setActive(boolean)
2299 * @param fcpInterfaceActive
2300 * {@code true} to activate the FCP interface, {@code false}
2301 * to deactivate the FCP interface
2302 * @return This preferences object
2304 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2305 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2310 * Returns the action level for which full access to the FCP interface
2313 * @return The action level for which full access to the FCP interface
2316 public FullAccessRequired getFcpFullAccessRequired() {
2317 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2321 * Sets the action level for which full access to the FCP interface is
2324 * @param fcpFullAccessRequired
2326 * @return This preferences
2328 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2329 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2334 * Returns whether the rescue mode is active.
2336 * @return {@code true} if the rescue mode is active, {@code false}
2339 public boolean isSoneRescueMode() {
2340 return options.getBooleanOption("SoneRescueMode").get();
2344 * Sets whether the rescue mode is active.
2346 * @param soneRescueMode
2347 * {@code true} if the rescue mode is active, {@code false}
2349 * @return This preferences
2351 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2352 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2357 * Returns whether Sone should clear its settings on the next restart.
2358 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2359 * to return {@code true} as well!
2361 * @return {@code true} if Sone should clear its settings on the next
2362 * restart, {@code false} otherwise
2364 public boolean isClearOnNextRestart() {
2365 return options.getBooleanOption("ClearOnNextRestart").get();
2369 * Sets whether Sone will clear its settings on the next restart.
2371 * @param clearOnNextRestart
2372 * {@code true} if Sone should clear its settings on the next
2373 * restart, {@code false} otherwise
2374 * @return This preferences
2376 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2377 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2382 * Returns whether Sone should really clear its settings on next
2383 * restart. This is a confirmation option that needs to be set in
2384 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2385 * settings on the next restart.
2387 * @return {@code true} if Sone should really clear its settings on the
2388 * next restart, {@code false} otherwise
2390 public boolean isReallyClearOnNextRestart() {
2391 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2395 * Sets whether Sone should really clear its settings on the next
2398 * @param reallyClearOnNextRestart
2399 * {@code true} if Sone should really clear its settings on
2400 * the next restart, {@code false} otherwise
2401 * @return This preferences
2403 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2404 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);