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.freenet.wot.Identity;
44 import net.pterodactylus.sone.freenet.wot.IdentityListener;
45 import net.pterodactylus.sone.freenet.wot.IdentityManager;
46 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
47 import net.pterodactylus.sone.freenet.wot.Trust;
48 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
49 import net.pterodactylus.sone.main.SonePlugin;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
52 import net.pterodactylus.util.logging.Logging;
53 import net.pterodactylus.util.number.Numbers;
54 import net.pterodactylus.util.validation.IntegerRangeValidator;
55 import net.pterodactylus.util.validation.Validation;
56 import net.pterodactylus.util.version.Version;
57 import freenet.keys.FreenetURI;
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public class Core implements IdentityListener, UpdateListener {
67 * Enumeration for the possible states of a {@link Sone}.
69 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public enum SoneStatus {
73 /** The Sone is unknown, i.e. not yet downloaded. */
76 /** The Sone is idle, i.e. not being downloaded or inserted. */
79 /** The Sone is currently being inserted. */
82 /** The Sone is currently being downloaded. */
87 private static final Logger logger = Logging.getLogger(Core.class);
90 private final Options options = new Options();
92 /** The preferences. */
93 private final Preferences preferences = new Preferences(options);
95 /** The core listener manager. */
96 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
98 /** The configuration. */
99 private Configuration configuration;
101 /** Whether we’re currently saving the configuration. */
102 private boolean storingConfiguration = false;
104 /** The identity manager. */
105 private final IdentityManager identityManager;
107 /** Interface to freenet. */
108 private final FreenetInterface freenetInterface;
110 /** The Sone downloader. */
111 private final SoneDownloader soneDownloader;
113 /** Sone downloader thread-pool. */
114 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
116 /** The update checker. */
117 private final UpdateChecker updateChecker;
119 /** Whether the core has been stopped. */
120 private volatile boolean stopped;
122 /** The Sones’ statuses. */
123 /* synchronize access on itself. */
124 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
126 /** Locked local Sones. */
127 /* synchronize on itself. */
128 private final Set<Sone> lockedSones = new HashSet<Sone>();
130 /** Sone inserters. */
131 /* synchronize access on this on localSones. */
132 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
134 /** All local Sones. */
135 /* synchronize access on this on itself. */
136 private Map<String, Sone> localSones = new HashMap<String, Sone>();
138 /** All remote Sones. */
139 /* synchronize access on this on itself. */
140 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
142 /** All new Sones. */
143 private Set<String> newSones = new HashSet<String>();
145 /** All known Sones. */
146 /* synchronize access on {@link #newSones}. */
147 private Set<String> knownSones = new HashSet<String>();
150 private Map<String, Post> posts = new HashMap<String, Post>();
152 /** All new posts. */
153 private Set<String> newPosts = new HashSet<String>();
155 /** All known posts. */
156 /* synchronize access on {@link #newPosts}. */
157 private Set<String> knownPosts = new HashSet<String>();
160 private Map<String, Reply> replies = new HashMap<String, Reply>();
162 /** All new replies. */
163 private Set<String> newReplies = new HashSet<String>();
165 /** All known replies. */
166 private Set<String> knownReplies = new HashSet<String>();
168 /** All bookmarked posts. */
169 /* synchronize access on itself. */
170 private Set<String> bookmarkedPosts = new HashSet<String>();
172 /** Trusted identities, sorted by own identities. */
173 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
176 * Creates a new core.
178 * @param configuration
179 * The configuration of the core
180 * @param freenetInterface
181 * The freenet interface
182 * @param identityManager
183 * The identity manager
185 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
186 this.configuration = configuration;
187 this.freenetInterface = freenetInterface;
188 this.identityManager = identityManager;
189 this.soneDownloader = new SoneDownloader(this, freenetInterface);
190 this.updateChecker = new UpdateChecker(freenetInterface);
194 // LISTENER MANAGEMENT
198 * Adds a new core listener.
200 * @param coreListener
201 * The listener to add
203 public void addCoreListener(CoreListener coreListener) {
204 coreListenerManager.addListener(coreListener);
208 * Removes a core listener.
210 * @param coreListener
211 * The listener to remove
213 public void removeCoreListener(CoreListener coreListener) {
214 coreListenerManager.removeListener(coreListener);
222 * Sets the configuration to use. This will automatically save the current
223 * configuration to the given configuration.
225 * @param configuration
226 * The new configuration to use
228 public void setConfiguration(Configuration configuration) {
229 this.configuration = configuration;
234 * Returns the options used by the core.
236 * @return The options of the core
238 public Preferences getPreferences() {
243 * Returns the identity manager used by the core.
245 * @return The identity manager
247 public IdentityManager getIdentityManager() {
248 return identityManager;
252 * Returns the update checker.
254 * @return The update checker
256 public UpdateChecker getUpdateChecker() {
257 return updateChecker;
261 * Returns the status of the given Sone.
264 * The Sone to get the status for
265 * @return The status of the Sone
267 public SoneStatus getSoneStatus(Sone sone) {
268 synchronized (soneStatuses) {
269 return soneStatuses.get(sone);
274 * Sets the status of the given Sone.
277 * The Sone to set the status of
281 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
282 synchronized (soneStatuses) {
283 soneStatuses.put(sone, soneStatus);
288 * Returns whether the given Sone is currently locked.
292 * @return {@code true} if the Sone is locked, {@code false} if it is not
294 public boolean isLocked(Sone sone) {
295 synchronized (lockedSones) {
296 return lockedSones.contains(sone);
301 * Returns all Sones, remote and local.
305 public Set<Sone> getSones() {
306 Set<Sone> allSones = new HashSet<Sone>();
307 allSones.addAll(getLocalSones());
308 allSones.addAll(getRemoteSones());
313 * Returns the Sone with the given ID, regardless whether it’s local or
317 * The ID of the Sone to get
318 * @return The Sone with the given ID, or {@code null} if there is no such
321 public Sone getSone(String id) {
322 return getSone(id, true);
326 * Returns the Sone with the given ID, regardless whether it’s local or
330 * The ID of the Sone to get
332 * {@code true} to create a new Sone if none exists,
333 * {@code false} to return {@code null} if a Sone with the given
335 * @return The Sone with the given ID, or {@code null} if there is no such
338 public Sone getSone(String id, boolean create) {
339 if (isLocalSone(id)) {
340 return getLocalSone(id);
342 return getRemoteSone(id, create);
346 * Checks whether the core knows a Sone with the given ID.
350 * @return {@code true} if there is a Sone with the given ID, {@code false}
353 public boolean hasSone(String id) {
354 return isLocalSone(id) || isRemoteSone(id);
358 * Returns whether the given Sone is a local Sone.
361 * The Sone to check for its locality
362 * @return {@code true} if the given Sone is local, {@code false} otherwise
364 public boolean isLocalSone(Sone sone) {
365 synchronized (localSones) {
366 return localSones.containsKey(sone.getId());
371 * Returns whether the given ID is the ID of a local Sone.
374 * The Sone ID to check for its locality
375 * @return {@code true} if the given ID is a local Sone, {@code false}
378 public boolean isLocalSone(String id) {
379 synchronized (localSones) {
380 return localSones.containsKey(id);
385 * Returns all local Sones.
387 * @return All local Sones
389 public Set<Sone> getLocalSones() {
390 synchronized (localSones) {
391 return new HashSet<Sone>(localSones.values());
396 * Returns the local Sone with the given ID.
399 * The ID of the Sone to get
400 * @return The Sone with the given ID
402 public Sone getLocalSone(String id) {
403 return getLocalSone(id, true);
407 * Returns the local Sone with the given ID, optionally creating a new Sone.
412 * {@code true} to create a new Sone if none exists,
413 * {@code false} to return null if none exists
414 * @return The Sone with the given ID, or {@code null}
416 public Sone getLocalSone(String id, boolean create) {
417 synchronized (localSones) {
418 Sone sone = localSones.get(id);
419 if ((sone == null) && create) {
421 localSones.put(id, sone);
422 setSoneStatus(sone, SoneStatus.unknown);
429 * Returns all remote Sones.
431 * @return All remote Sones
433 public Set<Sone> getRemoteSones() {
434 synchronized (remoteSones) {
435 return new HashSet<Sone>(remoteSones.values());
440 * Returns the remote Sone with the given ID.
443 * The ID of the remote Sone to get
444 * @return The Sone with the given ID
446 public Sone getRemoteSone(String id) {
447 return getRemoteSone(id, true);
451 * Returns the remote Sone with the given ID.
454 * The ID of the remote Sone to get
456 * {@code true} to always create a Sone, {@code false} to return
457 * {@code null} if no Sone with the given ID exists
458 * @return The Sone with the given ID
460 public Sone getRemoteSone(String id, boolean create) {
461 synchronized (remoteSones) {
462 Sone sone = remoteSones.get(id);
463 if ((sone == null) && create) {
465 remoteSones.put(id, sone);
466 setSoneStatus(sone, SoneStatus.unknown);
473 * Returns whether the given Sone is a remote Sone.
477 * @return {@code true} if the given Sone is a remote Sone, {@code false}
480 public boolean isRemoteSone(Sone sone) {
481 synchronized (remoteSones) {
482 return remoteSones.containsKey(sone.getId());
487 * Returns whether the Sone with the given ID is a remote Sone.
490 * The ID of the Sone to check
491 * @return {@code true} if the Sone with the given ID is a remote Sone,
492 * {@code false} otherwise
494 public boolean isRemoteSone(String id) {
495 synchronized (remoteSones) {
496 return remoteSones.containsKey(id);
501 * Returns whether the Sone with the given ID is a new Sone.
504 * The ID of the sone to check for
505 * @return {@code true} if the given Sone is new, false otherwise
507 public boolean isNewSone(String soneId) {
508 synchronized (newSones) {
509 return !knownSones.contains(soneId) && newSones.contains(soneId);
514 * Returns whether the given Sone has been modified.
517 * The Sone to check for modifications
518 * @return {@code true} if a modification has been detected in the Sone,
519 * {@code false} otherwise
521 public boolean isModifiedSone(Sone sone) {
522 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
526 * Returns whether the target Sone is trusted by the origin Sone.
532 * @return {@code true} if the target Sone is trusted by the origin Sone
534 public boolean isSoneTrusted(Sone origin, Sone target) {
535 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
536 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
540 * Returns the post with the given ID.
543 * The ID of the post to get
544 * @return The post with the given ID, or a new post with the given ID
546 public Post getPost(String postId) {
547 return getPost(postId, true);
551 * Returns the post with the given ID, optionally creating a new post.
554 * The ID of the post to get
556 * {@code true} it create a new post if no post with the given ID
557 * exists, {@code false} to return {@code null}
558 * @return The post, or {@code null} if there is no such post
560 public Post getPost(String postId, boolean create) {
561 synchronized (posts) {
562 Post post = posts.get(postId);
563 if ((post == null) && create) {
564 post = new Post(postId);
565 posts.put(postId, post);
572 * Returns whether the given post ID is new.
576 * @return {@code true} if the post is considered to be new, {@code false}
579 public boolean isNewPost(String postId) {
580 synchronized (newPosts) {
581 return !knownPosts.contains(postId) && newPosts.contains(postId);
586 * Returns all posts that have the given Sone as recipient.
588 * @see Post#getRecipient()
590 * The recipient of the posts
591 * @return All posts that have the given Sone as recipient
593 public Set<Post> getDirectedPosts(Sone recipient) {
594 Validation.begin().isNotNull("Recipient", recipient).check();
595 Set<Post> directedPosts = new HashSet<Post>();
596 synchronized (posts) {
597 for (Post post : posts.values()) {
598 if (recipient.equals(post.getRecipient())) {
599 directedPosts.add(post);
603 return directedPosts;
607 * Returns the reply with the given ID. If there is no reply with the given
608 * ID yet, a new one is created.
611 * The ID of the reply to get
614 public Reply getReply(String replyId) {
615 return getReply(replyId, true);
619 * Returns the reply with the given ID. If there is no reply with the given
620 * ID yet, a new one is created, unless {@code create} is false in which
621 * case {@code null} is returned.
624 * The ID of the reply to get
626 * {@code true} to always return a {@link Reply}, {@code false}
627 * to return {@code null} if no reply can be found
628 * @return The reply, or {@code null} if there is no such reply
630 public Reply getReply(String replyId, boolean create) {
631 synchronized (replies) {
632 Reply reply = replies.get(replyId);
633 if (create && (reply == null)) {
634 reply = new Reply(replyId);
635 replies.put(replyId, reply);
642 * Returns all replies for the given post, order ascending by time.
645 * The post to get all replies for
646 * @return All replies for the given post
648 public List<Reply> getReplies(Post post) {
649 Set<Sone> sones = getSones();
650 List<Reply> replies = new ArrayList<Reply>();
651 for (Sone sone : sones) {
652 for (Reply reply : sone.getReplies()) {
653 if (reply.getPost().equals(post)) {
658 Collections.sort(replies, Reply.TIME_COMPARATOR);
663 * Returns whether the reply with the given ID is new.
666 * The ID of the reply to check
667 * @return {@code true} if the reply is considered to be new, {@code false}
670 public boolean isNewReply(String replyId) {
671 synchronized (newReplies) {
672 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
677 * Returns all Sones that have liked the given post.
680 * The post to get the liking Sones for
681 * @return The Sones that like the given post
683 public Set<Sone> getLikes(Post post) {
684 Set<Sone> sones = new HashSet<Sone>();
685 for (Sone sone : getSones()) {
686 if (sone.getLikedPostIds().contains(post.getId())) {
694 * Returns all Sones that have liked the given reply.
697 * The reply to get the liking Sones for
698 * @return The Sones that like the given reply
700 public Set<Sone> getLikes(Reply reply) {
701 Set<Sone> sones = new HashSet<Sone>();
702 for (Sone sone : getSones()) {
703 if (sone.getLikedReplyIds().contains(reply.getId())) {
711 * Returns whether the given post is bookmarked.
715 * @return {@code true} if the given post is bookmarked, {@code false}
718 public boolean isBookmarked(Post post) {
719 return isPostBookmarked(post.getId());
723 * Returns whether the post with the given ID is bookmarked.
726 * The ID of the post to check
727 * @return {@code true} if the post with the given ID is bookmarked,
728 * {@code false} otherwise
730 public boolean isPostBookmarked(String id) {
731 synchronized (bookmarkedPosts) {
732 return bookmarkedPosts.contains(id);
737 * Returns all currently known bookmarked posts.
739 * @return All bookmarked posts
741 public Set<Post> getBookmarkedPosts() {
742 Set<Post> posts = new HashSet<Post>();
743 synchronized (bookmarkedPosts) {
744 for (String bookmarkedPostId : bookmarkedPosts) {
745 Post post = getPost(bookmarkedPostId, false);
759 * Locks the given Sone. A locked Sone will not be inserted by
760 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
766 public void lockSone(Sone sone) {
767 synchronized (lockedSones) {
768 if (lockedSones.add(sone)) {
769 coreListenerManager.fireSoneLocked(sone);
775 * Unlocks the given Sone.
777 * @see #lockSone(Sone)
781 public void unlockSone(Sone sone) {
782 synchronized (lockedSones) {
783 if (lockedSones.remove(sone)) {
784 coreListenerManager.fireSoneUnlocked(sone);
790 * Adds a local Sone from the given ID which has to be the ID of an own
794 * The ID of an own identity to add a Sone for
795 * @return The added (or already existing) Sone
797 public Sone addLocalSone(String id) {
798 synchronized (localSones) {
799 if (localSones.containsKey(id)) {
800 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
801 return localSones.get(id);
803 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
804 if (ownIdentity == null) {
805 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
808 return addLocalSone(ownIdentity);
813 * Adds a local Sone from the given own identity.
816 * The own identity to create a Sone from
817 * @return The added (or already existing) Sone
819 public Sone addLocalSone(OwnIdentity ownIdentity) {
820 if (ownIdentity == null) {
821 logger.log(Level.WARNING, "Given OwnIdentity is null!");
824 synchronized (localSones) {
827 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
828 } catch (MalformedURLException mue1) {
829 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
832 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
833 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
834 /* TODO - load posts ’n stuff */
835 localSones.put(ownIdentity.getId(), sone);
836 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
837 soneInserters.put(sone, soneInserter);
838 setSoneStatus(sone, SoneStatus.idle);
840 if (!preferences.isSoneRescueMode()) {
841 soneInserter.start();
843 new Thread(new Runnable() {
846 @SuppressWarnings("synthetic-access")
848 if (!preferences.isSoneRescueMode()) {
851 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
852 coreListenerManager.fireRescuingSone(sone);
854 long edition = sone.getLatestEdition();
855 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
856 logger.log(Level.FINE, "Downloading edition " + edition + "…");
857 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
860 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
862 coreListenerManager.fireRescuedSone(sone);
863 soneInserter.start();
866 }, "Sone Downloader").start();
872 * Creates a new Sone for the given own identity.
875 * The own identity to create a Sone for
876 * @return The created Sone
878 public Sone createSone(OwnIdentity ownIdentity) {
880 ownIdentity.addContext("Sone");
881 } catch (WebOfTrustException wote1) {
882 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
885 Sone sone = addLocalSone(ownIdentity);
886 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
887 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
893 * Adds the Sone of the given identity.
896 * The identity whose Sone to add
897 * @return The added or already existing Sone
899 public Sone addRemoteSone(Identity identity) {
900 if (identity == null) {
901 logger.log(Level.WARNING, "Given Identity is null!");
904 synchronized (remoteSones) {
905 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
906 boolean newSone = sone.getRequestUri() == null;
907 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
908 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
910 synchronized (newSones) {
911 newSone = !knownSones.contains(sone.getId());
913 newSones.add(sone.getId());
917 coreListenerManager.fireNewSoneFound(sone);
918 for (Sone localSone : getLocalSones()) {
919 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
920 localSone.addFriend(sone.getId());
925 remoteSones.put(identity.getId(), sone);
926 soneDownloader.addSone(sone);
927 setSoneStatus(sone, SoneStatus.unknown);
928 soneDownloaders.execute(new Runnable() {
931 @SuppressWarnings("synthetic-access")
933 soneDownloader.fetchSone(sone, sone.getRequestUri());
942 * Retrieves the trust relationship from the origin to the target. If the
943 * trust relationship can not be retrieved, {@code null} is returned.
945 * @see Identity#getTrust(OwnIdentity)
947 * The origin of the trust tree
949 * The target of the trust
950 * @return The trust relationship
952 public Trust getTrust(Sone origin, Sone target) {
953 if (!isLocalSone(origin)) {
954 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
957 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
961 * Sets the trust value of the given origin Sone for the target Sone.
968 * The trust value (from {@code -100} to {@code 100})
970 public void setTrust(Sone origin, Sone target, int trustValue) {
971 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();
973 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
974 } catch (WebOfTrustException wote1) {
975 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
980 * Removes any trust assignment for the given target Sone.
987 public void removeTrust(Sone origin, Sone target) {
988 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
990 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
991 } catch (WebOfTrustException wote1) {
992 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
997 * Assigns the configured positive trust value for the given target.
1004 public void trustSone(Sone origin, Sone target) {
1005 setTrust(origin, target, preferences.getPositiveTrust());
1009 * Assigns the configured negative trust value for the given target.
1016 public void distrustSone(Sone origin, Sone target) {
1017 setTrust(origin, target, preferences.getNegativeTrust());
1021 * Removes the trust assignment for the given target.
1028 public void untrustSone(Sone origin, Sone target) {
1029 removeTrust(origin, target);
1033 * Updates the stores Sone with the given Sone.
1038 public void updateSone(Sone sone) {
1039 if (hasSone(sone.getId())) {
1040 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1041 Sone storedSone = getSone(sone.getId());
1042 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1043 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1046 synchronized (posts) {
1047 if (!soneRescueMode) {
1048 for (Post post : storedSone.getPosts()) {
1049 posts.remove(post.getId());
1050 if (!sone.getPosts().contains(post)) {
1051 coreListenerManager.firePostRemoved(post);
1055 List<Post> storedPosts = storedSone.getPosts();
1056 synchronized (newPosts) {
1057 for (Post post : sone.getPosts()) {
1058 post.setSone(storedSone);
1059 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1060 newPosts.add(post.getId());
1061 coreListenerManager.fireNewPostFound(post);
1063 posts.put(post.getId(), post);
1067 synchronized (replies) {
1068 if (!soneRescueMode) {
1069 for (Reply reply : storedSone.getReplies()) {
1070 replies.remove(reply.getId());
1071 if (!sone.getReplies().contains(reply)) {
1072 coreListenerManager.fireReplyRemoved(reply);
1076 Set<Reply> storedReplies = storedSone.getReplies();
1077 synchronized (newReplies) {
1078 for (Reply reply : sone.getReplies()) {
1079 reply.setSone(storedSone);
1080 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1081 newReplies.add(reply.getId());
1082 coreListenerManager.fireNewReplyFound(reply);
1084 replies.put(reply.getId(), reply);
1088 synchronized (storedSone) {
1089 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1090 storedSone.setTime(sone.getTime());
1092 storedSone.setClient(sone.getClient());
1093 storedSone.setProfile(sone.getProfile());
1094 if (soneRescueMode) {
1095 for (Post post : sone.getPosts()) {
1096 storedSone.addPost(post);
1098 for (Reply reply : sone.getReplies()) {
1099 storedSone.addReply(reply);
1101 for (String likedPostId : sone.getLikedPostIds()) {
1102 storedSone.addLikedPostId(likedPostId);
1104 for (String likedReplyId : sone.getLikedReplyIds()) {
1105 storedSone.addLikedReplyId(likedReplyId);
1108 storedSone.setPosts(sone.getPosts());
1109 storedSone.setReplies(sone.getReplies());
1110 storedSone.setLikePostIds(sone.getLikedPostIds());
1111 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1113 storedSone.setLatestEdition(sone.getLatestEdition());
1119 * Deletes the given Sone. This will remove the Sone from the
1120 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1121 * and remove the context from its identity.
1124 * The Sone to delete
1126 public void deleteSone(Sone sone) {
1127 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1128 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1131 synchronized (localSones) {
1132 if (!localSones.containsKey(sone.getId())) {
1133 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1136 localSones.remove(sone.getId());
1137 soneInserters.remove(sone).stop();
1140 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1141 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1142 } catch (WebOfTrustException wote1) {
1143 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1146 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1147 } catch (ConfigurationException ce1) {
1148 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1153 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1154 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1157 * The Sone to mark as known
1159 public void markSoneKnown(Sone sone) {
1160 synchronized (newSones) {
1161 if (newSones.remove(sone.getId())) {
1162 knownSones.add(sone.getId());
1163 coreListenerManager.fireMarkSoneKnown(sone);
1164 saveConfiguration();
1170 * Loads and updates the given Sone from the configuration. If any error is
1171 * encountered, loading is aborted and the given Sone is not changed.
1174 * The Sone to load and update
1176 public void loadSone(Sone sone) {
1177 if (!isLocalSone(sone)) {
1178 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1182 /* initialize options. */
1183 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1186 String sonePrefix = "Sone/" + sone.getId();
1187 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1188 if (soneTime == null) {
1189 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1192 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1195 Profile profile = new Profile();
1196 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1197 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1198 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1199 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1200 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1201 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1203 /* load profile fields. */
1205 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1206 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1207 if (fieldName == null) {
1210 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1211 profile.addField(fieldName).setValue(fieldValue);
1215 Set<Post> posts = new HashSet<Post>();
1217 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1218 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1219 if (postId == null) {
1222 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1223 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1224 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1225 if ((postTime == 0) || (postText == null)) {
1226 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1229 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1230 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1231 post.setRecipient(getSone(postRecipientId));
1237 Set<Reply> replies = new HashSet<Reply>();
1239 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1240 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1241 if (replyId == null) {
1244 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1245 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1246 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1247 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1248 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1251 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1254 /* load post likes. */
1255 Set<String> likedPostIds = new HashSet<String>();
1257 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1258 if (likedPostId == null) {
1261 likedPostIds.add(likedPostId);
1264 /* load reply likes. */
1265 Set<String> likedReplyIds = new HashSet<String>();
1267 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1268 if (likedReplyId == null) {
1271 likedReplyIds.add(likedReplyId);
1275 Set<String> friends = new HashSet<String>();
1277 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1278 if (friendId == null) {
1281 friends.add(friendId);
1285 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1287 /* if we’re still here, Sone was loaded successfully. */
1288 synchronized (sone) {
1289 sone.setTime(soneTime);
1290 sone.setProfile(profile);
1291 sone.setPosts(posts);
1292 sone.setReplies(replies);
1293 sone.setLikePostIds(likedPostIds);
1294 sone.setLikeReplyIds(likedReplyIds);
1295 sone.setFriends(friends);
1296 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1298 synchronized (newSones) {
1299 for (String friend : friends) {
1300 knownSones.add(friend);
1303 synchronized (newPosts) {
1304 for (Post post : posts) {
1305 knownPosts.add(post.getId());
1308 synchronized (newReplies) {
1309 for (Reply reply : replies) {
1310 knownReplies.add(reply.getId());
1316 * Saves the given Sone. This will persist all local settings for the given
1317 * Sone, such as the friends list and similar, private options.
1322 public synchronized void saveSone(Sone sone) {
1323 if (!isLocalSone(sone)) {
1324 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1327 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1328 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1332 logger.log(Level.INFO, "Saving Sone: %s", sone);
1334 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1336 /* save Sone into configuration. */
1337 String sonePrefix = "Sone/" + sone.getId();
1338 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1339 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1342 Profile profile = sone.getProfile();
1343 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1344 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1345 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1346 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1347 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1348 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1350 /* save profile fields. */
1351 int fieldCounter = 0;
1352 for (Field profileField : profile.getFields()) {
1353 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1354 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1355 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1357 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1360 int postCounter = 0;
1361 for (Post post : sone.getPosts()) {
1362 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1363 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1364 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1365 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1366 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1368 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1371 int replyCounter = 0;
1372 for (Reply reply : sone.getReplies()) {
1373 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1374 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1375 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1376 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1377 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1379 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1381 /* save post likes. */
1382 int postLikeCounter = 0;
1383 for (String postId : sone.getLikedPostIds()) {
1384 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1386 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1388 /* save reply likes. */
1389 int replyLikeCounter = 0;
1390 for (String replyId : sone.getLikedReplyIds()) {
1391 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1393 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1396 int friendCounter = 0;
1397 for (String friendId : sone.getFriends()) {
1398 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1400 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1403 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1405 configuration.save();
1406 logger.log(Level.INFO, "Sone %s saved.", sone);
1407 } catch (ConfigurationException ce1) {
1408 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1409 } catch (WebOfTrustException wote1) {
1410 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1415 * Creates a new post.
1418 * The Sone that creates the post
1420 * The text of the post
1421 * @return The created post
1423 public Post createPost(Sone sone, String text) {
1424 return createPost(sone, System.currentTimeMillis(), text);
1428 * Creates a new post.
1431 * The Sone that creates the post
1433 * The time of the post
1435 * The text of the post
1436 * @return The created post
1438 public Post createPost(Sone sone, long time, String text) {
1439 return createPost(sone, null, time, text);
1443 * Creates a new post.
1446 * The Sone that creates the post
1448 * The recipient Sone, or {@code null} if this post does not have
1451 * The text of the post
1452 * @return The created post
1454 public Post createPost(Sone sone, Sone recipient, String text) {
1455 return createPost(sone, recipient, System.currentTimeMillis(), text);
1459 * Creates a new post.
1462 * The Sone that creates the post
1464 * The recipient Sone, or {@code null} if this post does not have
1467 * The time of the post
1469 * The text of the post
1470 * @return The created post
1472 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1473 if (!isLocalSone(sone)) {
1474 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1477 Post post = new Post(sone, time, text);
1478 if (recipient != null) {
1479 post.setRecipient(recipient);
1481 synchronized (posts) {
1482 posts.put(post.getId(), post);
1484 synchronized (newPosts) {
1485 newPosts.add(post.getId());
1486 coreListenerManager.fireNewPostFound(post);
1494 * Deletes the given post.
1497 * The post to delete
1499 public void deletePost(Post post) {
1500 if (!isLocalSone(post.getSone())) {
1501 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1504 post.getSone().removePost(post);
1505 synchronized (posts) {
1506 posts.remove(post.getId());
1508 coreListenerManager.firePostRemoved(post);
1509 synchronized (newPosts) {
1510 markPostKnown(post);
1511 knownPosts.remove(post.getId());
1513 saveSone(post.getSone());
1517 * Marks the given post as known, if it is currently a new post (according
1518 * to {@link #isNewPost(String)}).
1521 * The post to mark as known
1523 public void markPostKnown(Post post) {
1524 synchronized (newPosts) {
1525 if (newPosts.remove(post.getId())) {
1526 knownPosts.add(post.getId());
1527 coreListenerManager.fireMarkPostKnown(post);
1528 saveConfiguration();
1534 * Bookmarks the given post.
1537 * The post to bookmark
1539 public void bookmark(Post post) {
1540 bookmarkPost(post.getId());
1544 * Bookmarks the post with the given ID.
1547 * The ID of the post to bookmark
1549 public void bookmarkPost(String id) {
1550 synchronized (bookmarkedPosts) {
1551 bookmarkedPosts.add(id);
1556 * Removes the given post from the bookmarks.
1559 * The post to unbookmark
1561 public void unbookmark(Post post) {
1562 unbookmarkPost(post.getId());
1566 * Removes the post with the given ID from the bookmarks.
1569 * The ID of the post to unbookmark
1571 public void unbookmarkPost(String id) {
1572 synchronized (bookmarkedPosts) {
1573 bookmarkedPosts.remove(id);
1578 * Creates a new reply.
1581 * The Sone that creates the reply
1583 * The post that this reply refers to
1585 * The text of the reply
1586 * @return The created reply
1588 public Reply createReply(Sone sone, Post post, String text) {
1589 return createReply(sone, post, System.currentTimeMillis(), text);
1593 * Creates a new reply.
1596 * The Sone that creates the reply
1598 * The post that this reply refers to
1600 * The time of the reply
1602 * The text of the reply
1603 * @return The created reply
1605 public Reply createReply(Sone sone, Post post, long time, String text) {
1606 if (!isLocalSone(sone)) {
1607 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1610 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1611 synchronized (replies) {
1612 replies.put(reply.getId(), reply);
1614 synchronized (newReplies) {
1615 newReplies.add(reply.getId());
1616 coreListenerManager.fireNewReplyFound(reply);
1618 sone.addReply(reply);
1624 * Deletes the given reply.
1627 * The reply to delete
1629 public void deleteReply(Reply reply) {
1630 Sone sone = reply.getSone();
1631 if (!isLocalSone(sone)) {
1632 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1635 synchronized (replies) {
1636 replies.remove(reply.getId());
1638 synchronized (newReplies) {
1639 markReplyKnown(reply);
1640 knownReplies.remove(reply.getId());
1642 sone.removeReply(reply);
1647 * Marks the given reply as known, if it is currently a new reply (according
1648 * to {@link #isNewReply(String)}).
1651 * The reply to mark as known
1653 public void markReplyKnown(Reply reply) {
1654 synchronized (newReplies) {
1655 if (newReplies.remove(reply.getId())) {
1656 knownReplies.add(reply.getId());
1657 coreListenerManager.fireMarkReplyKnown(reply);
1658 saveConfiguration();
1666 public void start() {
1667 loadConfiguration();
1668 updateChecker.addUpdateListener(this);
1669 updateChecker.start();
1675 public void stop() {
1676 synchronized (localSones) {
1677 for (SoneInserter soneInserter : soneInserters.values()) {
1678 soneInserter.stop();
1681 updateChecker.stop();
1682 updateChecker.removeUpdateListener(this);
1683 soneDownloader.stop();
1684 saveConfiguration();
1689 * Saves the current options.
1691 public void saveConfiguration() {
1692 synchronized (configuration) {
1693 if (storingConfiguration) {
1694 logger.log(Level.FINE, "Already storing configuration…");
1697 storingConfiguration = true;
1700 /* store the options first. */
1702 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1703 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1704 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1705 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1706 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1707 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1708 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1709 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1710 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1711 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1713 /* save known Sones. */
1714 int soneCounter = 0;
1715 synchronized (newSones) {
1716 for (String knownSoneId : knownSones) {
1717 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1719 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1722 /* save known posts. */
1723 int postCounter = 0;
1724 synchronized (newPosts) {
1725 for (String knownPostId : knownPosts) {
1726 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1728 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1731 /* save known replies. */
1732 int replyCounter = 0;
1733 synchronized (newReplies) {
1734 for (String knownReplyId : knownReplies) {
1735 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1737 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1740 /* save bookmarked posts. */
1741 int bookmarkedPostCounter = 0;
1742 synchronized (bookmarkedPosts) {
1743 for (String bookmarkedPostId : bookmarkedPosts) {
1744 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1747 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1750 configuration.save();
1752 } catch (ConfigurationException ce1) {
1753 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1755 synchronized (configuration) {
1756 storingConfiguration = false;
1766 * Loads the configuration.
1768 @SuppressWarnings("unchecked")
1769 private void loadConfiguration() {
1770 /* create options. */
1771 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1774 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1775 SoneInserter.setInsertionDelay(newValue);
1779 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1780 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1781 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1782 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1783 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1784 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1785 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1786 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1788 /* read options from configuration. */
1789 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1790 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1791 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1792 options.getBooleanOption("ClearOnNextRestart").set(null);
1793 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1794 if (clearConfiguration) {
1795 /* stop loading the configuration. */
1799 loadConfigurationValue("InsertionDelay");
1800 loadConfigurationValue("PostsPerPage");
1801 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1802 loadConfigurationValue("PositiveTrust");
1803 loadConfigurationValue("NegativeTrust");
1804 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1805 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1807 /* load known Sones. */
1808 int soneCounter = 0;
1810 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1811 if (knownSoneId == null) {
1814 synchronized (newSones) {
1815 knownSones.add(knownSoneId);
1819 /* load known posts. */
1820 int postCounter = 0;
1822 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1823 if (knownPostId == null) {
1826 synchronized (newPosts) {
1827 knownPosts.add(knownPostId);
1831 /* load known replies. */
1832 int replyCounter = 0;
1834 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1835 if (knownReplyId == null) {
1838 synchronized (newReplies) {
1839 knownReplies.add(knownReplyId);
1843 /* load bookmarked posts. */
1844 int bookmarkedPostCounter = 0;
1846 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1847 if (bookmarkedPostId == null) {
1850 synchronized (bookmarkedPosts) {
1851 bookmarkedPosts.add(bookmarkedPostId);
1858 * Loads an {@link Integer} configuration value for the option with the
1859 * given name, logging validation failures.
1862 * The name of the option to load
1864 private void loadConfigurationValue(String optionName) {
1866 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1867 } catch (IllegalArgumentException iae1) {
1868 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1873 * Generate a Sone URI from the given URI and latest edition.
1876 * The URI to derive the Sone URI from
1877 * @return The derived URI
1879 private FreenetURI getSoneUri(String uriString) {
1881 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1883 } catch (MalformedURLException mue1) {
1884 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1890 // INTERFACE IdentityListener
1897 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1898 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1899 if (ownIdentity.hasContext("Sone")) {
1900 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1901 addLocalSone(ownIdentity);
1909 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1910 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1911 trustedIdentities.remove(ownIdentity);
1918 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1919 logger.log(Level.FINEST, "Adding Identity: " + identity);
1920 trustedIdentities.get(ownIdentity).add(identity);
1921 addRemoteSone(identity);
1928 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1929 new Thread(new Runnable() {
1932 @SuppressWarnings("synthetic-access")
1934 Sone sone = getRemoteSone(identity.getId());
1935 sone.setIdentity(identity);
1936 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1937 soneDownloader.addSone(sone);
1938 soneDownloader.fetchSone(sone);
1947 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1948 trustedIdentities.get(ownIdentity).remove(identity);
1949 boolean foundIdentity = false;
1950 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
1951 if (trustedIdentity.getKey().equals(ownIdentity)) {
1954 if (trustedIdentity.getValue().contains(identity)) {
1955 foundIdentity = true;
1958 if (foundIdentity) {
1959 /* some local identity still trusts this identity, don’t remove. */
1962 Sone sone = getSone(identity.getId(), false);
1964 /* TODO - we don’t have the Sone anymore. should this happen? */
1967 synchronized (posts) {
1968 synchronized (newPosts) {
1969 for (Post post : sone.getPosts()) {
1970 posts.remove(post.getId());
1971 newPosts.remove(post.getId());
1972 coreListenerManager.firePostRemoved(post);
1976 synchronized (replies) {
1977 synchronized (newReplies) {
1978 for (Reply reply : sone.getReplies()) {
1979 replies.remove(reply.getId());
1980 newReplies.remove(reply.getId());
1981 coreListenerManager.fireReplyRemoved(reply);
1985 synchronized (remoteSones) {
1986 remoteSones.remove(identity.getId());
1988 synchronized (newSones) {
1989 newSones.remove(identity.getId());
1994 // INTERFACE UpdateListener
2001 public void updateFound(Version version, long releaseTime, long latestEdition) {
2002 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2006 * Convenience interface for external classes that want to access the core’s
2009 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2011 public static class Preferences {
2013 /** The wrapped options. */
2014 private final Options options;
2017 * Creates a new preferences object wrapped around the given options.
2020 * The options to wrap
2022 public Preferences(Options options) {
2023 this.options = options;
2027 * Returns the insertion delay.
2029 * @return The insertion delay
2031 public int getInsertionDelay() {
2032 return options.getIntegerOption("InsertionDelay").get();
2036 * Validates the given insertion delay.
2038 * @param insertionDelay
2039 * The insertion delay to validate
2040 * @return {@code true} if the given insertion delay was valid, {@code
2043 public boolean validateInsertionDelay(Integer insertionDelay) {
2044 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2048 * Sets the insertion delay
2050 * @param insertionDelay
2051 * The new insertion delay, or {@code null} to restore it to
2053 * @return This preferences
2055 public Preferences setInsertionDelay(Integer insertionDelay) {
2056 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2061 * Returns the number of posts to show per page.
2063 * @return The number of posts to show per page
2065 public int getPostsPerPage() {
2066 return options.getIntegerOption("PostsPerPage").get();
2070 * Validates the number of posts per page.
2072 * @param postsPerPage
2073 * The number of posts per page
2074 * @return {@code true} if the number of posts per page was valid,
2075 * {@code false} otherwise
2077 public boolean validatePostsPerPage(Integer postsPerPage) {
2078 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2082 * Sets the number of posts to show per page.
2084 * @param postsPerPage
2085 * The number of posts to show per page
2086 * @return This preferences object
2088 public Preferences setPostsPerPage(Integer postsPerPage) {
2089 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2094 * Returns whether Sone requires full access to be even visible.
2096 * @return {@code true} if Sone requires full access, {@code false}
2099 public boolean isRequireFullAccess() {
2100 return options.getBooleanOption("RequireFullAccess").get();
2104 * Sets whether Sone requires full access to be even visible.
2106 * @param requireFullAccess
2107 * {@code true} if Sone requires full access, {@code false}
2110 public void setRequireFullAccess(Boolean requireFullAccess) {
2111 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2115 * Returns the positive trust.
2117 * @return The positive trust
2119 public int getPositiveTrust() {
2120 return options.getIntegerOption("PositiveTrust").get();
2124 * Validates the positive trust.
2126 * @param positiveTrust
2127 * The positive trust to validate
2128 * @return {@code true} if the positive trust was valid, {@code false}
2131 public boolean validatePositiveTrust(Integer positiveTrust) {
2132 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2136 * Sets the positive trust.
2138 * @param positiveTrust
2139 * The new positive trust, or {@code null} to restore it to
2141 * @return This preferences
2143 public Preferences setPositiveTrust(Integer positiveTrust) {
2144 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2149 * Returns the negative trust.
2151 * @return The negative trust
2153 public int getNegativeTrust() {
2154 return options.getIntegerOption("NegativeTrust").get();
2158 * Validates the negative trust.
2160 * @param negativeTrust
2161 * The negative trust to validate
2162 * @return {@code true} if the negative trust was valid, {@code false}
2165 public boolean validateNegativeTrust(Integer negativeTrust) {
2166 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2170 * Sets the negative trust.
2172 * @param negativeTrust
2173 * The negative trust, or {@code null} to restore it to the
2175 * @return The preferences
2177 public Preferences setNegativeTrust(Integer negativeTrust) {
2178 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2183 * Returns the trust comment. This is the comment that is set in the web
2184 * of trust when a trust value is assigned to an identity.
2186 * @return The trust comment
2188 public String getTrustComment() {
2189 return options.getStringOption("TrustComment").get();
2193 * Sets the trust comment.
2195 * @param trustComment
2196 * The trust comment, or {@code null} to restore it to the
2198 * @return This preferences
2200 public Preferences setTrustComment(String trustComment) {
2201 options.getStringOption("TrustComment").set(trustComment);
2206 * Returns whether the rescue mode is active.
2208 * @return {@code true} if the rescue mode is active, {@code false}
2211 public boolean isSoneRescueMode() {
2212 return options.getBooleanOption("SoneRescueMode").get();
2216 * Sets whether the rescue mode is active.
2218 * @param soneRescueMode
2219 * {@code true} if the rescue mode is active, {@code false}
2221 * @return This preferences
2223 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2224 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2229 * Returns whether Sone should clear its settings on the next restart.
2230 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2231 * to return {@code true} as well!
2233 * @return {@code true} if Sone should clear its settings on the next
2234 * restart, {@code false} otherwise
2236 public boolean isClearOnNextRestart() {
2237 return options.getBooleanOption("ClearOnNextRestart").get();
2241 * Sets whether Sone will clear its settings on the next restart.
2243 * @param clearOnNextRestart
2244 * {@code true} if Sone should clear its settings on the next
2245 * restart, {@code false} otherwise
2246 * @return This preferences
2248 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2249 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2254 * Returns whether Sone should really clear its settings on next
2255 * restart. This is a confirmation option that needs to be set in
2256 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2257 * settings on the next restart.
2259 * @return {@code true} if Sone should really clear its settings on the
2260 * next restart, {@code false} otherwise
2262 public boolean isReallyClearOnNextRestart() {
2263 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2267 * Sets whether Sone should really clear its settings on the next
2270 * @param reallyClearOnNextRestart
2271 * {@code true} if Sone should really clear its settings on
2272 * the next restart, {@code false} otherwise
2273 * @return This preferences
2275 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2276 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);