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.validation.IntegerRangeValidator;
58 import net.pterodactylus.util.validation.Validation;
59 import net.pterodactylus.util.version.Version;
60 import freenet.client.FetchResult;
61 import freenet.keys.FreenetURI;
66 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68 public class Core implements IdentityListener, UpdateListener {
71 * Enumeration for the possible states of a {@link Sone}.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public enum SoneStatus {
77 /** The Sone is unknown, i.e. not yet downloaded. */
80 /** The Sone is idle, i.e. not being downloaded or inserted. */
83 /** The Sone is currently being inserted. */
86 /** The Sone is currently being downloaded. */
91 private static final Logger logger = Logging.getLogger(Core.class);
94 private final Options options = new Options();
96 /** The preferences. */
97 private final Preferences preferences = new Preferences(options);
99 /** The core listener manager. */
100 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
102 /** The configuration. */
103 private Configuration configuration;
105 /** Whether we’re currently saving the configuration. */
106 private boolean storingConfiguration = false;
108 /** The identity manager. */
109 private final IdentityManager identityManager;
111 /** Interface to freenet. */
112 private final FreenetInterface freenetInterface;
114 /** The Sone downloader. */
115 private final SoneDownloader soneDownloader;
117 /** Sone downloader thread-pool. */
118 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
120 /** The update checker. */
121 private final UpdateChecker updateChecker;
123 /** The FCP interface. */
124 private volatile FcpInterface fcpInterface;
126 /** Whether the core has been stopped. */
127 private volatile boolean stopped;
129 /** The Sones’ statuses. */
130 /* synchronize access on itself. */
131 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
133 /** Locked local Sones. */
134 /* synchronize on itself. */
135 private final Set<Sone> lockedSones = new HashSet<Sone>();
137 /** Sone inserters. */
138 /* synchronize access on this on localSones. */
139 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
141 /** All local Sones. */
142 /* synchronize access on this on itself. */
143 private Map<String, Sone> localSones = new HashMap<String, Sone>();
145 /** All remote Sones. */
146 /* synchronize access on this on itself. */
147 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
149 /** All new Sones. */
150 private Set<String> newSones = new HashSet<String>();
152 /** All known Sones. */
153 /* synchronize access on {@link #newSones}. */
154 private Set<String> knownSones = new HashSet<String>();
157 private Map<String, Post> posts = new HashMap<String, Post>();
159 /** All new posts. */
160 private Set<String> newPosts = new HashSet<String>();
162 /** All known posts. */
163 /* synchronize access on {@link #newPosts}. */
164 private Set<String> knownPosts = new HashSet<String>();
167 private Map<String, Reply> replies = new HashMap<String, Reply>();
169 /** All new replies. */
170 private Set<String> newReplies = new HashSet<String>();
172 /** All known replies. */
173 private Set<String> knownReplies = new HashSet<String>();
175 /** All bookmarked posts. */
176 /* synchronize access on itself. */
177 private Set<String> bookmarkedPosts = new HashSet<String>();
179 /** Trusted identities, sorted by own identities. */
180 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
183 * Creates a new core.
185 * @param configuration
186 * The configuration of the core
187 * @param freenetInterface
188 * The freenet interface
189 * @param identityManager
190 * The identity manager
192 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
193 this.configuration = configuration;
194 this.freenetInterface = freenetInterface;
195 this.identityManager = identityManager;
196 this.soneDownloader = new SoneDownloader(this, freenetInterface);
197 this.updateChecker = new UpdateChecker(freenetInterface);
201 // LISTENER MANAGEMENT
205 * Adds a new core listener.
207 * @param coreListener
208 * The listener to add
210 public void addCoreListener(CoreListener coreListener) {
211 coreListenerManager.addListener(coreListener);
215 * Removes a core listener.
217 * @param coreListener
218 * The listener to remove
220 public void removeCoreListener(CoreListener coreListener) {
221 coreListenerManager.removeListener(coreListener);
229 * Sets the configuration to use. This will automatically save the current
230 * configuration to the given configuration.
232 * @param configuration
233 * The new configuration to use
235 public void setConfiguration(Configuration configuration) {
236 this.configuration = configuration;
241 * Returns the options used by the core.
243 * @return The options of the core
245 public Preferences getPreferences() {
250 * Returns the identity manager used by the core.
252 * @return The identity manager
254 public IdentityManager getIdentityManager() {
255 return identityManager;
259 * Returns the update checker.
261 * @return The update checker
263 public UpdateChecker getUpdateChecker() {
264 return updateChecker;
268 * Sets the FCP interface to use.
270 * @param fcpInterface
271 * The FCP interface to use
273 public void setFcpInterface(FcpInterface fcpInterface) {
274 this.fcpInterface = fcpInterface;
278 * Returns the status of the given Sone.
281 * The Sone to get the status for
282 * @return The status of the Sone
284 public SoneStatus getSoneStatus(Sone sone) {
285 synchronized (soneStatuses) {
286 return soneStatuses.get(sone);
291 * Sets the status of the given Sone.
294 * The Sone to set the status of
298 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
299 synchronized (soneStatuses) {
300 soneStatuses.put(sone, soneStatus);
305 * Returns whether the given Sone is currently locked.
309 * @return {@code true} if the Sone is locked, {@code false} if it is not
311 public boolean isLocked(Sone sone) {
312 synchronized (lockedSones) {
313 return lockedSones.contains(sone);
318 * Returns all Sones, remote and local.
322 public Set<Sone> getSones() {
323 Set<Sone> allSones = new HashSet<Sone>();
324 allSones.addAll(getLocalSones());
325 allSones.addAll(getRemoteSones());
330 * Returns the Sone with the given ID, regardless whether it’s local or
334 * The ID of the Sone to get
335 * @return The Sone with the given ID, or {@code null} if there is no such
338 public Sone getSone(String id) {
339 return getSone(id, true);
343 * Returns the Sone with the given ID, regardless whether it’s local or
347 * The ID of the Sone to get
349 * {@code true} to create a new Sone if none exists,
350 * {@code false} to return {@code null} if a Sone with the given
352 * @return The Sone with the given ID, or {@code null} if there is no such
355 public Sone getSone(String id, boolean create) {
356 if (isLocalSone(id)) {
357 return getLocalSone(id);
359 return getRemoteSone(id, create);
363 * Checks whether the core knows a Sone with the given ID.
367 * @return {@code true} if there is a Sone with the given ID, {@code false}
370 public boolean hasSone(String id) {
371 return isLocalSone(id) || isRemoteSone(id);
375 * Returns whether the given Sone is a local Sone.
378 * The Sone to check for its locality
379 * @return {@code true} if the given Sone is local, {@code false} otherwise
381 public boolean isLocalSone(Sone sone) {
382 synchronized (localSones) {
383 return localSones.containsKey(sone.getId());
388 * Returns whether the given ID is the ID of a local Sone.
391 * The Sone ID to check for its locality
392 * @return {@code true} if the given ID is a local Sone, {@code false}
395 public boolean isLocalSone(String id) {
396 synchronized (localSones) {
397 return localSones.containsKey(id);
402 * Returns all local Sones.
404 * @return All local Sones
406 public Set<Sone> getLocalSones() {
407 synchronized (localSones) {
408 return new HashSet<Sone>(localSones.values());
413 * Returns the local Sone with the given ID.
416 * The ID of the Sone to get
417 * @return The Sone with the given ID
419 public Sone getLocalSone(String id) {
420 return getLocalSone(id, true);
424 * Returns the local Sone with the given ID, optionally creating a new Sone.
429 * {@code true} to create a new Sone if none exists,
430 * {@code false} to return null if none exists
431 * @return The Sone with the given ID, or {@code null}
433 public Sone getLocalSone(String id, boolean create) {
434 synchronized (localSones) {
435 Sone sone = localSones.get(id);
436 if ((sone == null) && create) {
438 localSones.put(id, sone);
439 setSoneStatus(sone, SoneStatus.unknown);
446 * Returns all remote Sones.
448 * @return All remote Sones
450 public Set<Sone> getRemoteSones() {
451 synchronized (remoteSones) {
452 return new HashSet<Sone>(remoteSones.values());
457 * Returns the remote Sone with the given ID.
460 * The ID of the remote Sone to get
461 * @return The Sone with the given ID
463 public Sone getRemoteSone(String id) {
464 return getRemoteSone(id, true);
468 * Returns the remote Sone with the given ID.
471 * The ID of the remote Sone to get
473 * {@code true} to always create a Sone, {@code false} to return
474 * {@code null} if no Sone with the given ID exists
475 * @return The Sone with the given ID
477 public Sone getRemoteSone(String id, boolean create) {
478 synchronized (remoteSones) {
479 Sone sone = remoteSones.get(id);
480 if ((sone == null) && create) {
482 remoteSones.put(id, sone);
483 setSoneStatus(sone, SoneStatus.unknown);
490 * Returns whether the given Sone is a remote Sone.
494 * @return {@code true} if the given Sone is a remote Sone, {@code false}
497 public boolean isRemoteSone(Sone sone) {
498 synchronized (remoteSones) {
499 return remoteSones.containsKey(sone.getId());
504 * Returns whether the Sone with the given ID is a remote Sone.
507 * The ID of the Sone to check
508 * @return {@code true} if the Sone with the given ID is a remote Sone,
509 * {@code false} otherwise
511 public boolean isRemoteSone(String id) {
512 synchronized (remoteSones) {
513 return remoteSones.containsKey(id);
518 * Returns whether the Sone with the given ID is a new Sone.
521 * The ID of the sone to check for
522 * @return {@code true} if the given Sone is new, false otherwise
524 public boolean isNewSone(String soneId) {
525 synchronized (newSones) {
526 return !knownSones.contains(soneId) && newSones.contains(soneId);
531 * Returns whether the given Sone has been modified.
534 * The Sone to check for modifications
535 * @return {@code true} if a modification has been detected in the Sone,
536 * {@code false} otherwise
538 public boolean isModifiedSone(Sone sone) {
539 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
543 * Returns whether the target Sone is trusted by the origin Sone.
549 * @return {@code true} if the target Sone is trusted by the origin Sone
551 public boolean isSoneTrusted(Sone origin, Sone target) {
552 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
553 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
557 * Returns the post with the given ID.
560 * The ID of the post to get
561 * @return The post with the given ID, or a new post with the given ID
563 public Post getPost(String postId) {
564 return getPost(postId, true);
568 * Returns the post with the given ID, optionally creating a new post.
571 * The ID of the post to get
573 * {@code true} it create a new post if no post with the given ID
574 * exists, {@code false} to return {@code null}
575 * @return The post, or {@code null} if there is no such post
577 public Post getPost(String postId, boolean create) {
578 synchronized (posts) {
579 Post post = posts.get(postId);
580 if ((post == null) && create) {
581 post = new Post(postId);
582 posts.put(postId, post);
589 * Returns whether the given post ID is new.
593 * @return {@code true} if the post is considered to be new, {@code false}
596 public boolean isNewPost(String postId) {
597 synchronized (newPosts) {
598 return !knownPosts.contains(postId) && newPosts.contains(postId);
603 * Returns all posts that have the given Sone as recipient.
605 * @see Post#getRecipient()
607 * The recipient of the posts
608 * @return All posts that have the given Sone as recipient
610 public Set<Post> getDirectedPosts(Sone recipient) {
611 Validation.begin().isNotNull("Recipient", recipient).check();
612 Set<Post> directedPosts = new HashSet<Post>();
613 synchronized (posts) {
614 for (Post post : posts.values()) {
615 if (recipient.equals(post.getRecipient())) {
616 directedPosts.add(post);
620 return directedPosts;
624 * Returns the reply with the given ID. If there is no reply with the given
625 * ID yet, a new one is created.
628 * The ID of the reply to get
631 public Reply getReply(String replyId) {
632 return getReply(replyId, true);
636 * Returns the reply with the given ID. If there is no reply with the given
637 * ID yet, a new one is created, unless {@code create} is false in which
638 * case {@code null} is returned.
641 * The ID of the reply to get
643 * {@code true} to always return a {@link Reply}, {@code false}
644 * to return {@code null} if no reply can be found
645 * @return The reply, or {@code null} if there is no such reply
647 public Reply getReply(String replyId, boolean create) {
648 synchronized (replies) {
649 Reply reply = replies.get(replyId);
650 if (create && (reply == null)) {
651 reply = new Reply(replyId);
652 replies.put(replyId, reply);
659 * Returns all replies for the given post, order ascending by time.
662 * The post to get all replies for
663 * @return All replies for the given post
665 public List<Reply> getReplies(Post post) {
666 Set<Sone> sones = getSones();
667 List<Reply> replies = new ArrayList<Reply>();
668 for (Sone sone : sones) {
669 for (Reply reply : sone.getReplies()) {
670 if (reply.getPost().equals(post)) {
675 Collections.sort(replies, Reply.TIME_COMPARATOR);
680 * Returns whether the reply with the given ID is new.
683 * The ID of the reply to check
684 * @return {@code true} if the reply is considered to be new, {@code false}
687 public boolean isNewReply(String replyId) {
688 synchronized (newReplies) {
689 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
694 * Returns all Sones that have liked the given post.
697 * The post to get the liking Sones for
698 * @return The Sones that like the given post
700 public Set<Sone> getLikes(Post post) {
701 Set<Sone> sones = new HashSet<Sone>();
702 for (Sone sone : getSones()) {
703 if (sone.getLikedPostIds().contains(post.getId())) {
711 * Returns all Sones that have liked the given reply.
714 * The reply to get the liking Sones for
715 * @return The Sones that like the given reply
717 public Set<Sone> getLikes(Reply reply) {
718 Set<Sone> sones = new HashSet<Sone>();
719 for (Sone sone : getSones()) {
720 if (sone.getLikedReplyIds().contains(reply.getId())) {
728 * Returns whether the given post is bookmarked.
732 * @return {@code true} if the given post is bookmarked, {@code false}
735 public boolean isBookmarked(Post post) {
736 return isPostBookmarked(post.getId());
740 * Returns whether the post with the given ID is bookmarked.
743 * The ID of the post to check
744 * @return {@code true} if the post with the given ID is bookmarked,
745 * {@code false} otherwise
747 public boolean isPostBookmarked(String id) {
748 synchronized (bookmarkedPosts) {
749 return bookmarkedPosts.contains(id);
754 * Returns all currently known bookmarked posts.
756 * @return All bookmarked posts
758 public Set<Post> getBookmarkedPosts() {
759 Set<Post> posts = new HashSet<Post>();
760 synchronized (bookmarkedPosts) {
761 for (String bookmarkedPostId : bookmarkedPosts) {
762 Post post = getPost(bookmarkedPostId, false);
776 * Locks the given Sone. A locked Sone will not be inserted by
777 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
783 public void lockSone(Sone sone) {
784 synchronized (lockedSones) {
785 if (lockedSones.add(sone)) {
786 coreListenerManager.fireSoneLocked(sone);
792 * Unlocks the given Sone.
794 * @see #lockSone(Sone)
798 public void unlockSone(Sone sone) {
799 synchronized (lockedSones) {
800 if (lockedSones.remove(sone)) {
801 coreListenerManager.fireSoneUnlocked(sone);
807 * Adds a local Sone from the given ID which has to be the ID of an own
811 * The ID of an own identity to add a Sone for
812 * @return The added (or already existing) Sone
814 public Sone addLocalSone(String id) {
815 synchronized (localSones) {
816 if (localSones.containsKey(id)) {
817 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
818 return localSones.get(id);
820 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
821 if (ownIdentity == null) {
822 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
825 return addLocalSone(ownIdentity);
830 * Adds a local Sone from the given own identity.
833 * The own identity to create a Sone from
834 * @return The added (or already existing) Sone
836 public Sone addLocalSone(OwnIdentity ownIdentity) {
837 if (ownIdentity == null) {
838 logger.log(Level.WARNING, "Given OwnIdentity is null!");
841 synchronized (localSones) {
844 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
845 } catch (MalformedURLException mue1) {
846 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
849 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
850 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
851 /* TODO - load posts ’n stuff */
852 localSones.put(ownIdentity.getId(), sone);
853 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
854 soneInserters.put(sone, soneInserter);
855 setSoneStatus(sone, SoneStatus.idle);
857 if (!preferences.isSoneRescueMode()) {
858 soneInserter.start();
860 new Thread(new Runnable() {
863 @SuppressWarnings("synthetic-access")
865 if (!preferences.isSoneRescueMode()) {
868 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
869 coreListenerManager.fireRescuingSone(sone);
871 long edition = sone.getLatestEdition();
872 /* find the latest edition the node knows about. */
873 Pair<FreenetURI, FetchResult> currentUri = freenetInterface.fetchUri(sone.getRequestUri());
874 if (currentUri != null) {
875 long currentEdition = currentUri.getLeft().getEdition();
876 if (currentEdition > edition) {
877 edition = currentEdition;
880 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
881 logger.log(Level.FINE, "Downloading edition " + edition + "…");
882 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
885 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
887 coreListenerManager.fireRescuedSone(sone);
888 soneInserter.start();
891 }, "Sone Downloader").start();
897 * Creates a new Sone for the given own identity.
900 * The own identity to create a Sone for
901 * @return The created Sone
903 public Sone createSone(OwnIdentity ownIdentity) {
905 ownIdentity.addContext("Sone");
906 } catch (WebOfTrustException wote1) {
907 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
910 Sone sone = addLocalSone(ownIdentity);
911 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
912 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
918 * Adds the Sone of the given identity.
921 * The identity whose Sone to add
922 * @return The added or already existing Sone
924 public Sone addRemoteSone(Identity identity) {
925 if (identity == null) {
926 logger.log(Level.WARNING, "Given Identity is null!");
929 synchronized (remoteSones) {
930 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
931 boolean newSone = sone.getRequestUri() == null;
932 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
933 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
935 synchronized (newSones) {
936 newSone = !knownSones.contains(sone.getId());
938 newSones.add(sone.getId());
942 coreListenerManager.fireNewSoneFound(sone);
943 for (Sone localSone : getLocalSones()) {
944 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
945 localSone.addFriend(sone.getId());
951 remoteSones.put(identity.getId(), sone);
952 soneDownloader.addSone(sone);
953 setSoneStatus(sone, SoneStatus.unknown);
954 soneDownloaders.execute(new Runnable() {
957 @SuppressWarnings("synthetic-access")
959 soneDownloader.fetchSone(sone, sone.getRequestUri());
968 * Retrieves the trust relationship from the origin to the target. If the
969 * trust relationship can not be retrieved, {@code null} is returned.
971 * @see Identity#getTrust(OwnIdentity)
973 * The origin of the trust tree
975 * The target of the trust
976 * @return The trust relationship
978 public Trust getTrust(Sone origin, Sone target) {
979 if (!isLocalSone(origin)) {
980 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
983 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
987 * Sets the trust value of the given origin Sone for the target Sone.
994 * The trust value (from {@code -100} to {@code 100})
996 public void setTrust(Sone origin, Sone target, int trustValue) {
997 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();
999 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1000 } catch (WebOfTrustException wote1) {
1001 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1006 * Removes any trust assignment for the given target Sone.
1013 public void removeTrust(Sone origin, Sone target) {
1014 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1016 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1017 } catch (WebOfTrustException wote1) {
1018 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1023 * Assigns the configured positive trust value for the given target.
1030 public void trustSone(Sone origin, Sone target) {
1031 setTrust(origin, target, preferences.getPositiveTrust());
1035 * Assigns the configured negative trust value for the given target.
1042 public void distrustSone(Sone origin, Sone target) {
1043 setTrust(origin, target, preferences.getNegativeTrust());
1047 * Removes the trust assignment for the given target.
1054 public void untrustSone(Sone origin, Sone target) {
1055 removeTrust(origin, target);
1059 * Updates the stores Sone with the given Sone.
1064 public void updateSone(Sone sone) {
1065 if (hasSone(sone.getId())) {
1066 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1067 Sone storedSone = getSone(sone.getId());
1068 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1069 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1072 synchronized (posts) {
1073 if (!soneRescueMode) {
1074 for (Post post : storedSone.getPosts()) {
1075 posts.remove(post.getId());
1076 if (!sone.getPosts().contains(post)) {
1077 coreListenerManager.firePostRemoved(post);
1081 List<Post> storedPosts = storedSone.getPosts();
1082 synchronized (newPosts) {
1083 for (Post post : sone.getPosts()) {
1084 post.setSone(storedSone);
1085 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1086 newPosts.add(post.getId());
1087 coreListenerManager.fireNewPostFound(post);
1089 posts.put(post.getId(), post);
1093 synchronized (replies) {
1094 if (!soneRescueMode) {
1095 for (Reply reply : storedSone.getReplies()) {
1096 replies.remove(reply.getId());
1097 if (!sone.getReplies().contains(reply)) {
1098 coreListenerManager.fireReplyRemoved(reply);
1102 Set<Reply> storedReplies = storedSone.getReplies();
1103 synchronized (newReplies) {
1104 for (Reply reply : sone.getReplies()) {
1105 reply.setSone(storedSone);
1106 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1107 newReplies.add(reply.getId());
1108 coreListenerManager.fireNewReplyFound(reply);
1110 replies.put(reply.getId(), reply);
1114 synchronized (storedSone) {
1115 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1116 storedSone.setTime(sone.getTime());
1118 storedSone.setClient(sone.getClient());
1119 storedSone.setProfile(sone.getProfile());
1120 if (soneRescueMode) {
1121 for (Post post : sone.getPosts()) {
1122 storedSone.addPost(post);
1124 for (Reply reply : sone.getReplies()) {
1125 storedSone.addReply(reply);
1127 for (String likedPostId : sone.getLikedPostIds()) {
1128 storedSone.addLikedPostId(likedPostId);
1130 for (String likedReplyId : sone.getLikedReplyIds()) {
1131 storedSone.addLikedReplyId(likedReplyId);
1134 storedSone.setPosts(sone.getPosts());
1135 storedSone.setReplies(sone.getReplies());
1136 storedSone.setLikePostIds(sone.getLikedPostIds());
1137 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1139 storedSone.setLatestEdition(sone.getLatestEdition());
1145 * Deletes the given Sone. This will remove the Sone from the
1146 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1147 * and remove the context from its identity.
1150 * The Sone to delete
1152 public void deleteSone(Sone sone) {
1153 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1154 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1157 synchronized (localSones) {
1158 if (!localSones.containsKey(sone.getId())) {
1159 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1162 localSones.remove(sone.getId());
1163 soneInserters.remove(sone).stop();
1166 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1167 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1168 } catch (WebOfTrustException wote1) {
1169 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1172 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1173 } catch (ConfigurationException ce1) {
1174 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1179 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1180 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1183 * The Sone to mark as known
1185 public void markSoneKnown(Sone sone) {
1186 synchronized (newSones) {
1187 if (newSones.remove(sone.getId())) {
1188 knownSones.add(sone.getId());
1189 coreListenerManager.fireMarkSoneKnown(sone);
1190 saveConfiguration();
1196 * Loads and updates the given Sone from the configuration. If any error is
1197 * encountered, loading is aborted and the given Sone is not changed.
1200 * The Sone to load and update
1202 public void loadSone(Sone sone) {
1203 if (!isLocalSone(sone)) {
1204 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1208 /* initialize options. */
1209 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1212 String sonePrefix = "Sone/" + sone.getId();
1213 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1214 if (soneTime == null) {
1215 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1218 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1221 Profile profile = new Profile();
1222 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1223 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1224 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1225 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1226 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1227 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1229 /* load profile fields. */
1231 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1232 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1233 if (fieldName == null) {
1236 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1237 profile.addField(fieldName).setValue(fieldValue);
1241 Set<Post> posts = new HashSet<Post>();
1243 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1244 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1245 if (postId == null) {
1248 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1249 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1250 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1251 if ((postTime == 0) || (postText == null)) {
1252 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1255 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1256 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1257 post.setRecipient(getSone(postRecipientId));
1263 Set<Reply> replies = new HashSet<Reply>();
1265 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1266 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1267 if (replyId == null) {
1270 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1271 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1272 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1273 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1274 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1277 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1280 /* load post likes. */
1281 Set<String> likedPostIds = new HashSet<String>();
1283 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1284 if (likedPostId == null) {
1287 likedPostIds.add(likedPostId);
1290 /* load reply likes. */
1291 Set<String> likedReplyIds = new HashSet<String>();
1293 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1294 if (likedReplyId == null) {
1297 likedReplyIds.add(likedReplyId);
1301 Set<String> friends = new HashSet<String>();
1303 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1304 if (friendId == null) {
1307 friends.add(friendId);
1311 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1313 /* if we’re still here, Sone was loaded successfully. */
1314 synchronized (sone) {
1315 sone.setTime(soneTime);
1316 sone.setProfile(profile);
1317 sone.setPosts(posts);
1318 sone.setReplies(replies);
1319 sone.setLikePostIds(likedPostIds);
1320 sone.setLikeReplyIds(likedReplyIds);
1321 sone.setFriends(friends);
1322 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1324 synchronized (newSones) {
1325 for (String friend : friends) {
1326 knownSones.add(friend);
1329 synchronized (newPosts) {
1330 for (Post post : posts) {
1331 knownPosts.add(post.getId());
1334 synchronized (newReplies) {
1335 for (Reply reply : replies) {
1336 knownReplies.add(reply.getId());
1342 * Saves the given Sone. This will persist all local settings for the given
1343 * Sone, such as the friends list and similar, private options.
1348 public synchronized void saveSone(Sone sone) {
1349 if (!isLocalSone(sone)) {
1350 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1353 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1354 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1358 logger.log(Level.INFO, "Saving Sone: %s", sone);
1360 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1362 /* save Sone into configuration. */
1363 String sonePrefix = "Sone/" + sone.getId();
1364 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1365 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1368 Profile profile = sone.getProfile();
1369 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1370 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1371 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1372 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1373 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1374 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1376 /* save profile fields. */
1377 int fieldCounter = 0;
1378 for (Field profileField : profile.getFields()) {
1379 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1380 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1381 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1383 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1386 int postCounter = 0;
1387 for (Post post : sone.getPosts()) {
1388 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1389 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1390 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1391 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1392 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1394 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1397 int replyCounter = 0;
1398 for (Reply reply : sone.getReplies()) {
1399 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1400 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1401 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1402 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1403 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1405 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1407 /* save post likes. */
1408 int postLikeCounter = 0;
1409 for (String postId : sone.getLikedPostIds()) {
1410 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1412 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1414 /* save reply likes. */
1415 int replyLikeCounter = 0;
1416 for (String replyId : sone.getLikedReplyIds()) {
1417 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1419 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1422 int friendCounter = 0;
1423 for (String friendId : sone.getFriends()) {
1424 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1426 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1429 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1431 configuration.save();
1432 logger.log(Level.INFO, "Sone %s saved.", sone);
1433 } catch (ConfigurationException ce1) {
1434 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1435 } catch (WebOfTrustException wote1) {
1436 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1441 * Creates a new post.
1444 * The Sone that creates the post
1446 * The text of the post
1447 * @return The created post
1449 public Post createPost(Sone sone, String text) {
1450 return createPost(sone, System.currentTimeMillis(), text);
1454 * Creates a new post.
1457 * The Sone that creates the post
1459 * The time of the post
1461 * The text of the post
1462 * @return The created post
1464 public Post createPost(Sone sone, long time, String text) {
1465 return createPost(sone, null, time, text);
1469 * Creates a new post.
1472 * The Sone that creates the post
1474 * The recipient Sone, or {@code null} if this post does not have
1477 * The text of the post
1478 * @return The created post
1480 public Post createPost(Sone sone, Sone recipient, String text) {
1481 return createPost(sone, recipient, System.currentTimeMillis(), text);
1485 * Creates a new post.
1488 * The Sone that creates the post
1490 * The recipient Sone, or {@code null} if this post does not have
1493 * The time of the post
1495 * The text of the post
1496 * @return The created post
1498 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1499 if (!isLocalSone(sone)) {
1500 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1503 Post post = new Post(sone, time, text);
1504 if (recipient != null) {
1505 post.setRecipient(recipient);
1507 synchronized (posts) {
1508 posts.put(post.getId(), post);
1510 synchronized (newPosts) {
1511 newPosts.add(post.getId());
1512 coreListenerManager.fireNewPostFound(post);
1520 * Deletes the given post.
1523 * The post to delete
1525 public void deletePost(Post post) {
1526 if (!isLocalSone(post.getSone())) {
1527 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1530 post.getSone().removePost(post);
1531 synchronized (posts) {
1532 posts.remove(post.getId());
1534 coreListenerManager.firePostRemoved(post);
1535 synchronized (newPosts) {
1536 markPostKnown(post);
1537 knownPosts.remove(post.getId());
1539 saveSone(post.getSone());
1543 * Marks the given post as known, if it is currently a new post (according
1544 * to {@link #isNewPost(String)}).
1547 * The post to mark as known
1549 public void markPostKnown(Post post) {
1550 synchronized (newPosts) {
1551 if (newPosts.remove(post.getId())) {
1552 knownPosts.add(post.getId());
1553 coreListenerManager.fireMarkPostKnown(post);
1554 saveConfiguration();
1560 * Bookmarks the given post.
1563 * The post to bookmark
1565 public void bookmark(Post post) {
1566 bookmarkPost(post.getId());
1570 * Bookmarks the post with the given ID.
1573 * The ID of the post to bookmark
1575 public void bookmarkPost(String id) {
1576 synchronized (bookmarkedPosts) {
1577 bookmarkedPosts.add(id);
1582 * Removes the given post from the bookmarks.
1585 * The post to unbookmark
1587 public void unbookmark(Post post) {
1588 unbookmarkPost(post.getId());
1592 * Removes the post with the given ID from the bookmarks.
1595 * The ID of the post to unbookmark
1597 public void unbookmarkPost(String id) {
1598 synchronized (bookmarkedPosts) {
1599 bookmarkedPosts.remove(id);
1604 * Creates a new reply.
1607 * The Sone that creates the reply
1609 * The post that this reply refers to
1611 * The text of the reply
1612 * @return The created reply
1614 public Reply createReply(Sone sone, Post post, String text) {
1615 return createReply(sone, post, System.currentTimeMillis(), text);
1619 * Creates a new reply.
1622 * The Sone that creates the reply
1624 * The post that this reply refers to
1626 * The time of the reply
1628 * The text of the reply
1629 * @return The created reply
1631 public Reply createReply(Sone sone, Post post, long time, String text) {
1632 if (!isLocalSone(sone)) {
1633 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1636 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1637 synchronized (replies) {
1638 replies.put(reply.getId(), reply);
1640 synchronized (newReplies) {
1641 newReplies.add(reply.getId());
1642 coreListenerManager.fireNewReplyFound(reply);
1644 sone.addReply(reply);
1650 * Deletes the given reply.
1653 * The reply to delete
1655 public void deleteReply(Reply reply) {
1656 Sone sone = reply.getSone();
1657 if (!isLocalSone(sone)) {
1658 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1661 synchronized (replies) {
1662 replies.remove(reply.getId());
1664 synchronized (newReplies) {
1665 markReplyKnown(reply);
1666 knownReplies.remove(reply.getId());
1668 sone.removeReply(reply);
1673 * Marks the given reply as known, if it is currently a new reply (according
1674 * to {@link #isNewReply(String)}).
1677 * The reply to mark as known
1679 public void markReplyKnown(Reply reply) {
1680 synchronized (newReplies) {
1681 if (newReplies.remove(reply.getId())) {
1682 knownReplies.add(reply.getId());
1683 coreListenerManager.fireMarkReplyKnown(reply);
1684 saveConfiguration();
1692 public void start() {
1693 loadConfiguration();
1694 updateChecker.addUpdateListener(this);
1695 updateChecker.start();
1701 public void stop() {
1702 synchronized (localSones) {
1703 for (SoneInserter soneInserter : soneInserters.values()) {
1704 soneInserter.stop();
1706 for (Sone localSone : localSones.values()) {
1707 saveSone(localSone);
1710 updateChecker.stop();
1711 updateChecker.removeUpdateListener(this);
1712 soneDownloader.stop();
1713 saveConfiguration();
1718 * Saves the current options.
1720 public void saveConfiguration() {
1721 synchronized (configuration) {
1722 if (storingConfiguration) {
1723 logger.log(Level.FINE, "Already storing configuration…");
1726 storingConfiguration = true;
1729 /* store the options first. */
1731 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1732 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1733 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1734 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1735 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1736 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1737 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1738 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1739 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1740 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1741 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1742 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1744 /* save known Sones. */
1745 int soneCounter = 0;
1746 synchronized (newSones) {
1747 for (String knownSoneId : knownSones) {
1748 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1750 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1753 /* save known posts. */
1754 int postCounter = 0;
1755 synchronized (newPosts) {
1756 for (String knownPostId : knownPosts) {
1757 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1759 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1762 /* save known replies. */
1763 int replyCounter = 0;
1764 synchronized (newReplies) {
1765 for (String knownReplyId : knownReplies) {
1766 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1768 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1771 /* save bookmarked posts. */
1772 int bookmarkedPostCounter = 0;
1773 synchronized (bookmarkedPosts) {
1774 for (String bookmarkedPostId : bookmarkedPosts) {
1775 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1778 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1781 configuration.save();
1783 } catch (ConfigurationException ce1) {
1784 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1786 synchronized (configuration) {
1787 storingConfiguration = false;
1797 * Loads the configuration.
1799 @SuppressWarnings("unchecked")
1800 private void loadConfiguration() {
1801 /* create options. */
1802 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1805 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1806 SoneInserter.setInsertionDelay(newValue);
1810 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1811 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1812 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1813 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1814 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1815 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1818 @SuppressWarnings("synthetic-access")
1819 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1820 fcpInterface.setActive(newValue);
1823 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1826 @SuppressWarnings("synthetic-access")
1827 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1828 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1832 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1833 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1834 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1836 /* read options from configuration. */
1837 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1838 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1839 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1840 options.getBooleanOption("ClearOnNextRestart").set(null);
1841 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1842 if (clearConfiguration) {
1843 /* stop loading the configuration. */
1847 loadConfigurationValue("InsertionDelay");
1848 loadConfigurationValue("PostsPerPage");
1849 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1850 loadConfigurationValue("PositiveTrust");
1851 loadConfigurationValue("NegativeTrust");
1852 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1853 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1854 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1855 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1857 /* load known Sones. */
1858 int soneCounter = 0;
1860 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1861 if (knownSoneId == null) {
1864 synchronized (newSones) {
1865 knownSones.add(knownSoneId);
1869 /* load known posts. */
1870 int postCounter = 0;
1872 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1873 if (knownPostId == null) {
1876 synchronized (newPosts) {
1877 knownPosts.add(knownPostId);
1881 /* load known replies. */
1882 int replyCounter = 0;
1884 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1885 if (knownReplyId == null) {
1888 synchronized (newReplies) {
1889 knownReplies.add(knownReplyId);
1893 /* load bookmarked posts. */
1894 int bookmarkedPostCounter = 0;
1896 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1897 if (bookmarkedPostId == null) {
1900 synchronized (bookmarkedPosts) {
1901 bookmarkedPosts.add(bookmarkedPostId);
1908 * Loads an {@link Integer} configuration value for the option with the
1909 * given name, logging validation failures.
1912 * The name of the option to load
1914 private void loadConfigurationValue(String optionName) {
1916 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1917 } catch (IllegalArgumentException iae1) {
1918 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1923 * Generate a Sone URI from the given URI and latest edition.
1926 * The URI to derive the Sone URI from
1927 * @return The derived URI
1929 private FreenetURI getSoneUri(String uriString) {
1931 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1933 } catch (MalformedURLException mue1) {
1934 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1940 // INTERFACE IdentityListener
1947 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1948 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1949 if (ownIdentity.hasContext("Sone")) {
1950 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1951 addLocalSone(ownIdentity);
1959 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1960 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1961 trustedIdentities.remove(ownIdentity);
1968 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1969 logger.log(Level.FINEST, "Adding Identity: " + identity);
1970 trustedIdentities.get(ownIdentity).add(identity);
1971 addRemoteSone(identity);
1978 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1979 new Thread(new Runnable() {
1982 @SuppressWarnings("synthetic-access")
1984 Sone sone = getRemoteSone(identity.getId());
1985 sone.setIdentity(identity);
1986 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1987 soneDownloader.addSone(sone);
1988 soneDownloader.fetchSone(sone);
1997 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1998 trustedIdentities.get(ownIdentity).remove(identity);
1999 boolean foundIdentity = false;
2000 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2001 if (trustedIdentity.getKey().equals(ownIdentity)) {
2004 if (trustedIdentity.getValue().contains(identity)) {
2005 foundIdentity = true;
2008 if (foundIdentity) {
2009 /* some local identity still trusts this identity, don’t remove. */
2012 Sone sone = getSone(identity.getId(), false);
2014 /* TODO - we don’t have the Sone anymore. should this happen? */
2017 synchronized (posts) {
2018 synchronized (newPosts) {
2019 for (Post post : sone.getPosts()) {
2020 posts.remove(post.getId());
2021 newPosts.remove(post.getId());
2022 coreListenerManager.firePostRemoved(post);
2026 synchronized (replies) {
2027 synchronized (newReplies) {
2028 for (Reply reply : sone.getReplies()) {
2029 replies.remove(reply.getId());
2030 newReplies.remove(reply.getId());
2031 coreListenerManager.fireReplyRemoved(reply);
2035 synchronized (remoteSones) {
2036 remoteSones.remove(identity.getId());
2038 synchronized (newSones) {
2039 newSones.remove(identity.getId());
2040 coreListenerManager.fireSoneRemoved(sone);
2045 // INTERFACE UpdateListener
2052 public void updateFound(Version version, long releaseTime, long latestEdition) {
2053 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2057 * Convenience interface for external classes that want to access the core’s
2060 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2062 public static class Preferences {
2064 /** The wrapped options. */
2065 private final Options options;
2068 * Creates a new preferences object wrapped around the given options.
2071 * The options to wrap
2073 public Preferences(Options options) {
2074 this.options = options;
2078 * Returns the insertion delay.
2080 * @return The insertion delay
2082 public int getInsertionDelay() {
2083 return options.getIntegerOption("InsertionDelay").get();
2087 * Validates the given insertion delay.
2089 * @param insertionDelay
2090 * The insertion delay to validate
2091 * @return {@code true} if the given insertion delay was valid, {@code
2094 public boolean validateInsertionDelay(Integer insertionDelay) {
2095 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2099 * Sets the insertion delay
2101 * @param insertionDelay
2102 * The new insertion delay, or {@code null} to restore it to
2104 * @return This preferences
2106 public Preferences setInsertionDelay(Integer insertionDelay) {
2107 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2112 * Returns the number of posts to show per page.
2114 * @return The number of posts to show per page
2116 public int getPostsPerPage() {
2117 return options.getIntegerOption("PostsPerPage").get();
2121 * Validates the number of posts per page.
2123 * @param postsPerPage
2124 * The number of posts per page
2125 * @return {@code true} if the number of posts per page was valid,
2126 * {@code false} otherwise
2128 public boolean validatePostsPerPage(Integer postsPerPage) {
2129 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2133 * Sets the number of posts to show per page.
2135 * @param postsPerPage
2136 * The number of posts to show per page
2137 * @return This preferences object
2139 public Preferences setPostsPerPage(Integer postsPerPage) {
2140 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2145 * Returns whether Sone requires full access to be even visible.
2147 * @return {@code true} if Sone requires full access, {@code false}
2150 public boolean isRequireFullAccess() {
2151 return options.getBooleanOption("RequireFullAccess").get();
2155 * Sets whether Sone requires full access to be even visible.
2157 * @param requireFullAccess
2158 * {@code true} if Sone requires full access, {@code false}
2161 public void setRequireFullAccess(Boolean requireFullAccess) {
2162 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2166 * Returns the positive trust.
2168 * @return The positive trust
2170 public int getPositiveTrust() {
2171 return options.getIntegerOption("PositiveTrust").get();
2175 * Validates the positive trust.
2177 * @param positiveTrust
2178 * The positive trust to validate
2179 * @return {@code true} if the positive trust was valid, {@code false}
2182 public boolean validatePositiveTrust(Integer positiveTrust) {
2183 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2187 * Sets the positive trust.
2189 * @param positiveTrust
2190 * The new positive trust, or {@code null} to restore it to
2192 * @return This preferences
2194 public Preferences setPositiveTrust(Integer positiveTrust) {
2195 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2200 * Returns the negative trust.
2202 * @return The negative trust
2204 public int getNegativeTrust() {
2205 return options.getIntegerOption("NegativeTrust").get();
2209 * Validates the negative trust.
2211 * @param negativeTrust
2212 * The negative trust to validate
2213 * @return {@code true} if the negative trust was valid, {@code false}
2216 public boolean validateNegativeTrust(Integer negativeTrust) {
2217 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2221 * Sets the negative trust.
2223 * @param negativeTrust
2224 * The negative trust, or {@code null} to restore it to the
2226 * @return The preferences
2228 public Preferences setNegativeTrust(Integer negativeTrust) {
2229 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2234 * Returns the trust comment. This is the comment that is set in the web
2235 * of trust when a trust value is assigned to an identity.
2237 * @return The trust comment
2239 public String getTrustComment() {
2240 return options.getStringOption("TrustComment").get();
2244 * Sets the trust comment.
2246 * @param trustComment
2247 * The trust comment, or {@code null} to restore it to the
2249 * @return This preferences
2251 public Preferences setTrustComment(String trustComment) {
2252 options.getStringOption("TrustComment").set(trustComment);
2257 * Returns whether the {@link FcpInterface FCP interface} is currently
2260 * @see FcpInterface#setActive(boolean)
2261 * @return {@code true} if the FCP interface is currently active,
2262 * {@code false} otherwise
2264 public boolean isFcpInterfaceActive() {
2265 return options.getBooleanOption("ActivateFcpInterface").get();
2269 * Sets whether the {@link FcpInterface FCP interface} is currently
2272 * @see FcpInterface#setActive(boolean)
2273 * @param fcpInterfaceActive
2274 * {@code true} to activate the FCP interface, {@code false}
2275 * to deactivate the FCP interface
2276 * @return This preferences object
2278 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2279 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2284 * Returns the action level for which full access to the FCP interface
2287 * @return The action level for which full access to the FCP interface
2290 public FullAccessRequired getFcpFullAccessRequired() {
2291 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2295 * Sets the action level for which full access to the FCP interface is
2298 * @param fcpFullAccessRequired
2300 * @return This preferences
2302 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2303 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2308 * Returns whether the rescue mode is active.
2310 * @return {@code true} if the rescue mode is active, {@code false}
2313 public boolean isSoneRescueMode() {
2314 return options.getBooleanOption("SoneRescueMode").get();
2318 * Sets whether the rescue mode is active.
2320 * @param soneRescueMode
2321 * {@code true} if the rescue mode is active, {@code false}
2323 * @return This preferences
2325 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2326 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2331 * Returns whether Sone should clear its settings on the next restart.
2332 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2333 * to return {@code true} as well!
2335 * @return {@code true} if Sone should clear its settings on the next
2336 * restart, {@code false} otherwise
2338 public boolean isClearOnNextRestart() {
2339 return options.getBooleanOption("ClearOnNextRestart").get();
2343 * Sets whether Sone will clear its settings on the next restart.
2345 * @param clearOnNextRestart
2346 * {@code true} if Sone should clear its settings on the next
2347 * restart, {@code false} otherwise
2348 * @return This preferences
2350 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2351 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2356 * Returns whether Sone should really clear its settings on next
2357 * restart. This is a confirmation option that needs to be set in
2358 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2359 * settings on the next restart.
2361 * @return {@code true} if Sone should really clear its settings on the
2362 * next restart, {@code false} otherwise
2364 public boolean isReallyClearOnNextRestart() {
2365 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2369 * Sets whether Sone should really clear its settings on the next
2372 * @param reallyClearOnNextRestart
2373 * {@code true} if Sone should really clear its settings on
2374 * the next restart, {@code false} otherwise
2375 * @return This preferences
2377 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2378 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);