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.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
54 import net.pterodactylus.util.logging.Logging;
55 import net.pterodactylus.util.number.Numbers;
56 import net.pterodactylus.util.validation.IntegerRangeValidator;
57 import net.pterodactylus.util.validation.Validation;
58 import net.pterodactylus.util.version.Version;
59 import freenet.keys.FreenetURI;
64 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66 public class Core implements IdentityListener, UpdateListener {
69 * Enumeration for the possible states of a {@link Sone}.
71 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
73 public enum SoneStatus {
75 /** The Sone is unknown, i.e. not yet downloaded. */
78 /** The Sone is idle, i.e. not being downloaded or inserted. */
81 /** The Sone is currently being inserted. */
84 /** The Sone is currently being downloaded. */
89 private static final Logger logger = Logging.getLogger(Core.class);
92 private final Options options = new Options();
94 /** The preferences. */
95 private final Preferences preferences = new Preferences(options);
97 /** The core listener manager. */
98 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
100 /** The configuration. */
101 private Configuration configuration;
103 /** Whether we’re currently saving the configuration. */
104 private boolean storingConfiguration = false;
106 /** The identity manager. */
107 private final IdentityManager identityManager;
109 /** Interface to freenet. */
110 private final FreenetInterface freenetInterface;
112 /** The Sone downloader. */
113 private final SoneDownloader soneDownloader;
115 /** Sone downloader thread-pool. */
116 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
118 /** The update checker. */
119 private final UpdateChecker updateChecker;
121 /** The FCP interface. */
122 private volatile FcpInterface fcpInterface;
124 /** Whether the core has been stopped. */
125 private volatile boolean stopped;
127 /** The Sones’ statuses. */
128 /* synchronize access on itself. */
129 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
131 /** Locked local Sones. */
132 /* synchronize on itself. */
133 private final Set<Sone> lockedSones = new HashSet<Sone>();
135 /** Sone inserters. */
136 /* synchronize access on this on localSones. */
137 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
139 /** All local Sones. */
140 /* synchronize access on this on itself. */
141 private Map<String, Sone> localSones = new HashMap<String, Sone>();
143 /** All remote Sones. */
144 /* synchronize access on this on itself. */
145 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
147 /** All new Sones. */
148 private Set<String> newSones = new HashSet<String>();
150 /** All known Sones. */
151 /* synchronize access on {@link #newSones}. */
152 private Set<String> knownSones = new HashSet<String>();
155 private Map<String, Post> posts = new HashMap<String, Post>();
157 /** All new posts. */
158 private Set<String> newPosts = new HashSet<String>();
160 /** All known posts. */
161 /* synchronize access on {@link #newPosts}. */
162 private Set<String> knownPosts = new HashSet<String>();
165 private Map<String, Reply> replies = new HashMap<String, Reply>();
167 /** All new replies. */
168 private Set<String> newReplies = new HashSet<String>();
170 /** All known replies. */
171 private Set<String> knownReplies = new HashSet<String>();
173 /** All bookmarked posts. */
174 /* synchronize access on itself. */
175 private Set<String> bookmarkedPosts = new HashSet<String>();
177 /** Trusted identities, sorted by own identities. */
178 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
181 * Creates a new core.
183 * @param configuration
184 * The configuration of the core
185 * @param freenetInterface
186 * The freenet interface
187 * @param identityManager
188 * The identity manager
190 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
191 this.configuration = configuration;
192 this.freenetInterface = freenetInterface;
193 this.identityManager = identityManager;
194 this.soneDownloader = new SoneDownloader(this, freenetInterface);
195 this.updateChecker = new UpdateChecker(freenetInterface);
199 // LISTENER MANAGEMENT
203 * Adds a new core listener.
205 * @param coreListener
206 * The listener to add
208 public void addCoreListener(CoreListener coreListener) {
209 coreListenerManager.addListener(coreListener);
213 * Removes a core listener.
215 * @param coreListener
216 * The listener to remove
218 public void removeCoreListener(CoreListener coreListener) {
219 coreListenerManager.removeListener(coreListener);
227 * Sets the configuration to use. This will automatically save the current
228 * configuration to the given configuration.
230 * @param configuration
231 * The new configuration to use
233 public void setConfiguration(Configuration configuration) {
234 this.configuration = configuration;
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Sets the FCP interface to use.
268 * @param fcpInterface
269 * The FCP interface to use
271 public void setFcpInterface(FcpInterface fcpInterface) {
272 this.fcpInterface = fcpInterface;
276 * Returns the status of the given Sone.
279 * The Sone to get the status for
280 * @return The status of the Sone
282 public SoneStatus getSoneStatus(Sone sone) {
283 synchronized (soneStatuses) {
284 return soneStatuses.get(sone);
289 * Sets the status of the given Sone.
292 * The Sone to set the status of
296 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
297 synchronized (soneStatuses) {
298 soneStatuses.put(sone, soneStatus);
303 * Returns whether the given Sone is currently locked.
307 * @return {@code true} if the Sone is locked, {@code false} if it is not
309 public boolean isLocked(Sone sone) {
310 synchronized (lockedSones) {
311 return lockedSones.contains(sone);
316 * Returns all Sones, remote and local.
320 public Set<Sone> getSones() {
321 Set<Sone> allSones = new HashSet<Sone>();
322 allSones.addAll(getLocalSones());
323 allSones.addAll(getRemoteSones());
328 * Returns the Sone with the given ID, regardless whether it’s local or
332 * The ID of the Sone to get
333 * @return The Sone with the given ID, or {@code null} if there is no such
336 public Sone getSone(String id) {
337 return getSone(id, true);
341 * Returns the Sone with the given ID, regardless whether it’s local or
345 * The ID of the Sone to get
347 * {@code true} to create a new Sone if none exists,
348 * {@code false} to return {@code null} if a Sone with the given
350 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Sone getSone(String id, boolean create) {
354 if (isLocalSone(id)) {
355 return getLocalSone(id);
357 return getRemoteSone(id, create);
361 * Checks whether the core knows a Sone with the given ID.
365 * @return {@code true} if there is a Sone with the given ID, {@code false}
368 public boolean hasSone(String id) {
369 return isLocalSone(id) || isRemoteSone(id);
373 * Returns whether the given Sone is a local Sone.
376 * The Sone to check for its locality
377 * @return {@code true} if the given Sone is local, {@code false} otherwise
379 public boolean isLocalSone(Sone sone) {
380 synchronized (localSones) {
381 return localSones.containsKey(sone.getId());
386 * Returns whether the given ID is the ID of a local Sone.
389 * The Sone ID to check for its locality
390 * @return {@code true} if the given ID is a local Sone, {@code false}
393 public boolean isLocalSone(String id) {
394 synchronized (localSones) {
395 return localSones.containsKey(id);
400 * Returns all local Sones.
402 * @return All local Sones
404 public Set<Sone> getLocalSones() {
405 synchronized (localSones) {
406 return new HashSet<Sone>(localSones.values());
411 * Returns the local Sone with the given ID.
414 * The ID of the Sone to get
415 * @return The Sone with the given ID
417 public Sone getLocalSone(String id) {
418 return getLocalSone(id, true);
422 * Returns the local Sone with the given ID, optionally creating a new Sone.
427 * {@code true} to create a new Sone if none exists,
428 * {@code false} to return null if none exists
429 * @return The Sone with the given ID, or {@code null}
431 public Sone getLocalSone(String id, boolean create) {
432 synchronized (localSones) {
433 Sone sone = localSones.get(id);
434 if ((sone == null) && create) {
436 localSones.put(id, sone);
437 setSoneStatus(sone, SoneStatus.unknown);
444 * Returns all remote Sones.
446 * @return All remote Sones
448 public Set<Sone> getRemoteSones() {
449 synchronized (remoteSones) {
450 return new HashSet<Sone>(remoteSones.values());
455 * Returns the remote Sone with the given ID.
458 * The ID of the remote Sone to get
459 * @return The Sone with the given ID
461 public Sone getRemoteSone(String id) {
462 return getRemoteSone(id, true);
466 * Returns the remote Sone with the given ID.
469 * The ID of the remote Sone to get
471 * {@code true} to always create a Sone, {@code false} to return
472 * {@code null} if no Sone with the given ID exists
473 * @return The Sone with the given ID
475 public Sone getRemoteSone(String id, boolean create) {
476 synchronized (remoteSones) {
477 Sone sone = remoteSones.get(id);
478 if ((sone == null) && create) {
480 remoteSones.put(id, sone);
481 setSoneStatus(sone, SoneStatus.unknown);
488 * Returns whether the given Sone is a remote Sone.
492 * @return {@code true} if the given Sone is a remote Sone, {@code false}
495 public boolean isRemoteSone(Sone sone) {
496 synchronized (remoteSones) {
497 return remoteSones.containsKey(sone.getId());
502 * Returns whether the Sone with the given ID is a remote Sone.
505 * The ID of the Sone to check
506 * @return {@code true} if the Sone with the given ID is a remote Sone,
507 * {@code false} otherwise
509 public boolean isRemoteSone(String id) {
510 synchronized (remoteSones) {
511 return remoteSones.containsKey(id);
516 * Returns whether the Sone with the given ID is a new Sone.
519 * The ID of the sone to check for
520 * @return {@code true} if the given Sone is new, false otherwise
522 public boolean isNewSone(String soneId) {
523 synchronized (newSones) {
524 return !knownSones.contains(soneId) && newSones.contains(soneId);
529 * Returns whether the given Sone has been modified.
532 * The Sone to check for modifications
533 * @return {@code true} if a modification has been detected in the Sone,
534 * {@code false} otherwise
536 public boolean isModifiedSone(Sone sone) {
537 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
541 * Returns whether the target Sone is trusted by the origin Sone.
547 * @return {@code true} if the target Sone is trusted by the origin Sone
549 public boolean isSoneTrusted(Sone origin, Sone target) {
550 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
551 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
555 * Returns the post with the given ID.
558 * The ID of the post to get
559 * @return The post with the given ID, or a new post with the given ID
561 public Post getPost(String postId) {
562 return getPost(postId, true);
566 * Returns the post with the given ID, optionally creating a new post.
569 * The ID of the post to get
571 * {@code true} it create a new post if no post with the given ID
572 * exists, {@code false} to return {@code null}
573 * @return The post, or {@code null} if there is no such post
575 public Post getPost(String postId, boolean create) {
576 synchronized (posts) {
577 Post post = posts.get(postId);
578 if ((post == null) && create) {
579 post = new Post(postId);
580 posts.put(postId, post);
587 * Returns whether the given post ID is new.
591 * @return {@code true} if the post is considered to be new, {@code false}
594 public boolean isNewPost(String postId) {
595 synchronized (newPosts) {
596 return !knownPosts.contains(postId) && newPosts.contains(postId);
601 * Returns all posts that have the given Sone as recipient.
603 * @see Post#getRecipient()
605 * The recipient of the posts
606 * @return All posts that have the given Sone as recipient
608 public Set<Post> getDirectedPosts(Sone recipient) {
609 Validation.begin().isNotNull("Recipient", recipient).check();
610 Set<Post> directedPosts = new HashSet<Post>();
611 synchronized (posts) {
612 for (Post post : posts.values()) {
613 if (recipient.equals(post.getRecipient())) {
614 directedPosts.add(post);
618 return directedPosts;
622 * Returns the reply with the given ID. If there is no reply with the given
623 * ID yet, a new one is created.
626 * The ID of the reply to get
629 public Reply getReply(String replyId) {
630 return getReply(replyId, true);
634 * Returns the reply with the given ID. If there is no reply with the given
635 * ID yet, a new one is created, unless {@code create} is false in which
636 * case {@code null} is returned.
639 * The ID of the reply to get
641 * {@code true} to always return a {@link Reply}, {@code false}
642 * to return {@code null} if no reply can be found
643 * @return The reply, or {@code null} if there is no such reply
645 public Reply getReply(String replyId, boolean create) {
646 synchronized (replies) {
647 Reply reply = replies.get(replyId);
648 if (create && (reply == null)) {
649 reply = new Reply(replyId);
650 replies.put(replyId, reply);
657 * Returns all replies for the given post, order ascending by time.
660 * The post to get all replies for
661 * @return All replies for the given post
663 public List<Reply> getReplies(Post post) {
664 Set<Sone> sones = getSones();
665 List<Reply> replies = new ArrayList<Reply>();
666 for (Sone sone : sones) {
667 for (Reply reply : sone.getReplies()) {
668 if (reply.getPost().equals(post)) {
673 Collections.sort(replies, Reply.TIME_COMPARATOR);
678 * Returns whether the reply with the given ID is new.
681 * The ID of the reply to check
682 * @return {@code true} if the reply is considered to be new, {@code false}
685 public boolean isNewReply(String replyId) {
686 synchronized (newReplies) {
687 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
692 * Returns all Sones that have liked the given post.
695 * The post to get the liking Sones for
696 * @return The Sones that like the given post
698 public Set<Sone> getLikes(Post post) {
699 Set<Sone> sones = new HashSet<Sone>();
700 for (Sone sone : getSones()) {
701 if (sone.getLikedPostIds().contains(post.getId())) {
709 * Returns all Sones that have liked the given reply.
712 * The reply to get the liking Sones for
713 * @return The Sones that like the given reply
715 public Set<Sone> getLikes(Reply reply) {
716 Set<Sone> sones = new HashSet<Sone>();
717 for (Sone sone : getSones()) {
718 if (sone.getLikedReplyIds().contains(reply.getId())) {
726 * Returns whether the given post is bookmarked.
730 * @return {@code true} if the given post is bookmarked, {@code false}
733 public boolean isBookmarked(Post post) {
734 return isPostBookmarked(post.getId());
738 * Returns whether the post with the given ID is bookmarked.
741 * The ID of the post to check
742 * @return {@code true} if the post with the given ID is bookmarked,
743 * {@code false} otherwise
745 public boolean isPostBookmarked(String id) {
746 synchronized (bookmarkedPosts) {
747 return bookmarkedPosts.contains(id);
752 * Returns all currently known bookmarked posts.
754 * @return All bookmarked posts
756 public Set<Post> getBookmarkedPosts() {
757 Set<Post> posts = new HashSet<Post>();
758 synchronized (bookmarkedPosts) {
759 for (String bookmarkedPostId : bookmarkedPosts) {
760 Post post = getPost(bookmarkedPostId, false);
774 * Locks the given Sone. A locked Sone will not be inserted by
775 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
781 public void lockSone(Sone sone) {
782 synchronized (lockedSones) {
783 if (lockedSones.add(sone)) {
784 coreListenerManager.fireSoneLocked(sone);
790 * Unlocks the given Sone.
792 * @see #lockSone(Sone)
796 public void unlockSone(Sone sone) {
797 synchronized (lockedSones) {
798 if (lockedSones.remove(sone)) {
799 coreListenerManager.fireSoneUnlocked(sone);
805 * Adds a local Sone from the given ID which has to be the ID of an own
809 * The ID of an own identity to add a Sone for
810 * @return The added (or already existing) Sone
812 public Sone addLocalSone(String id) {
813 synchronized (localSones) {
814 if (localSones.containsKey(id)) {
815 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
816 return localSones.get(id);
818 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
819 if (ownIdentity == null) {
820 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
823 return addLocalSone(ownIdentity);
828 * Adds a local Sone from the given own identity.
831 * The own identity to create a Sone from
832 * @return The added (or already existing) Sone
834 public Sone addLocalSone(OwnIdentity ownIdentity) {
835 if (ownIdentity == null) {
836 logger.log(Level.WARNING, "Given OwnIdentity is null!");
839 synchronized (localSones) {
842 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
843 } catch (MalformedURLException mue1) {
844 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
847 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
848 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
849 /* TODO - load posts ’n stuff */
850 localSones.put(ownIdentity.getId(), sone);
851 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
852 soneInserters.put(sone, soneInserter);
853 setSoneStatus(sone, SoneStatus.idle);
855 if (!preferences.isSoneRescueMode()) {
856 soneInserter.start();
858 new Thread(new Runnable() {
861 @SuppressWarnings("synthetic-access")
863 if (!preferences.isSoneRescueMode()) {
866 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
867 coreListenerManager.fireRescuingSone(sone);
869 long edition = sone.getLatestEdition();
870 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
871 logger.log(Level.FINE, "Downloading edition " + edition + "…");
872 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
875 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
877 coreListenerManager.fireRescuedSone(sone);
878 soneInserter.start();
881 }, "Sone Downloader").start();
887 * Creates a new Sone for the given own identity.
890 * The own identity to create a Sone for
891 * @return The created Sone
893 public Sone createSone(OwnIdentity ownIdentity) {
895 ownIdentity.addContext("Sone");
896 } catch (WebOfTrustException wote1) {
897 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
900 Sone sone = addLocalSone(ownIdentity);
901 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
902 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
908 * Adds the Sone of the given identity.
911 * The identity whose Sone to add
912 * @return The added or already existing Sone
914 public Sone addRemoteSone(Identity identity) {
915 if (identity == null) {
916 logger.log(Level.WARNING, "Given Identity is null!");
919 synchronized (remoteSones) {
920 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
921 boolean newSone = sone.getRequestUri() == null;
922 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
923 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
925 synchronized (newSones) {
926 newSone = !knownSones.contains(sone.getId());
928 newSones.add(sone.getId());
932 coreListenerManager.fireNewSoneFound(sone);
933 for (Sone localSone : getLocalSones()) {
934 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
935 localSone.addFriend(sone.getId());
940 remoteSones.put(identity.getId(), sone);
941 soneDownloader.addSone(sone);
942 setSoneStatus(sone, SoneStatus.unknown);
943 soneDownloaders.execute(new Runnable() {
946 @SuppressWarnings("synthetic-access")
948 soneDownloader.fetchSone(sone, sone.getRequestUri());
957 * Retrieves the trust relationship from the origin to the target. If the
958 * trust relationship can not be retrieved, {@code null} is returned.
960 * @see Identity#getTrust(OwnIdentity)
962 * The origin of the trust tree
964 * The target of the trust
965 * @return The trust relationship
967 public Trust getTrust(Sone origin, Sone target) {
968 if (!isLocalSone(origin)) {
969 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
972 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
976 * Sets the trust value of the given origin Sone for the target Sone.
983 * The trust value (from {@code -100} to {@code 100})
985 public void setTrust(Sone origin, Sone target, int trustValue) {
986 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();
988 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
989 } catch (WebOfTrustException wote1) {
990 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
995 * Removes any trust assignment for the given target Sone.
1002 public void removeTrust(Sone origin, Sone target) {
1003 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1005 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1006 } catch (WebOfTrustException wote1) {
1007 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1012 * Assigns the configured positive trust value for the given target.
1019 public void trustSone(Sone origin, Sone target) {
1020 setTrust(origin, target, preferences.getPositiveTrust());
1024 * Assigns the configured negative trust value for the given target.
1031 public void distrustSone(Sone origin, Sone target) {
1032 setTrust(origin, target, preferences.getNegativeTrust());
1036 * Removes the trust assignment for the given target.
1043 public void untrustSone(Sone origin, Sone target) {
1044 removeTrust(origin, target);
1048 * Updates the stores Sone with the given Sone.
1053 public void updateSone(Sone sone) {
1054 if (hasSone(sone.getId())) {
1055 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1056 Sone storedSone = getSone(sone.getId());
1057 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1058 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1061 synchronized (posts) {
1062 if (!soneRescueMode) {
1063 for (Post post : storedSone.getPosts()) {
1064 posts.remove(post.getId());
1065 if (!sone.getPosts().contains(post)) {
1066 coreListenerManager.firePostRemoved(post);
1070 List<Post> storedPosts = storedSone.getPosts();
1071 synchronized (newPosts) {
1072 for (Post post : sone.getPosts()) {
1073 post.setSone(storedSone);
1074 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1075 newPosts.add(post.getId());
1076 coreListenerManager.fireNewPostFound(post);
1078 posts.put(post.getId(), post);
1082 synchronized (replies) {
1083 if (!soneRescueMode) {
1084 for (Reply reply : storedSone.getReplies()) {
1085 replies.remove(reply.getId());
1086 if (!sone.getReplies().contains(reply)) {
1087 coreListenerManager.fireReplyRemoved(reply);
1091 Set<Reply> storedReplies = storedSone.getReplies();
1092 synchronized (newReplies) {
1093 for (Reply reply : sone.getReplies()) {
1094 reply.setSone(storedSone);
1095 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1096 newReplies.add(reply.getId());
1097 coreListenerManager.fireNewReplyFound(reply);
1099 replies.put(reply.getId(), reply);
1103 synchronized (storedSone) {
1104 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1105 storedSone.setTime(sone.getTime());
1107 storedSone.setClient(sone.getClient());
1108 storedSone.setProfile(sone.getProfile());
1109 if (soneRescueMode) {
1110 for (Post post : sone.getPosts()) {
1111 storedSone.addPost(post);
1113 for (Reply reply : sone.getReplies()) {
1114 storedSone.addReply(reply);
1116 for (String likedPostId : sone.getLikedPostIds()) {
1117 storedSone.addLikedPostId(likedPostId);
1119 for (String likedReplyId : sone.getLikedReplyIds()) {
1120 storedSone.addLikedReplyId(likedReplyId);
1123 storedSone.setPosts(sone.getPosts());
1124 storedSone.setReplies(sone.getReplies());
1125 storedSone.setLikePostIds(sone.getLikedPostIds());
1126 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1128 storedSone.setLatestEdition(sone.getLatestEdition());
1134 * Deletes the given Sone. This will remove the Sone from the
1135 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1136 * and remove the context from its identity.
1139 * The Sone to delete
1141 public void deleteSone(Sone sone) {
1142 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1143 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1146 synchronized (localSones) {
1147 if (!localSones.containsKey(sone.getId())) {
1148 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1151 localSones.remove(sone.getId());
1152 soneInserters.remove(sone).stop();
1155 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1156 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1157 } catch (WebOfTrustException wote1) {
1158 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1161 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1162 } catch (ConfigurationException ce1) {
1163 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1168 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1169 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1172 * The Sone to mark as known
1174 public void markSoneKnown(Sone sone) {
1175 synchronized (newSones) {
1176 if (newSones.remove(sone.getId())) {
1177 knownSones.add(sone.getId());
1178 coreListenerManager.fireMarkSoneKnown(sone);
1179 saveConfiguration();
1185 * Loads and updates the given Sone from the configuration. If any error is
1186 * encountered, loading is aborted and the given Sone is not changed.
1189 * The Sone to load and update
1191 public void loadSone(Sone sone) {
1192 if (!isLocalSone(sone)) {
1193 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1197 /* initialize options. */
1198 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1201 String sonePrefix = "Sone/" + sone.getId();
1202 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1203 if (soneTime == null) {
1204 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1207 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1210 Profile profile = new Profile();
1211 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1212 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1213 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1214 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1215 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1216 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1218 /* load profile fields. */
1220 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1221 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1222 if (fieldName == null) {
1225 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1226 profile.addField(fieldName).setValue(fieldValue);
1230 Set<Post> posts = new HashSet<Post>();
1232 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1233 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1234 if (postId == null) {
1237 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1238 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1239 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1240 if ((postTime == 0) || (postText == null)) {
1241 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1244 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1245 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1246 post.setRecipient(getSone(postRecipientId));
1252 Set<Reply> replies = new HashSet<Reply>();
1254 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1255 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1256 if (replyId == null) {
1259 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1260 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1261 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1262 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1263 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1266 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1269 /* load post likes. */
1270 Set<String> likedPostIds = new HashSet<String>();
1272 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1273 if (likedPostId == null) {
1276 likedPostIds.add(likedPostId);
1279 /* load reply likes. */
1280 Set<String> likedReplyIds = new HashSet<String>();
1282 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1283 if (likedReplyId == null) {
1286 likedReplyIds.add(likedReplyId);
1290 Set<String> friends = new HashSet<String>();
1292 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1293 if (friendId == null) {
1296 friends.add(friendId);
1300 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1302 /* if we’re still here, Sone was loaded successfully. */
1303 synchronized (sone) {
1304 sone.setTime(soneTime);
1305 sone.setProfile(profile);
1306 sone.setPosts(posts);
1307 sone.setReplies(replies);
1308 sone.setLikePostIds(likedPostIds);
1309 sone.setLikeReplyIds(likedReplyIds);
1310 sone.setFriends(friends);
1311 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1313 synchronized (newSones) {
1314 for (String friend : friends) {
1315 knownSones.add(friend);
1318 synchronized (newPosts) {
1319 for (Post post : posts) {
1320 knownPosts.add(post.getId());
1323 synchronized (newReplies) {
1324 for (Reply reply : replies) {
1325 knownReplies.add(reply.getId());
1331 * Saves the given Sone. This will persist all local settings for the given
1332 * Sone, such as the friends list and similar, private options.
1337 public synchronized void saveSone(Sone sone) {
1338 if (!isLocalSone(sone)) {
1339 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1342 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1343 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1347 logger.log(Level.INFO, "Saving Sone: %s", sone);
1349 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1351 /* save Sone into configuration. */
1352 String sonePrefix = "Sone/" + sone.getId();
1353 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1354 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1357 Profile profile = sone.getProfile();
1358 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1359 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1360 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1361 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1362 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1363 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1365 /* save profile fields. */
1366 int fieldCounter = 0;
1367 for (Field profileField : profile.getFields()) {
1368 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1369 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1370 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1372 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1375 int postCounter = 0;
1376 for (Post post : sone.getPosts()) {
1377 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1378 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1379 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1380 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1381 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1383 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1386 int replyCounter = 0;
1387 for (Reply reply : sone.getReplies()) {
1388 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1389 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1390 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1391 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1392 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1394 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1396 /* save post likes. */
1397 int postLikeCounter = 0;
1398 for (String postId : sone.getLikedPostIds()) {
1399 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1401 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1403 /* save reply likes. */
1404 int replyLikeCounter = 0;
1405 for (String replyId : sone.getLikedReplyIds()) {
1406 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1408 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1411 int friendCounter = 0;
1412 for (String friendId : sone.getFriends()) {
1413 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1415 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1418 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1420 configuration.save();
1421 logger.log(Level.INFO, "Sone %s saved.", sone);
1422 } catch (ConfigurationException ce1) {
1423 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1424 } catch (WebOfTrustException wote1) {
1425 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1430 * Creates a new post.
1433 * The Sone that creates the post
1435 * The text of the post
1436 * @return The created post
1438 public Post createPost(Sone sone, String text) {
1439 return createPost(sone, System.currentTimeMillis(), text);
1443 * Creates a new post.
1446 * The Sone that creates the post
1448 * The time of the post
1450 * The text of the post
1451 * @return The created post
1453 public Post createPost(Sone sone, long time, String text) {
1454 return createPost(sone, null, time, text);
1458 * Creates a new post.
1461 * The Sone that creates the post
1463 * The recipient Sone, or {@code null} if this post does not have
1466 * The text of the post
1467 * @return The created post
1469 public Post createPost(Sone sone, Sone recipient, String text) {
1470 return createPost(sone, recipient, System.currentTimeMillis(), text);
1474 * Creates a new post.
1477 * The Sone that creates the post
1479 * The recipient Sone, or {@code null} if this post does not have
1482 * The time of the post
1484 * The text of the post
1485 * @return The created post
1487 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1488 if (!isLocalSone(sone)) {
1489 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1492 Post post = new Post(sone, time, text);
1493 if (recipient != null) {
1494 post.setRecipient(recipient);
1496 synchronized (posts) {
1497 posts.put(post.getId(), post);
1499 synchronized (newPosts) {
1500 newPosts.add(post.getId());
1501 coreListenerManager.fireNewPostFound(post);
1509 * Deletes the given post.
1512 * The post to delete
1514 public void deletePost(Post post) {
1515 if (!isLocalSone(post.getSone())) {
1516 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1519 post.getSone().removePost(post);
1520 synchronized (posts) {
1521 posts.remove(post.getId());
1523 coreListenerManager.firePostRemoved(post);
1524 synchronized (newPosts) {
1525 markPostKnown(post);
1526 knownPosts.remove(post.getId());
1528 saveSone(post.getSone());
1532 * Marks the given post as known, if it is currently a new post (according
1533 * to {@link #isNewPost(String)}).
1536 * The post to mark as known
1538 public void markPostKnown(Post post) {
1539 synchronized (newPosts) {
1540 if (newPosts.remove(post.getId())) {
1541 knownPosts.add(post.getId());
1542 coreListenerManager.fireMarkPostKnown(post);
1543 saveConfiguration();
1549 * Bookmarks the given post.
1552 * The post to bookmark
1554 public void bookmark(Post post) {
1555 bookmarkPost(post.getId());
1559 * Bookmarks the post with the given ID.
1562 * The ID of the post to bookmark
1564 public void bookmarkPost(String id) {
1565 synchronized (bookmarkedPosts) {
1566 bookmarkedPosts.add(id);
1571 * Removes the given post from the bookmarks.
1574 * The post to unbookmark
1576 public void unbookmark(Post post) {
1577 unbookmarkPost(post.getId());
1581 * Removes the post with the given ID from the bookmarks.
1584 * The ID of the post to unbookmark
1586 public void unbookmarkPost(String id) {
1587 synchronized (bookmarkedPosts) {
1588 bookmarkedPosts.remove(id);
1593 * Creates a new reply.
1596 * The Sone that creates the reply
1598 * The post that this reply refers to
1600 * The text of the reply
1601 * @return The created reply
1603 public Reply createReply(Sone sone, Post post, String text) {
1604 return createReply(sone, post, System.currentTimeMillis(), text);
1608 * Creates a new reply.
1611 * The Sone that creates the reply
1613 * The post that this reply refers to
1615 * The time of the reply
1617 * The text of the reply
1618 * @return The created reply
1620 public Reply createReply(Sone sone, Post post, long time, String text) {
1621 if (!isLocalSone(sone)) {
1622 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1625 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1626 synchronized (replies) {
1627 replies.put(reply.getId(), reply);
1629 synchronized (newReplies) {
1630 newReplies.add(reply.getId());
1631 coreListenerManager.fireNewReplyFound(reply);
1633 sone.addReply(reply);
1639 * Deletes the given reply.
1642 * The reply to delete
1644 public void deleteReply(Reply reply) {
1645 Sone sone = reply.getSone();
1646 if (!isLocalSone(sone)) {
1647 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1650 synchronized (replies) {
1651 replies.remove(reply.getId());
1653 synchronized (newReplies) {
1654 markReplyKnown(reply);
1655 knownReplies.remove(reply.getId());
1657 sone.removeReply(reply);
1662 * Marks the given reply as known, if it is currently a new reply (according
1663 * to {@link #isNewReply(String)}).
1666 * The reply to mark as known
1668 public void markReplyKnown(Reply reply) {
1669 synchronized (newReplies) {
1670 if (newReplies.remove(reply.getId())) {
1671 knownReplies.add(reply.getId());
1672 coreListenerManager.fireMarkReplyKnown(reply);
1673 saveConfiguration();
1681 public void start() {
1682 loadConfiguration();
1683 updateChecker.addUpdateListener(this);
1684 updateChecker.start();
1690 public void stop() {
1691 synchronized (localSones) {
1692 for (SoneInserter soneInserter : soneInserters.values()) {
1693 soneInserter.stop();
1696 updateChecker.stop();
1697 updateChecker.removeUpdateListener(this);
1698 soneDownloader.stop();
1699 saveConfiguration();
1704 * Saves the current options.
1706 public void saveConfiguration() {
1707 synchronized (configuration) {
1708 if (storingConfiguration) {
1709 logger.log(Level.FINE, "Already storing configuration…");
1712 storingConfiguration = true;
1715 /* store the options first. */
1717 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1718 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1719 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1720 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1721 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1722 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1723 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1724 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1725 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1726 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1727 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1728 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1730 /* save known Sones. */
1731 int soneCounter = 0;
1732 synchronized (newSones) {
1733 for (String knownSoneId : knownSones) {
1734 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1736 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1739 /* save known posts. */
1740 int postCounter = 0;
1741 synchronized (newPosts) {
1742 for (String knownPostId : knownPosts) {
1743 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1745 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1748 /* save known replies. */
1749 int replyCounter = 0;
1750 synchronized (newReplies) {
1751 for (String knownReplyId : knownReplies) {
1752 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1754 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1757 /* save bookmarked posts. */
1758 int bookmarkedPostCounter = 0;
1759 synchronized (bookmarkedPosts) {
1760 for (String bookmarkedPostId : bookmarkedPosts) {
1761 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1764 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1767 configuration.save();
1769 } catch (ConfigurationException ce1) {
1770 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1772 synchronized (configuration) {
1773 storingConfiguration = false;
1783 * Loads the configuration.
1785 @SuppressWarnings("unchecked")
1786 private void loadConfiguration() {
1787 /* create options. */
1788 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1791 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1792 SoneInserter.setInsertionDelay(newValue);
1796 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1797 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1798 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1799 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1800 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1801 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1804 @SuppressWarnings("synthetic-access")
1805 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1806 fcpInterface.setActive(newValue);
1809 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1812 @SuppressWarnings("synthetic-access")
1813 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1814 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1818 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1819 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1820 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1822 /* read options from configuration. */
1823 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1824 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1825 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1826 options.getBooleanOption("ClearOnNextRestart").set(null);
1827 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1828 if (clearConfiguration) {
1829 /* stop loading the configuration. */
1833 loadConfigurationValue("InsertionDelay");
1834 loadConfigurationValue("PostsPerPage");
1835 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1836 loadConfigurationValue("PositiveTrust");
1837 loadConfigurationValue("NegativeTrust");
1838 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1839 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1840 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1841 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1843 /* load known Sones. */
1844 int soneCounter = 0;
1846 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1847 if (knownSoneId == null) {
1850 synchronized (newSones) {
1851 knownSones.add(knownSoneId);
1855 /* load known posts. */
1856 int postCounter = 0;
1858 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1859 if (knownPostId == null) {
1862 synchronized (newPosts) {
1863 knownPosts.add(knownPostId);
1867 /* load known replies. */
1868 int replyCounter = 0;
1870 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1871 if (knownReplyId == null) {
1874 synchronized (newReplies) {
1875 knownReplies.add(knownReplyId);
1879 /* load bookmarked posts. */
1880 int bookmarkedPostCounter = 0;
1882 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1883 if (bookmarkedPostId == null) {
1886 synchronized (bookmarkedPosts) {
1887 bookmarkedPosts.add(bookmarkedPostId);
1894 * Loads an {@link Integer} configuration value for the option with the
1895 * given name, logging validation failures.
1898 * The name of the option to load
1900 private void loadConfigurationValue(String optionName) {
1902 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1903 } catch (IllegalArgumentException iae1) {
1904 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1909 * Generate a Sone URI from the given URI and latest edition.
1912 * The URI to derive the Sone URI from
1913 * @return The derived URI
1915 private FreenetURI getSoneUri(String uriString) {
1917 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1919 } catch (MalformedURLException mue1) {
1920 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1926 // INTERFACE IdentityListener
1933 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1934 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1935 if (ownIdentity.hasContext("Sone")) {
1936 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1937 addLocalSone(ownIdentity);
1945 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1946 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1947 trustedIdentities.remove(ownIdentity);
1954 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1955 logger.log(Level.FINEST, "Adding Identity: " + identity);
1956 trustedIdentities.get(ownIdentity).add(identity);
1957 addRemoteSone(identity);
1964 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1965 new Thread(new Runnable() {
1968 @SuppressWarnings("synthetic-access")
1970 Sone sone = getRemoteSone(identity.getId());
1971 sone.setIdentity(identity);
1972 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1973 soneDownloader.addSone(sone);
1974 soneDownloader.fetchSone(sone);
1983 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1984 trustedIdentities.get(ownIdentity).remove(identity);
1985 boolean foundIdentity = false;
1986 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
1987 if (trustedIdentity.getKey().equals(ownIdentity)) {
1990 if (trustedIdentity.getValue().contains(identity)) {
1991 foundIdentity = true;
1994 if (foundIdentity) {
1995 /* some local identity still trusts this identity, don’t remove. */
1998 Sone sone = getSone(identity.getId(), false);
2000 /* TODO - we don’t have the Sone anymore. should this happen? */
2003 synchronized (posts) {
2004 synchronized (newPosts) {
2005 for (Post post : sone.getPosts()) {
2006 posts.remove(post.getId());
2007 newPosts.remove(post.getId());
2008 coreListenerManager.firePostRemoved(post);
2012 synchronized (replies) {
2013 synchronized (newReplies) {
2014 for (Reply reply : sone.getReplies()) {
2015 replies.remove(reply.getId());
2016 newReplies.remove(reply.getId());
2017 coreListenerManager.fireReplyRemoved(reply);
2021 synchronized (remoteSones) {
2022 remoteSones.remove(identity.getId());
2024 synchronized (newSones) {
2025 newSones.remove(identity.getId());
2030 // INTERFACE UpdateListener
2037 public void updateFound(Version version, long releaseTime, long latestEdition) {
2038 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2042 * Convenience interface for external classes that want to access the core’s
2045 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2047 public static class Preferences {
2049 /** The wrapped options. */
2050 private final Options options;
2053 * Creates a new preferences object wrapped around the given options.
2056 * The options to wrap
2058 public Preferences(Options options) {
2059 this.options = options;
2063 * Returns the insertion delay.
2065 * @return The insertion delay
2067 public int getInsertionDelay() {
2068 return options.getIntegerOption("InsertionDelay").get();
2072 * Validates the given insertion delay.
2074 * @param insertionDelay
2075 * The insertion delay to validate
2076 * @return {@code true} if the given insertion delay was valid, {@code
2079 public boolean validateInsertionDelay(Integer insertionDelay) {
2080 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2084 * Sets the insertion delay
2086 * @param insertionDelay
2087 * The new insertion delay, or {@code null} to restore it to
2089 * @return This preferences
2091 public Preferences setInsertionDelay(Integer insertionDelay) {
2092 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2097 * Returns the number of posts to show per page.
2099 * @return The number of posts to show per page
2101 public int getPostsPerPage() {
2102 return options.getIntegerOption("PostsPerPage").get();
2106 * Validates the number of posts per page.
2108 * @param postsPerPage
2109 * The number of posts per page
2110 * @return {@code true} if the number of posts per page was valid,
2111 * {@code false} otherwise
2113 public boolean validatePostsPerPage(Integer postsPerPage) {
2114 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2118 * Sets the number of posts to show per page.
2120 * @param postsPerPage
2121 * The number of posts to show per page
2122 * @return This preferences object
2124 public Preferences setPostsPerPage(Integer postsPerPage) {
2125 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2130 * Returns whether Sone requires full access to be even visible.
2132 * @return {@code true} if Sone requires full access, {@code false}
2135 public boolean isRequireFullAccess() {
2136 return options.getBooleanOption("RequireFullAccess").get();
2140 * Sets whether Sone requires full access to be even visible.
2142 * @param requireFullAccess
2143 * {@code true} if Sone requires full access, {@code false}
2146 public void setRequireFullAccess(Boolean requireFullAccess) {
2147 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2151 * Returns the positive trust.
2153 * @return The positive trust
2155 public int getPositiveTrust() {
2156 return options.getIntegerOption("PositiveTrust").get();
2160 * Validates the positive trust.
2162 * @param positiveTrust
2163 * The positive trust to validate
2164 * @return {@code true} if the positive trust was valid, {@code false}
2167 public boolean validatePositiveTrust(Integer positiveTrust) {
2168 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2172 * Sets the positive trust.
2174 * @param positiveTrust
2175 * The new positive trust, or {@code null} to restore it to
2177 * @return This preferences
2179 public Preferences setPositiveTrust(Integer positiveTrust) {
2180 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2185 * Returns the negative trust.
2187 * @return The negative trust
2189 public int getNegativeTrust() {
2190 return options.getIntegerOption("NegativeTrust").get();
2194 * Validates the negative trust.
2196 * @param negativeTrust
2197 * The negative trust to validate
2198 * @return {@code true} if the negative trust was valid, {@code false}
2201 public boolean validateNegativeTrust(Integer negativeTrust) {
2202 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2206 * Sets the negative trust.
2208 * @param negativeTrust
2209 * The negative trust, or {@code null} to restore it to the
2211 * @return The preferences
2213 public Preferences setNegativeTrust(Integer negativeTrust) {
2214 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2219 * Returns the trust comment. This is the comment that is set in the web
2220 * of trust when a trust value is assigned to an identity.
2222 * @return The trust comment
2224 public String getTrustComment() {
2225 return options.getStringOption("TrustComment").get();
2229 * Sets the trust comment.
2231 * @param trustComment
2232 * The trust comment, or {@code null} to restore it to the
2234 * @return This preferences
2236 public Preferences setTrustComment(String trustComment) {
2237 options.getStringOption("TrustComment").set(trustComment);
2242 * Returns whether the {@link FcpInterface FCP interface} is currently
2245 * @see FcpInterface#setActive(boolean)
2246 * @return {@code true} if the FCP interface is currently active,
2247 * {@code false} otherwise
2249 public boolean isFcpInterfaceActive() {
2250 return options.getBooleanOption("ActivateFcpInterface").get();
2254 * Sets whether the {@link FcpInterface FCP interface} is currently
2257 * @see FcpInterface#setActive(boolean)
2258 * @param fcpInterfaceActive
2259 * {@code true} to activate the FCP interface, {@code false}
2260 * to deactivate the FCP interface
2261 * @return This preferences object
2263 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2264 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2269 * Returns the action level for which full access to the FCP interface
2272 * @return The action level for which full access to the FCP interface
2275 public FullAccessRequired getFcpFullAccessRequired() {
2276 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2280 * Sets the action level for which full access to the FCP interface is
2283 * @param fcpFullAccessRequired
2285 * @return This preferences
2287 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2288 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2293 * Returns whether the rescue mode is active.
2295 * @return {@code true} if the rescue mode is active, {@code false}
2298 public boolean isSoneRescueMode() {
2299 return options.getBooleanOption("SoneRescueMode").get();
2303 * Sets whether the rescue mode is active.
2305 * @param soneRescueMode
2306 * {@code true} if the rescue mode is active, {@code false}
2308 * @return This preferences
2310 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2311 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2316 * Returns whether Sone should clear its settings on the next restart.
2317 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2318 * to return {@code true} as well!
2320 * @return {@code true} if Sone should clear its settings on the next
2321 * restart, {@code false} otherwise
2323 public boolean isClearOnNextRestart() {
2324 return options.getBooleanOption("ClearOnNextRestart").get();
2328 * Sets whether Sone will clear its settings on the next restart.
2330 * @param clearOnNextRestart
2331 * {@code true} if Sone should clear its settings on the next
2332 * restart, {@code false} otherwise
2333 * @return This preferences
2335 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2336 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2341 * Returns whether Sone should really clear its settings on next
2342 * restart. This is a confirmation option that needs to be set in
2343 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2344 * settings on the next restart.
2346 * @return {@code true} if Sone should really clear its settings on the
2347 * next restart, {@code false} otherwise
2349 public boolean isReallyClearOnNextRestart() {
2350 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2354 * Sets whether Sone should really clear its settings on the next
2357 * @param reallyClearOnNextRestart
2358 * {@code true} if Sone should really clear its settings on
2359 * the next restart, {@code false} otherwise
2360 * @return This preferences
2362 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2363 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);