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, SoneProvider, PostProvider {
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
356 public Sone getSone(String id, boolean create) {
357 if (isLocalSone(id)) {
358 return getLocalSone(id);
360 return getRemoteSone(id, create);
364 * Checks whether the core knows a Sone with the given ID.
368 * @return {@code true} if there is a Sone with the given ID, {@code false}
371 public boolean hasSone(String id) {
372 return isLocalSone(id) || isRemoteSone(id);
376 * Returns whether the given Sone is a local Sone.
379 * The Sone to check for its locality
380 * @return {@code true} if the given Sone is local, {@code false} otherwise
382 public boolean isLocalSone(Sone sone) {
383 synchronized (localSones) {
384 return localSones.containsKey(sone.getId());
389 * Returns whether the given ID is the ID of a local Sone.
392 * The Sone ID to check for its locality
393 * @return {@code true} if the given ID is a local Sone, {@code false}
396 public boolean isLocalSone(String id) {
397 synchronized (localSones) {
398 return localSones.containsKey(id);
403 * Returns all local Sones.
405 * @return All local Sones
407 public Set<Sone> getLocalSones() {
408 synchronized (localSones) {
409 return new HashSet<Sone>(localSones.values());
414 * Returns the local Sone with the given ID.
417 * The ID of the Sone to get
418 * @return The Sone with the given ID
420 public Sone getLocalSone(String id) {
421 return getLocalSone(id, true);
425 * Returns the local Sone with the given ID, optionally creating a new Sone.
430 * {@code true} to create a new Sone if none exists,
431 * {@code false} to return null if none exists
432 * @return The Sone with the given ID, or {@code null}
434 public Sone getLocalSone(String id, boolean create) {
435 synchronized (localSones) {
436 Sone sone = localSones.get(id);
437 if ((sone == null) && create) {
439 localSones.put(id, sone);
440 setSoneStatus(sone, SoneStatus.unknown);
447 * Returns all remote Sones.
449 * @return All remote Sones
451 public Set<Sone> getRemoteSones() {
452 synchronized (remoteSones) {
453 return new HashSet<Sone>(remoteSones.values());
458 * Returns the remote Sone with the given ID.
461 * The ID of the remote Sone to get
462 * @return The Sone with the given ID
464 public Sone getRemoteSone(String id) {
465 return getRemoteSone(id, true);
469 * Returns the remote Sone with the given ID.
472 * The ID of the remote Sone to get
474 * {@code true} to always create a Sone, {@code false} to return
475 * {@code null} if no Sone with the given ID exists
476 * @return The Sone with the given ID
478 public Sone getRemoteSone(String id, boolean create) {
479 synchronized (remoteSones) {
480 Sone sone = remoteSones.get(id);
481 if ((sone == null) && create) {
483 remoteSones.put(id, sone);
484 setSoneStatus(sone, SoneStatus.unknown);
491 * Returns whether the given Sone is a remote Sone.
495 * @return {@code true} if the given Sone is a remote Sone, {@code false}
498 public boolean isRemoteSone(Sone sone) {
499 synchronized (remoteSones) {
500 return remoteSones.containsKey(sone.getId());
505 * Returns whether the Sone with the given ID is a remote Sone.
508 * The ID of the Sone to check
509 * @return {@code true} if the Sone with the given ID is a remote Sone,
510 * {@code false} otherwise
512 public boolean isRemoteSone(String id) {
513 synchronized (remoteSones) {
514 return remoteSones.containsKey(id);
519 * Returns whether the Sone with the given ID is a new Sone.
522 * The ID of the sone to check for
523 * @return {@code true} if the given Sone is new, false otherwise
525 public boolean isNewSone(String soneId) {
526 synchronized (newSones) {
527 return !knownSones.contains(soneId) && newSones.contains(soneId);
532 * Returns whether the given Sone has been modified.
535 * The Sone to check for modifications
536 * @return {@code true} if a modification has been detected in the Sone,
537 * {@code false} otherwise
539 public boolean isModifiedSone(Sone sone) {
540 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
544 * Returns whether the target Sone is trusted by the origin Sone.
550 * @return {@code true} if the target Sone is trusted by the origin Sone
552 public boolean isSoneTrusted(Sone origin, Sone target) {
553 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
554 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
558 * Returns the post with the given ID.
561 * The ID of the post to get
562 * @return The post with the given ID, or a new post with the given ID
564 public Post getPost(String postId) {
565 return getPost(postId, true);
569 * Returns the post with the given ID, optionally creating a new post.
572 * The ID of the post to get
574 * {@code true} it create a new post if no post with the given ID
575 * exists, {@code false} to return {@code null}
576 * @return The post, or {@code null} if there is no such post
579 public Post getPost(String postId, boolean create) {
580 synchronized (posts) {
581 Post post = posts.get(postId);
582 if ((post == null) && create) {
583 post = new Post(postId);
584 posts.put(postId, post);
591 * Returns whether the given post ID is new.
595 * @return {@code true} if the post is considered to be new, {@code false}
598 public boolean isNewPost(String postId) {
599 synchronized (newPosts) {
600 return !knownPosts.contains(postId) && newPosts.contains(postId);
605 * Returns all posts that have the given Sone as recipient.
607 * @see Post#getRecipient()
609 * The recipient of the posts
610 * @return All posts that have the given Sone as recipient
612 public Set<Post> getDirectedPosts(Sone recipient) {
613 Validation.begin().isNotNull("Recipient", recipient).check();
614 Set<Post> directedPosts = new HashSet<Post>();
615 synchronized (posts) {
616 for (Post post : posts.values()) {
617 if (recipient.equals(post.getRecipient())) {
618 directedPosts.add(post);
622 return directedPosts;
626 * Returns the reply with the given ID. If there is no reply with the given
627 * ID yet, a new one is created.
630 * The ID of the reply to get
633 public Reply getReply(String replyId) {
634 return getReply(replyId, true);
638 * Returns the reply with the given ID. If there is no reply with the given
639 * ID yet, a new one is created, unless {@code create} is false in which
640 * case {@code null} is returned.
643 * The ID of the reply to get
645 * {@code true} to always return a {@link Reply}, {@code false}
646 * to return {@code null} if no reply can be found
647 * @return The reply, or {@code null} if there is no such reply
649 public Reply getReply(String replyId, boolean create) {
650 synchronized (replies) {
651 Reply reply = replies.get(replyId);
652 if (create && (reply == null)) {
653 reply = new Reply(replyId);
654 replies.put(replyId, reply);
661 * Returns all replies for the given post, order ascending by time.
664 * The post to get all replies for
665 * @return All replies for the given post
667 public List<Reply> getReplies(Post post) {
668 Set<Sone> sones = getSones();
669 List<Reply> replies = new ArrayList<Reply>();
670 for (Sone sone : sones) {
671 for (Reply reply : sone.getReplies()) {
672 if (reply.getPost().equals(post)) {
677 Collections.sort(replies, Reply.TIME_COMPARATOR);
682 * Returns whether the reply with the given ID is new.
685 * The ID of the reply to check
686 * @return {@code true} if the reply is considered to be new, {@code false}
689 public boolean isNewReply(String replyId) {
690 synchronized (newReplies) {
691 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
696 * Returns all Sones that have liked the given post.
699 * The post to get the liking Sones for
700 * @return The Sones that like the given post
702 public Set<Sone> getLikes(Post post) {
703 Set<Sone> sones = new HashSet<Sone>();
704 for (Sone sone : getSones()) {
705 if (sone.getLikedPostIds().contains(post.getId())) {
713 * Returns all Sones that have liked the given reply.
716 * The reply to get the liking Sones for
717 * @return The Sones that like the given reply
719 public Set<Sone> getLikes(Reply reply) {
720 Set<Sone> sones = new HashSet<Sone>();
721 for (Sone sone : getSones()) {
722 if (sone.getLikedReplyIds().contains(reply.getId())) {
730 * Returns whether the given post is bookmarked.
734 * @return {@code true} if the given post is bookmarked, {@code false}
737 public boolean isBookmarked(Post post) {
738 return isPostBookmarked(post.getId());
742 * Returns whether the post with the given ID is bookmarked.
745 * The ID of the post to check
746 * @return {@code true} if the post with the given ID is bookmarked,
747 * {@code false} otherwise
749 public boolean isPostBookmarked(String id) {
750 synchronized (bookmarkedPosts) {
751 return bookmarkedPosts.contains(id);
756 * Returns all currently known bookmarked posts.
758 * @return All bookmarked posts
760 public Set<Post> getBookmarkedPosts() {
761 Set<Post> posts = new HashSet<Post>();
762 synchronized (bookmarkedPosts) {
763 for (String bookmarkedPostId : bookmarkedPosts) {
764 Post post = getPost(bookmarkedPostId, false);
778 * Locks the given Sone. A locked Sone will not be inserted by
779 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
785 public void lockSone(Sone sone) {
786 synchronized (lockedSones) {
787 if (lockedSones.add(sone)) {
788 coreListenerManager.fireSoneLocked(sone);
794 * Unlocks the given Sone.
796 * @see #lockSone(Sone)
800 public void unlockSone(Sone sone) {
801 synchronized (lockedSones) {
802 if (lockedSones.remove(sone)) {
803 coreListenerManager.fireSoneUnlocked(sone);
809 * Adds a local Sone from the given ID which has to be the ID of an own
813 * The ID of an own identity to add a Sone for
814 * @return The added (or already existing) Sone
816 public Sone addLocalSone(String id) {
817 synchronized (localSones) {
818 if (localSones.containsKey(id)) {
819 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
820 return localSones.get(id);
822 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
823 if (ownIdentity == null) {
824 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
827 return addLocalSone(ownIdentity);
832 * Adds a local Sone from the given own identity.
835 * The own identity to create a Sone from
836 * @return The added (or already existing) Sone
838 public Sone addLocalSone(OwnIdentity ownIdentity) {
839 if (ownIdentity == null) {
840 logger.log(Level.WARNING, "Given OwnIdentity is null!");
843 synchronized (localSones) {
846 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
847 } catch (MalformedURLException mue1) {
848 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
851 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
852 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
853 /* TODO - load posts ’n stuff */
854 localSones.put(ownIdentity.getId(), sone);
855 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
856 soneInserters.put(sone, soneInserter);
857 setSoneStatus(sone, SoneStatus.idle);
859 if (!preferences.isSoneRescueMode()) {
860 soneInserter.start();
862 new Thread(new Runnable() {
865 @SuppressWarnings("synthetic-access")
867 if (!preferences.isSoneRescueMode()) {
870 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
871 coreListenerManager.fireRescuingSone(sone);
873 long edition = sone.getLatestEdition();
874 /* find the latest edition the node knows about. */
875 Pair<FreenetURI, FetchResult> currentUri = freenetInterface.fetchUri(sone.getRequestUri());
876 if (currentUri != null) {
877 long currentEdition = currentUri.getLeft().getEdition();
878 if (currentEdition > edition) {
879 edition = currentEdition;
882 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
883 logger.log(Level.FINE, "Downloading edition " + edition + "…");
884 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
887 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
889 coreListenerManager.fireRescuedSone(sone);
890 soneInserter.start();
893 }, "Sone Downloader").start();
899 * Creates a new Sone for the given own identity.
902 * The own identity to create a Sone for
903 * @return The created Sone
905 public Sone createSone(OwnIdentity ownIdentity) {
907 ownIdentity.addContext("Sone");
908 } catch (WebOfTrustException wote1) {
909 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
912 Sone sone = addLocalSone(ownIdentity);
913 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
914 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
920 * Adds the Sone of the given identity.
923 * The identity whose Sone to add
924 * @return The added or already existing Sone
926 public Sone addRemoteSone(Identity identity) {
927 if (identity == null) {
928 logger.log(Level.WARNING, "Given Identity is null!");
931 synchronized (remoteSones) {
932 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
933 boolean newSone = sone.getRequestUri() == null;
934 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
935 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
937 synchronized (newSones) {
938 newSone = !knownSones.contains(sone.getId());
940 newSones.add(sone.getId());
944 coreListenerManager.fireNewSoneFound(sone);
945 for (Sone localSone : getLocalSones()) {
946 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
947 localSone.addFriend(sone.getId());
953 remoteSones.put(identity.getId(), sone);
954 soneDownloader.addSone(sone);
955 setSoneStatus(sone, SoneStatus.unknown);
956 soneDownloaders.execute(new Runnable() {
959 @SuppressWarnings("synthetic-access")
961 soneDownloader.fetchSone(sone, sone.getRequestUri());
970 * Retrieves the trust relationship from the origin to the target. If the
971 * trust relationship can not be retrieved, {@code null} is returned.
973 * @see Identity#getTrust(OwnIdentity)
975 * The origin of the trust tree
977 * The target of the trust
978 * @return The trust relationship
980 public Trust getTrust(Sone origin, Sone target) {
981 if (!isLocalSone(origin)) {
982 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
985 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
989 * Sets the trust value of the given origin Sone for the target Sone.
996 * The trust value (from {@code -100} to {@code 100})
998 public void setTrust(Sone origin, Sone target, int trustValue) {
999 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();
1001 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1002 } catch (WebOfTrustException wote1) {
1003 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1008 * Removes any trust assignment for the given target Sone.
1015 public void removeTrust(Sone origin, Sone target) {
1016 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1018 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1019 } catch (WebOfTrustException wote1) {
1020 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1025 * Assigns the configured positive trust value for the given target.
1032 public void trustSone(Sone origin, Sone target) {
1033 setTrust(origin, target, preferences.getPositiveTrust());
1037 * Assigns the configured negative trust value for the given target.
1044 public void distrustSone(Sone origin, Sone target) {
1045 setTrust(origin, target, preferences.getNegativeTrust());
1049 * Removes the trust assignment for the given target.
1056 public void untrustSone(Sone origin, Sone target) {
1057 removeTrust(origin, target);
1061 * Updates the stores Sone with the given Sone.
1066 public void updateSone(Sone sone) {
1067 if (hasSone(sone.getId())) {
1068 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1069 Sone storedSone = getSone(sone.getId());
1070 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1071 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1074 synchronized (posts) {
1075 if (!soneRescueMode) {
1076 for (Post post : storedSone.getPosts()) {
1077 posts.remove(post.getId());
1078 if (!sone.getPosts().contains(post)) {
1079 coreListenerManager.firePostRemoved(post);
1083 List<Post> storedPosts = storedSone.getPosts();
1084 synchronized (newPosts) {
1085 for (Post post : sone.getPosts()) {
1086 post.setSone(storedSone);
1087 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1088 newPosts.add(post.getId());
1089 coreListenerManager.fireNewPostFound(post);
1091 posts.put(post.getId(), post);
1095 synchronized (replies) {
1096 if (!soneRescueMode) {
1097 for (Reply reply : storedSone.getReplies()) {
1098 replies.remove(reply.getId());
1099 if (!sone.getReplies().contains(reply)) {
1100 coreListenerManager.fireReplyRemoved(reply);
1104 Set<Reply> storedReplies = storedSone.getReplies();
1105 synchronized (newReplies) {
1106 for (Reply reply : sone.getReplies()) {
1107 reply.setSone(storedSone);
1108 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1109 newReplies.add(reply.getId());
1110 coreListenerManager.fireNewReplyFound(reply);
1112 replies.put(reply.getId(), reply);
1116 synchronized (storedSone) {
1117 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1118 storedSone.setTime(sone.getTime());
1120 storedSone.setClient(sone.getClient());
1121 storedSone.setProfile(sone.getProfile());
1122 if (soneRescueMode) {
1123 for (Post post : sone.getPosts()) {
1124 storedSone.addPost(post);
1126 for (Reply reply : sone.getReplies()) {
1127 storedSone.addReply(reply);
1129 for (String likedPostId : sone.getLikedPostIds()) {
1130 storedSone.addLikedPostId(likedPostId);
1132 for (String likedReplyId : sone.getLikedReplyIds()) {
1133 storedSone.addLikedReplyId(likedReplyId);
1136 storedSone.setPosts(sone.getPosts());
1137 storedSone.setReplies(sone.getReplies());
1138 storedSone.setLikePostIds(sone.getLikedPostIds());
1139 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1141 storedSone.setLatestEdition(sone.getLatestEdition());
1147 * Deletes the given Sone. This will remove the Sone from the
1148 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1149 * and remove the context from its identity.
1152 * The Sone to delete
1154 public void deleteSone(Sone sone) {
1155 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1156 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1159 synchronized (localSones) {
1160 if (!localSones.containsKey(sone.getId())) {
1161 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1164 localSones.remove(sone.getId());
1165 soneInserters.remove(sone).stop();
1168 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1169 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1170 } catch (WebOfTrustException wote1) {
1171 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1174 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1175 } catch (ConfigurationException ce1) {
1176 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1181 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1182 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1185 * The Sone to mark as known
1187 public void markSoneKnown(Sone sone) {
1188 synchronized (newSones) {
1189 if (newSones.remove(sone.getId())) {
1190 knownSones.add(sone.getId());
1191 coreListenerManager.fireMarkSoneKnown(sone);
1192 saveConfiguration();
1198 * Loads and updates the given Sone from the configuration. If any error is
1199 * encountered, loading is aborted and the given Sone is not changed.
1202 * The Sone to load and update
1204 public void loadSone(Sone sone) {
1205 if (!isLocalSone(sone)) {
1206 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1210 /* initialize options. */
1211 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1214 String sonePrefix = "Sone/" + sone.getId();
1215 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1216 if (soneTime == null) {
1217 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1220 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1223 Profile profile = new Profile();
1224 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1225 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1226 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1227 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1228 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1229 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1231 /* load profile fields. */
1233 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1234 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1235 if (fieldName == null) {
1238 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1239 profile.addField(fieldName).setValue(fieldValue);
1243 Set<Post> posts = new HashSet<Post>();
1245 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1246 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1247 if (postId == null) {
1250 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1251 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1252 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1253 if ((postTime == 0) || (postText == null)) {
1254 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1257 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1258 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1259 post.setRecipient(getSone(postRecipientId));
1265 Set<Reply> replies = new HashSet<Reply>();
1267 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1268 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1269 if (replyId == null) {
1272 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1273 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1274 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1275 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1276 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1279 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1282 /* load post likes. */
1283 Set<String> likedPostIds = new HashSet<String>();
1285 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1286 if (likedPostId == null) {
1289 likedPostIds.add(likedPostId);
1292 /* load reply likes. */
1293 Set<String> likedReplyIds = new HashSet<String>();
1295 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1296 if (likedReplyId == null) {
1299 likedReplyIds.add(likedReplyId);
1303 Set<String> friends = new HashSet<String>();
1305 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1306 if (friendId == null) {
1309 friends.add(friendId);
1313 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1315 /* if we’re still here, Sone was loaded successfully. */
1316 synchronized (sone) {
1317 sone.setTime(soneTime);
1318 sone.setProfile(profile);
1319 sone.setPosts(posts);
1320 sone.setReplies(replies);
1321 sone.setLikePostIds(likedPostIds);
1322 sone.setLikeReplyIds(likedReplyIds);
1323 sone.setFriends(friends);
1324 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1326 synchronized (newSones) {
1327 for (String friend : friends) {
1328 knownSones.add(friend);
1331 synchronized (newPosts) {
1332 for (Post post : posts) {
1333 knownPosts.add(post.getId());
1336 synchronized (newReplies) {
1337 for (Reply reply : replies) {
1338 knownReplies.add(reply.getId());
1344 * Saves the given Sone. This will persist all local settings for the given
1345 * Sone, such as the friends list and similar, private options.
1350 public synchronized void saveSone(Sone sone) {
1351 if (!isLocalSone(sone)) {
1352 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1355 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1356 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1360 logger.log(Level.INFO, "Saving Sone: %s", sone);
1362 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1364 /* save Sone into configuration. */
1365 String sonePrefix = "Sone/" + sone.getId();
1366 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1367 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1370 Profile profile = sone.getProfile();
1371 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1372 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1373 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1374 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1375 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1376 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1378 /* save profile fields. */
1379 int fieldCounter = 0;
1380 for (Field profileField : profile.getFields()) {
1381 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1382 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1383 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1385 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1388 int postCounter = 0;
1389 for (Post post : sone.getPosts()) {
1390 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1391 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1392 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1393 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1394 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1396 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1399 int replyCounter = 0;
1400 for (Reply reply : sone.getReplies()) {
1401 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1402 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1403 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1404 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1405 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1407 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1409 /* save post likes. */
1410 int postLikeCounter = 0;
1411 for (String postId : sone.getLikedPostIds()) {
1412 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1414 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1416 /* save reply likes. */
1417 int replyLikeCounter = 0;
1418 for (String replyId : sone.getLikedReplyIds()) {
1419 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1421 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1424 int friendCounter = 0;
1425 for (String friendId : sone.getFriends()) {
1426 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1428 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1431 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1433 configuration.save();
1434 logger.log(Level.INFO, "Sone %s saved.", sone);
1435 } catch (ConfigurationException ce1) {
1436 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1437 } catch (WebOfTrustException wote1) {
1438 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1443 * Creates a new post.
1446 * The Sone that creates the post
1448 * The text of the post
1449 * @return The created post
1451 public Post createPost(Sone sone, String text) {
1452 return createPost(sone, System.currentTimeMillis(), text);
1456 * Creates a new post.
1459 * The Sone that creates the post
1461 * The time of the post
1463 * The text of the post
1464 * @return The created post
1466 public Post createPost(Sone sone, long time, String text) {
1467 return createPost(sone, null, time, text);
1471 * Creates a new post.
1474 * The Sone that creates the post
1476 * The recipient Sone, or {@code null} if this post does not have
1479 * The text of the post
1480 * @return The created post
1482 public Post createPost(Sone sone, Sone recipient, String text) {
1483 return createPost(sone, recipient, System.currentTimeMillis(), text);
1487 * Creates a new post.
1490 * The Sone that creates the post
1492 * The recipient Sone, or {@code null} if this post does not have
1495 * The time of the post
1497 * The text of the post
1498 * @return The created post
1500 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1501 if (!isLocalSone(sone)) {
1502 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1505 Post post = new Post(sone, time, text);
1506 if (recipient != null) {
1507 post.setRecipient(recipient);
1509 synchronized (posts) {
1510 posts.put(post.getId(), post);
1512 synchronized (newPosts) {
1513 newPosts.add(post.getId());
1514 coreListenerManager.fireNewPostFound(post);
1522 * Deletes the given post.
1525 * The post to delete
1527 public void deletePost(Post post) {
1528 if (!isLocalSone(post.getSone())) {
1529 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1532 post.getSone().removePost(post);
1533 synchronized (posts) {
1534 posts.remove(post.getId());
1536 coreListenerManager.firePostRemoved(post);
1537 synchronized (newPosts) {
1538 markPostKnown(post);
1539 knownPosts.remove(post.getId());
1541 saveSone(post.getSone());
1545 * Marks the given post as known, if it is currently a new post (according
1546 * to {@link #isNewPost(String)}).
1549 * The post to mark as known
1551 public void markPostKnown(Post post) {
1552 synchronized (newPosts) {
1553 if (newPosts.remove(post.getId())) {
1554 knownPosts.add(post.getId());
1555 coreListenerManager.fireMarkPostKnown(post);
1556 saveConfiguration();
1562 * Bookmarks the given post.
1565 * The post to bookmark
1567 public void bookmark(Post post) {
1568 bookmarkPost(post.getId());
1572 * Bookmarks the post with the given ID.
1575 * The ID of the post to bookmark
1577 public void bookmarkPost(String id) {
1578 synchronized (bookmarkedPosts) {
1579 bookmarkedPosts.add(id);
1584 * Removes the given post from the bookmarks.
1587 * The post to unbookmark
1589 public void unbookmark(Post post) {
1590 unbookmarkPost(post.getId());
1594 * Removes the post with the given ID from the bookmarks.
1597 * The ID of the post to unbookmark
1599 public void unbookmarkPost(String id) {
1600 synchronized (bookmarkedPosts) {
1601 bookmarkedPosts.remove(id);
1606 * Creates a new reply.
1609 * The Sone that creates the reply
1611 * The post that this reply refers to
1613 * The text of the reply
1614 * @return The created reply
1616 public Reply createReply(Sone sone, Post post, String text) {
1617 return createReply(sone, post, System.currentTimeMillis(), text);
1621 * Creates a new reply.
1624 * The Sone that creates the reply
1626 * The post that this reply refers to
1628 * The time of the reply
1630 * The text of the reply
1631 * @return The created reply
1633 public Reply createReply(Sone sone, Post post, long time, String text) {
1634 if (!isLocalSone(sone)) {
1635 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1638 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1639 synchronized (replies) {
1640 replies.put(reply.getId(), reply);
1642 synchronized (newReplies) {
1643 newReplies.add(reply.getId());
1644 coreListenerManager.fireNewReplyFound(reply);
1646 sone.addReply(reply);
1652 * Deletes the given reply.
1655 * The reply to delete
1657 public void deleteReply(Reply reply) {
1658 Sone sone = reply.getSone();
1659 if (!isLocalSone(sone)) {
1660 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1663 synchronized (replies) {
1664 replies.remove(reply.getId());
1666 synchronized (newReplies) {
1667 markReplyKnown(reply);
1668 knownReplies.remove(reply.getId());
1670 sone.removeReply(reply);
1675 * Marks the given reply as known, if it is currently a new reply (according
1676 * to {@link #isNewReply(String)}).
1679 * The reply to mark as known
1681 public void markReplyKnown(Reply reply) {
1682 synchronized (newReplies) {
1683 if (newReplies.remove(reply.getId())) {
1684 knownReplies.add(reply.getId());
1685 coreListenerManager.fireMarkReplyKnown(reply);
1686 saveConfiguration();
1694 public void start() {
1695 loadConfiguration();
1696 updateChecker.addUpdateListener(this);
1697 updateChecker.start();
1703 public void stop() {
1704 synchronized (localSones) {
1705 for (SoneInserter soneInserter : soneInserters.values()) {
1706 soneInserter.stop();
1708 for (Sone localSone : localSones.values()) {
1709 saveSone(localSone);
1712 updateChecker.stop();
1713 updateChecker.removeUpdateListener(this);
1714 soneDownloader.stop();
1715 saveConfiguration();
1720 * Saves the current options.
1722 public void saveConfiguration() {
1723 synchronized (configuration) {
1724 if (storingConfiguration) {
1725 logger.log(Level.FINE, "Already storing configuration…");
1728 storingConfiguration = true;
1731 /* store the options first. */
1733 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1734 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1735 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1736 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1737 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1738 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1739 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1740 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1741 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1742 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1743 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1744 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1746 /* save known Sones. */
1747 int soneCounter = 0;
1748 synchronized (newSones) {
1749 for (String knownSoneId : knownSones) {
1750 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1752 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1755 /* save known posts. */
1756 int postCounter = 0;
1757 synchronized (newPosts) {
1758 for (String knownPostId : knownPosts) {
1759 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1761 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1764 /* save known replies. */
1765 int replyCounter = 0;
1766 synchronized (newReplies) {
1767 for (String knownReplyId : knownReplies) {
1768 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1770 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1773 /* save bookmarked posts. */
1774 int bookmarkedPostCounter = 0;
1775 synchronized (bookmarkedPosts) {
1776 for (String bookmarkedPostId : bookmarkedPosts) {
1777 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1780 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1783 configuration.save();
1785 } catch (ConfigurationException ce1) {
1786 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1788 synchronized (configuration) {
1789 storingConfiguration = false;
1799 * Loads the configuration.
1801 @SuppressWarnings("unchecked")
1802 private void loadConfiguration() {
1803 /* create options. */
1804 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1807 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1808 SoneInserter.setInsertionDelay(newValue);
1812 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1813 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1814 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1815 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1816 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1817 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1820 @SuppressWarnings("synthetic-access")
1821 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1822 fcpInterface.setActive(newValue);
1825 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1828 @SuppressWarnings("synthetic-access")
1829 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1830 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1834 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1835 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1836 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1838 /* read options from configuration. */
1839 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1840 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1841 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1842 options.getBooleanOption("ClearOnNextRestart").set(null);
1843 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1844 if (clearConfiguration) {
1845 /* stop loading the configuration. */
1849 loadConfigurationValue("InsertionDelay");
1850 loadConfigurationValue("PostsPerPage");
1851 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1852 loadConfigurationValue("PositiveTrust");
1853 loadConfigurationValue("NegativeTrust");
1854 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1855 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1856 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1857 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1859 /* load known Sones. */
1860 int soneCounter = 0;
1862 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1863 if (knownSoneId == null) {
1866 synchronized (newSones) {
1867 knownSones.add(knownSoneId);
1871 /* load known posts. */
1872 int postCounter = 0;
1874 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1875 if (knownPostId == null) {
1878 synchronized (newPosts) {
1879 knownPosts.add(knownPostId);
1883 /* load known replies. */
1884 int replyCounter = 0;
1886 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1887 if (knownReplyId == null) {
1890 synchronized (newReplies) {
1891 knownReplies.add(knownReplyId);
1895 /* load bookmarked posts. */
1896 int bookmarkedPostCounter = 0;
1898 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1899 if (bookmarkedPostId == null) {
1902 synchronized (bookmarkedPosts) {
1903 bookmarkedPosts.add(bookmarkedPostId);
1910 * Loads an {@link Integer} configuration value for the option with the
1911 * given name, logging validation failures.
1914 * The name of the option to load
1916 private void loadConfigurationValue(String optionName) {
1918 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1919 } catch (IllegalArgumentException iae1) {
1920 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1925 * Generate a Sone URI from the given URI and latest edition.
1928 * The URI to derive the Sone URI from
1929 * @return The derived URI
1931 private FreenetURI getSoneUri(String uriString) {
1933 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1935 } catch (MalformedURLException mue1) {
1936 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1942 // INTERFACE IdentityListener
1949 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1950 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1951 if (ownIdentity.hasContext("Sone")) {
1952 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1953 addLocalSone(ownIdentity);
1961 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1962 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1963 trustedIdentities.remove(ownIdentity);
1970 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1971 logger.log(Level.FINEST, "Adding Identity: " + identity);
1972 trustedIdentities.get(ownIdentity).add(identity);
1973 addRemoteSone(identity);
1980 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1981 new Thread(new Runnable() {
1984 @SuppressWarnings("synthetic-access")
1986 Sone sone = getRemoteSone(identity.getId());
1987 sone.setIdentity(identity);
1988 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1989 soneDownloader.addSone(sone);
1990 soneDownloader.fetchSone(sone);
1999 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2000 trustedIdentities.get(ownIdentity).remove(identity);
2001 boolean foundIdentity = false;
2002 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2003 if (trustedIdentity.getKey().equals(ownIdentity)) {
2006 if (trustedIdentity.getValue().contains(identity)) {
2007 foundIdentity = true;
2010 if (foundIdentity) {
2011 /* some local identity still trusts this identity, don’t remove. */
2014 Sone sone = getSone(identity.getId(), false);
2016 /* TODO - we don’t have the Sone anymore. should this happen? */
2019 synchronized (posts) {
2020 synchronized (newPosts) {
2021 for (Post post : sone.getPosts()) {
2022 posts.remove(post.getId());
2023 newPosts.remove(post.getId());
2024 coreListenerManager.firePostRemoved(post);
2028 synchronized (replies) {
2029 synchronized (newReplies) {
2030 for (Reply reply : sone.getReplies()) {
2031 replies.remove(reply.getId());
2032 newReplies.remove(reply.getId());
2033 coreListenerManager.fireReplyRemoved(reply);
2037 synchronized (remoteSones) {
2038 remoteSones.remove(identity.getId());
2040 synchronized (newSones) {
2041 newSones.remove(identity.getId());
2042 coreListenerManager.fireSoneRemoved(sone);
2047 // INTERFACE UpdateListener
2054 public void updateFound(Version version, long releaseTime, long latestEdition) {
2055 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2059 * Convenience interface for external classes that want to access the core’s
2062 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2064 public static class Preferences {
2066 /** The wrapped options. */
2067 private final Options options;
2070 * Creates a new preferences object wrapped around the given options.
2073 * The options to wrap
2075 public Preferences(Options options) {
2076 this.options = options;
2080 * Returns the insertion delay.
2082 * @return The insertion delay
2084 public int getInsertionDelay() {
2085 return options.getIntegerOption("InsertionDelay").get();
2089 * Validates the given insertion delay.
2091 * @param insertionDelay
2092 * The insertion delay to validate
2093 * @return {@code true} if the given insertion delay was valid, {@code
2096 public boolean validateInsertionDelay(Integer insertionDelay) {
2097 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2101 * Sets the insertion delay
2103 * @param insertionDelay
2104 * The new insertion delay, or {@code null} to restore it to
2106 * @return This preferences
2108 public Preferences setInsertionDelay(Integer insertionDelay) {
2109 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2114 * Returns the number of posts to show per page.
2116 * @return The number of posts to show per page
2118 public int getPostsPerPage() {
2119 return options.getIntegerOption("PostsPerPage").get();
2123 * Validates the number of posts per page.
2125 * @param postsPerPage
2126 * The number of posts per page
2127 * @return {@code true} if the number of posts per page was valid,
2128 * {@code false} otherwise
2130 public boolean validatePostsPerPage(Integer postsPerPage) {
2131 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2135 * Sets the number of posts to show per page.
2137 * @param postsPerPage
2138 * The number of posts to show per page
2139 * @return This preferences object
2141 public Preferences setPostsPerPage(Integer postsPerPage) {
2142 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2147 * Returns whether Sone requires full access to be even visible.
2149 * @return {@code true} if Sone requires full access, {@code false}
2152 public boolean isRequireFullAccess() {
2153 return options.getBooleanOption("RequireFullAccess").get();
2157 * Sets whether Sone requires full access to be even visible.
2159 * @param requireFullAccess
2160 * {@code true} if Sone requires full access, {@code false}
2163 public void setRequireFullAccess(Boolean requireFullAccess) {
2164 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2168 * Returns the positive trust.
2170 * @return The positive trust
2172 public int getPositiveTrust() {
2173 return options.getIntegerOption("PositiveTrust").get();
2177 * Validates the positive trust.
2179 * @param positiveTrust
2180 * The positive trust to validate
2181 * @return {@code true} if the positive trust was valid, {@code false}
2184 public boolean validatePositiveTrust(Integer positiveTrust) {
2185 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2189 * Sets the positive trust.
2191 * @param positiveTrust
2192 * The new positive trust, or {@code null} to restore it to
2194 * @return This preferences
2196 public Preferences setPositiveTrust(Integer positiveTrust) {
2197 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2202 * Returns the negative trust.
2204 * @return The negative trust
2206 public int getNegativeTrust() {
2207 return options.getIntegerOption("NegativeTrust").get();
2211 * Validates the negative trust.
2213 * @param negativeTrust
2214 * The negative trust to validate
2215 * @return {@code true} if the negative trust was valid, {@code false}
2218 public boolean validateNegativeTrust(Integer negativeTrust) {
2219 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2223 * Sets the negative trust.
2225 * @param negativeTrust
2226 * The negative trust, or {@code null} to restore it to the
2228 * @return The preferences
2230 public Preferences setNegativeTrust(Integer negativeTrust) {
2231 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2236 * Returns the trust comment. This is the comment that is set in the web
2237 * of trust when a trust value is assigned to an identity.
2239 * @return The trust comment
2241 public String getTrustComment() {
2242 return options.getStringOption("TrustComment").get();
2246 * Sets the trust comment.
2248 * @param trustComment
2249 * The trust comment, or {@code null} to restore it to the
2251 * @return This preferences
2253 public Preferences setTrustComment(String trustComment) {
2254 options.getStringOption("TrustComment").set(trustComment);
2259 * Returns whether the {@link FcpInterface FCP interface} is currently
2262 * @see FcpInterface#setActive(boolean)
2263 * @return {@code true} if the FCP interface is currently active,
2264 * {@code false} otherwise
2266 public boolean isFcpInterfaceActive() {
2267 return options.getBooleanOption("ActivateFcpInterface").get();
2271 * Sets whether the {@link FcpInterface FCP interface} is currently
2274 * @see FcpInterface#setActive(boolean)
2275 * @param fcpInterfaceActive
2276 * {@code true} to activate the FCP interface, {@code false}
2277 * to deactivate the FCP interface
2278 * @return This preferences object
2280 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2281 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2286 * Returns the action level for which full access to the FCP interface
2289 * @return The action level for which full access to the FCP interface
2292 public FullAccessRequired getFcpFullAccessRequired() {
2293 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2297 * Sets the action level for which full access to the FCP interface is
2300 * @param fcpFullAccessRequired
2302 * @return This preferences
2304 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2305 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2310 * Returns whether the rescue mode is active.
2312 * @return {@code true} if the rescue mode is active, {@code false}
2315 public boolean isSoneRescueMode() {
2316 return options.getBooleanOption("SoneRescueMode").get();
2320 * Sets whether the rescue mode is active.
2322 * @param soneRescueMode
2323 * {@code true} if the rescue mode is active, {@code false}
2325 * @return This preferences
2327 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2328 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2333 * Returns whether Sone should clear its settings on the next restart.
2334 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2335 * to return {@code true} as well!
2337 * @return {@code true} if Sone should clear its settings on the next
2338 * restart, {@code false} otherwise
2340 public boolean isClearOnNextRestart() {
2341 return options.getBooleanOption("ClearOnNextRestart").get();
2345 * Sets whether Sone will clear its settings on the next restart.
2347 * @param clearOnNextRestart
2348 * {@code true} if Sone should clear its settings on the next
2349 * restart, {@code false} otherwise
2350 * @return This preferences
2352 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2353 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2358 * Returns whether Sone should really clear its settings on next
2359 * restart. This is a confirmation option that needs to be set in
2360 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2361 * settings on the next restart.
2363 * @return {@code true} if Sone should really clear its settings on the
2364 * next restart, {@code false} otherwise
2366 public boolean isReallyClearOnNextRestart() {
2367 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2371 * Sets whether Sone should really clear its settings on the next
2374 * @param reallyClearOnNextRestart
2375 * {@code true} if Sone should really clear its settings on
2376 * the next restart, {@code false} otherwise
2377 * @return This preferences
2379 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2380 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);