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.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Client;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.freenet.wot.Identity;
40 import net.pterodactylus.sone.freenet.wot.IdentityListener;
41 import net.pterodactylus.sone.freenet.wot.IdentityManager;
42 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
43 import net.pterodactylus.sone.freenet.wot.Trust;
44 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
45 import net.pterodactylus.sone.main.SonePlugin;
46 import net.pterodactylus.util.config.Configuration;
47 import net.pterodactylus.util.config.ConfigurationException;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.number.Numbers;
50 import freenet.keys.FreenetURI;
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class Core implements IdentityListener {
60 * Enumeration for the possible states of a {@link Sone}.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public enum SoneStatus {
66 /** The Sone is unknown, i.e. not yet downloaded. */
69 /** The Sone is idle, i.e. not being downloaded or inserted. */
72 /** The Sone is currently being inserted. */
75 /** The Sone is currently being downloaded. */
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The core listener manager. */
86 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
88 /** The configuration. */
89 private Configuration configuration;
91 /** The identity manager. */
92 private final IdentityManager identityManager;
94 /** Interface to freenet. */
95 private final FreenetInterface freenetInterface;
97 /** The Sone downloader. */
98 private final SoneDownloader soneDownloader;
100 /** Whether the core has been stopped. */
101 private volatile boolean stopped;
103 /** The Sones’ statuses. */
104 /* synchronize access on itself. */
105 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
107 /** Locked local Sones. */
108 /* synchronize on itself. */
109 private final Set<Sone> lockedSones = new HashSet<Sone>();
111 /** Sone inserters. */
112 /* synchronize access on this on localSones. */
113 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
115 /** All local Sones. */
116 /* synchronize access on this on itself. */
117 private Map<String, Sone> localSones = new HashMap<String, Sone>();
119 /** All remote Sones. */
120 /* synchronize access on this on itself. */
121 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
123 /** All new Sones. */
124 private Set<String> newSones = new HashSet<String>();
126 /** All known Sones. */
127 /* synchronize access on {@link #newSones}. */
128 private Set<String> knownSones = new HashSet<String>();
131 private Map<String, Post> posts = new HashMap<String, Post>();
133 /** All new posts. */
134 private Set<String> newPosts = new HashSet<String>();
136 /** All known posts. */
137 /* synchronize access on {@link #newPosts}. */
138 private Set<String> knownPosts = new HashSet<String>();
141 private Map<String, Reply> replies = new HashMap<String, Reply>();
143 /** All new replies. */
144 private Set<String> newReplies = new HashSet<String>();
146 /** All known replies. */
147 private Set<String> knownReplies = new HashSet<String>();
149 /** Trusted identities, sorted by own identities. */
150 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
153 * Creates a new core.
155 * @param configuration
156 * The configuration of the core
157 * @param freenetInterface
158 * The freenet interface
159 * @param identityManager
160 * The identity manager
162 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
163 this.configuration = configuration;
164 this.freenetInterface = freenetInterface;
165 this.identityManager = identityManager;
166 this.soneDownloader = new SoneDownloader(this, freenetInterface);
170 // LISTENER MANAGEMENT
174 * Adds a new core listener.
176 * @param coreListener
177 * The listener to add
179 public void addCoreListener(CoreListener coreListener) {
180 coreListenerManager.addListener(coreListener);
184 * Removes a core listener.
186 * @param coreListener
187 * The listener to remove
189 public void removeCoreListener(CoreListener coreListener) {
190 coreListenerManager.removeListener(coreListener);
198 * Sets the configuration to use. This will automatically save the current
199 * configuration to the given configuration.
201 * @param configuration
202 * The new configuration to use
204 public void setConfiguration(Configuration configuration) {
205 this.configuration = configuration;
210 * Returns the options used by the core.
212 * @return The options of the core
214 public Options getOptions() {
219 * Returns whether the “Sone rescue mode” is currently activated.
221 * @return {@code true} if the “Sone rescue mode” is currently activated,
222 * {@code false} if it is not
224 public boolean isSoneRescueMode() {
225 return options.getBooleanOption("SoneRescueMode").get();
229 * Returns the identity manager used by the core.
231 * @return The identity manager
233 public IdentityManager getIdentityManager() {
234 return identityManager;
238 * Returns the status of the given Sone.
241 * The Sone to get the status for
242 * @return The status of the Sone
244 public SoneStatus getSoneStatus(Sone sone) {
245 synchronized (soneStatuses) {
246 return soneStatuses.get(sone);
251 * Sets the status of the given Sone.
254 * The Sone to set the status of
258 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
259 synchronized (soneStatuses) {
260 soneStatuses.put(sone, soneStatus);
265 * Returns whether the given Sone is currently locked.
269 * @return {@code true} if the Sone is locked, {@code false} if it is not
271 public boolean isLocked(Sone sone) {
272 synchronized (lockedSones) {
273 return lockedSones.contains(sone);
278 * Returns all Sones, remote and local.
282 public Set<Sone> getSones() {
283 Set<Sone> allSones = new HashSet<Sone>();
284 allSones.addAll(getLocalSones());
285 allSones.addAll(getRemoteSones());
290 * Returns the Sone with the given ID, regardless whether it’s local or
294 * The ID of the Sone to get
295 * @return The Sone with the given ID, or {@code null} if there is no such
298 public Sone getSone(String id) {
299 return getSone(id, true);
303 * Returns the Sone with the given ID, regardless whether it’s local or
307 * The ID of the Sone to get
309 * {@code true} to create a new Sone if none exists,
310 * {@code false} to return {@code null} if a Sone with the given
312 * @return The Sone with the given ID, or {@code null} if there is no such
315 public Sone getSone(String id, boolean create) {
316 if (isLocalSone(id)) {
317 return getLocalSone(id);
319 return getRemoteSone(id, create);
323 * Checks whether the core knows a Sone with the given ID.
327 * @return {@code true} if there is a Sone with the given ID, {@code false}
330 public boolean hasSone(String id) {
331 return isLocalSone(id) || isRemoteSone(id);
335 * Returns whether the given Sone is a local Sone.
338 * The Sone to check for its locality
339 * @return {@code true} if the given Sone is local, {@code false} otherwise
341 public boolean isLocalSone(Sone sone) {
342 synchronized (localSones) {
343 return localSones.containsKey(sone.getId());
348 * Returns whether the given ID is the ID of a local Sone.
351 * The Sone ID to check for its locality
352 * @return {@code true} if the given ID is a local Sone, {@code false}
355 public boolean isLocalSone(String id) {
356 synchronized (localSones) {
357 return localSones.containsKey(id);
362 * Returns all local Sones.
364 * @return All local Sones
366 public Set<Sone> getLocalSones() {
367 synchronized (localSones) {
368 return new HashSet<Sone>(localSones.values());
373 * Returns the local Sone with the given ID.
376 * The ID of the Sone to get
377 * @return The Sone with the given ID
379 public Sone getLocalSone(String id) {
380 return getLocalSone(id, true);
384 * Returns the local Sone with the given ID, optionally creating a new Sone.
389 * {@code true} to create a new Sone if none exists,
390 * {@code false} to return null if none exists
391 * @return The Sone with the given ID, or {@code null}
393 public Sone getLocalSone(String id, boolean create) {
394 synchronized (localSones) {
395 Sone sone = localSones.get(id);
396 if ((sone == null) && create) {
398 localSones.put(id, sone);
405 * Returns all remote Sones.
407 * @return All remote Sones
409 public Set<Sone> getRemoteSones() {
410 synchronized (remoteSones) {
411 return new HashSet<Sone>(remoteSones.values());
416 * Returns the remote Sone with the given ID.
419 * The ID of the remote Sone to get
420 * @return The Sone with the given ID
422 public Sone getRemoteSone(String id) {
423 return getRemoteSone(id, true);
427 * Returns the remote Sone with the given ID.
430 * The ID of the remote Sone to get
432 * {@code true} to always create a Sone, {@code false} to return
433 * {@code null} if no Sone with the given ID exists
434 * @return The Sone with the given ID
436 public Sone getRemoteSone(String id, boolean create) {
437 synchronized (remoteSones) {
438 Sone sone = remoteSones.get(id);
439 if ((sone == null) && create) {
441 remoteSones.put(id, sone);
448 * Returns whether the given Sone is a remote Sone.
452 * @return {@code true} if the given Sone is a remote Sone, {@code false}
455 public boolean isRemoteSone(Sone sone) {
456 synchronized (remoteSones) {
457 return remoteSones.containsKey(sone.getId());
462 * Returns whether the Sone with the given ID is a remote Sone.
465 * The ID of the Sone to check
466 * @return {@code true} if the Sone with the given ID is a remote Sone,
467 * {@code false} otherwise
469 public boolean isRemoteSone(String id) {
470 synchronized (remoteSones) {
471 return remoteSones.containsKey(id);
476 * Returns whether the given Sone is a new Sone. After this check, the Sone
477 * is marked as known, i.e. a second call with the same parameters will
478 * always yield {@code false}.
481 * The sone to check for
482 * @return {@code true} if the given Sone is new, false otherwise
484 public boolean isNewSone(Sone sone) {
485 synchronized (newSones) {
486 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
487 knownSones.add(sone.getId());
489 coreListenerManager.fireMarkSoneKnown(sone);
496 * Returns whether the given Sone has been modified.
499 * The Sone to check for modifications
500 * @return {@code true} if a modification has been detected in the Sone,
501 * {@code false} otherwise
503 public boolean isModifiedSone(Sone sone) {
504 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
508 * Returns whether the target Sone is trusted by the origin Sone.
514 * @return {@code true} if the target Sone is trusted by the origin Sone
516 public boolean isSoneTrusted(Sone origin, Sone target) {
517 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
521 * Returns the post with the given ID.
524 * The ID of the post to get
525 * @return The post, or {@code null} if there is no such post
527 public Post getPost(String postId) {
528 return getPost(postId, true);
532 * Returns the post with the given ID, optionally creating a new post.
535 * The ID of the post to get
537 * {@code true} it create a new post if no post with the given ID
538 * exists, {@code false} to return {@code null}
539 * @return The post, or {@code null} if there is no such post
541 public Post getPost(String postId, boolean create) {
542 synchronized (posts) {
543 Post post = posts.get(postId);
544 if ((post == null) && create) {
545 post = new Post(postId);
546 posts.put(postId, post);
553 * Returns whether the given post ID is new. After this method returns it is
554 * marked a known post ID.
558 * @return {@code true} if the post is considered to be new, {@code false}
561 public boolean isNewPost(String postId) {
562 return isNewPost(postId, true);
566 * Returns whether the given post ID is new. If {@code markAsKnown} is
567 * {@code true} then after this method returns the post ID is marked a known
573 * {@code true} to mark the post ID as known, {@code false} to
574 * not to mark it as known
575 * @return {@code true} if the post is considered to be new, {@code false}
578 public boolean isNewPost(String postId, boolean markAsKnown) {
579 synchronized (newPosts) {
580 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
582 Post post = getPost(postId, false);
592 * Returns the reply with the given ID. If there is no reply with the given
593 * ID yet, a new one is created.
596 * The ID of the reply to get
599 public Reply getReply(String replyId) {
600 return getReply(replyId, true);
604 * Returns the reply with the given ID. If there is no reply with the given
605 * ID yet, a new one is created, unless {@code create} is false in which
606 * case {@code null} is returned.
609 * The ID of the reply to get
611 * {@code true} to always return a {@link Reply}, {@code false}
612 * to return {@code null} if no reply can be found
613 * @return The reply, or {@code null} if there is no such reply
615 public Reply getReply(String replyId, boolean create) {
616 synchronized (replies) {
617 Reply reply = replies.get(replyId);
618 if (create && (reply == null)) {
619 reply = new Reply(replyId);
620 replies.put(replyId, reply);
627 * Returns all replies for the given post, order ascending by time.
630 * The post to get all replies for
631 * @return All replies for the given post
633 public List<Reply> getReplies(Post post) {
634 Set<Sone> sones = getSones();
635 List<Reply> replies = new ArrayList<Reply>();
636 for (Sone sone : sones) {
637 for (Reply reply : sone.getReplies()) {
638 if (reply.getPost().equals(post)) {
643 Collections.sort(replies, Reply.TIME_COMPARATOR);
648 * Returns whether the reply with the given ID is new.
651 * The ID of the reply to check
652 * @return {@code true} if the reply is considered to be new, {@code false}
655 public boolean isNewReply(String replyId) {
656 return isNewReply(replyId, true);
660 * Returns whether the reply with the given ID is new.
663 * The ID of the reply to check
665 * {@code true} to mark the reply as known, {@code false} to not
666 * to mark it as known
667 * @return {@code true} if the reply is considered to be new, {@code false}
670 public boolean isNewReply(String replyId, boolean markAsKnown) {
671 synchronized (newReplies) {
672 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
674 Reply reply = getReply(replyId, false);
676 markReplyKnown(reply);
684 * Returns all Sones that have liked the given post.
687 * The post to get the liking Sones for
688 * @return The Sones that like the given post
690 public Set<Sone> getLikes(Post post) {
691 Set<Sone> sones = new HashSet<Sone>();
692 for (Sone sone : getSones()) {
693 if (sone.getLikedPostIds().contains(post.getId())) {
701 * Returns all Sones that have liked the given reply.
704 * The reply to get the liking Sones for
705 * @return The Sones that like the given reply
707 public Set<Sone> getLikes(Reply reply) {
708 Set<Sone> sones = new HashSet<Sone>();
709 for (Sone sone : getSones()) {
710 if (sone.getLikedReplyIds().contains(reply.getId())) {
722 * Locks the given Sone. A locked Sone will not be inserted by
723 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
729 public void lockSone(Sone sone) {
730 synchronized (lockedSones) {
731 if (lockedSones.add(sone)) {
732 coreListenerManager.fireSoneLocked(sone);
738 * Unlocks the given Sone.
740 * @see #lockSone(Sone)
744 public void unlockSone(Sone sone) {
745 synchronized (lockedSones) {
746 if (lockedSones.remove(sone)) {
747 coreListenerManager.fireSoneUnlocked(sone);
753 * Adds a local Sone from the given ID which has to be the ID of an own
757 * The ID of an own identity to add a Sone for
758 * @return The added (or already existing) Sone
760 public Sone addLocalSone(String id) {
761 synchronized (localSones) {
762 if (localSones.containsKey(id)) {
763 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
764 return localSones.get(id);
766 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
767 if (ownIdentity == null) {
768 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
771 return addLocalSone(ownIdentity);
776 * Adds a local Sone from the given own identity.
779 * The own identity to create a Sone from
780 * @return The added (or already existing) Sone
782 public Sone addLocalSone(OwnIdentity ownIdentity) {
783 if (ownIdentity == null) {
784 logger.log(Level.WARNING, "Given OwnIdentity is null!");
787 synchronized (localSones) {
790 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
791 } catch (MalformedURLException mue1) {
792 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
795 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
796 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
797 /* TODO - load posts ’n stuff */
798 localSones.put(ownIdentity.getId(), sone);
799 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
800 soneInserters.put(sone, soneInserter);
801 setSoneStatus(sone, SoneStatus.idle);
803 if (!isSoneRescueMode()) {
804 soneInserter.start();
806 new Thread(new Runnable() {
809 @SuppressWarnings("synthetic-access")
811 if (!isSoneRescueMode()) {
812 soneDownloader.fetchSone(sone);
815 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
816 coreListenerManager.fireRescuingSone(sone);
818 long edition = sone.getLatestEdition();
819 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
820 logger.log(Level.FINE, "Downloading edition " + edition + "…");
821 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
824 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
826 coreListenerManager.fireRescuedSone(sone);
827 soneInserter.start();
830 }, "Sone Downloader").start();
836 * Creates a new Sone for the given own identity.
839 * The own identity to create a Sone for
840 * @return The created Sone
842 public Sone createSone(OwnIdentity ownIdentity) {
844 ownIdentity.addContext("Sone");
845 } catch (WebOfTrustException wote1) {
846 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
849 Sone sone = addLocalSone(ownIdentity);
854 * Adds the Sone of the given identity.
857 * The identity whose Sone to add
858 * @return The added or already existing Sone
860 public Sone addRemoteSone(Identity identity) {
861 if (identity == null) {
862 logger.log(Level.WARNING, "Given Identity is null!");
865 synchronized (remoteSones) {
866 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
867 boolean newSone = sone.getRequestUri() == null;
868 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
869 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
871 synchronized (newSones) {
872 newSone = !knownSones.contains(sone.getId());
874 newSones.add(sone.getId());
878 coreListenerManager.fireNewSoneFound(sone);
881 remoteSones.put(identity.getId(), sone);
882 soneDownloader.addSone(sone);
883 setSoneStatus(sone, SoneStatus.unknown);
884 new Thread(new Runnable() {
887 @SuppressWarnings("synthetic-access")
889 soneDownloader.fetchSone(sone);
892 }, "Sone Downloader").start();
898 * Retrieves the trust relationship from the origin to the target.
901 * The origin of the trust tree
903 * The target of the trust
904 * @return The trust relationship
906 public Trust getTrust(Sone origin, Sone target) {
907 if (!isLocalSone(origin)) {
908 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
912 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
913 } catch (WebOfTrustException wote1) {
914 logger.log(Level.WARNING, "Could not get trust for Sone: " + target, wote1);
920 * Updates the stores Sone with the given Sone.
925 public void updateSone(Sone sone) {
926 if (hasSone(sone.getId())) {
927 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
928 Sone storedSone = getSone(sone.getId());
929 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
930 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
933 synchronized (posts) {
934 if (!soneRescueMode) {
935 for (Post post : storedSone.getPosts()) {
936 posts.remove(post.getId());
937 if (!sone.getPosts().contains(post)) {
938 coreListenerManager.firePostRemoved(post);
942 synchronized (newPosts) {
943 for (Post post : sone.getPosts()) {
944 post.setSone(getSone(post.getSone().getId()));
945 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
946 newPosts.add(post.getId());
947 coreListenerManager.fireNewPostFound(post);
949 posts.put(post.getId(), post);
953 synchronized (replies) {
954 if (!soneRescueMode) {
955 for (Reply reply : storedSone.getReplies()) {
956 replies.remove(reply.getId());
957 if (!sone.getReplies().contains(reply)) {
958 coreListenerManager.fireReplyRemoved(reply);
962 synchronized (newReplies) {
963 for (Reply reply : sone.getReplies()) {
964 reply.setSone(getSone(reply.getSone().getId()));
965 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
966 newReplies.add(reply.getId());
967 coreListenerManager.fireNewReplyFound(reply);
969 replies.put(reply.getId(), reply);
973 synchronized (storedSone) {
974 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
975 storedSone.setTime(sone.getTime());
977 storedSone.setClient(sone.getClient());
978 storedSone.setProfile(sone.getProfile());
979 if (soneRescueMode) {
980 for (Post post : sone.getPosts()) {
981 storedSone.addPost(post);
983 for (Reply reply : sone.getReplies()) {
984 storedSone.addReply(reply);
986 for (String likedPostId : sone.getLikedPostIds()) {
987 storedSone.addLikedPostId(likedPostId);
989 for (String likedReplyId : sone.getLikedReplyIds()) {
990 storedSone.addLikedReplyId(likedReplyId);
993 storedSone.setPosts(sone.getPosts());
994 storedSone.setReplies(sone.getReplies());
995 storedSone.setLikePostIds(sone.getLikedPostIds());
996 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
998 storedSone.setLatestEdition(sone.getLatestEdition());
1004 * Deletes the given Sone. This will remove the Sone from the
1005 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1006 * and remove the context from its identity.
1009 * The Sone to delete
1011 public void deleteSone(Sone sone) {
1012 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1013 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1016 synchronized (localSones) {
1017 if (!localSones.containsKey(sone.getId())) {
1018 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1021 localSones.remove(sone.getId());
1022 soneInserters.remove(sone).stop();
1025 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1026 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1027 } catch (WebOfTrustException wote1) {
1028 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1031 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1032 } catch (ConfigurationException ce1) {
1033 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1038 * Loads and updates the given Sone from the configuration. If any error is
1039 * encountered, loading is aborted and the given Sone is not changed.
1042 * The Sone to load and update
1044 public void loadSone(Sone sone) {
1045 if (!isLocalSone(sone)) {
1046 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1051 String sonePrefix = "Sone/" + sone.getId();
1052 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1053 if (soneTime == null) {
1054 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1057 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1060 Profile profile = new Profile();
1061 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1062 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1063 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1064 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1065 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1066 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1069 Set<Post> posts = new HashSet<Post>();
1071 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1072 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1073 if (postId == null) {
1076 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1077 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1078 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1079 if ((postTime == 0) || (postText == null)) {
1080 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1083 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1084 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1085 post.setRecipient(getSone(postRecipientId));
1091 Set<Reply> replies = new HashSet<Reply>();
1093 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1094 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1095 if (replyId == null) {
1098 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1099 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1100 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1101 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1102 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1105 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1108 /* load post likes. */
1109 Set<String> likedPostIds = new HashSet<String>();
1111 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1112 if (likedPostId == null) {
1115 likedPostIds.add(likedPostId);
1118 /* load reply likes. */
1119 Set<String> likedReplyIds = new HashSet<String>();
1121 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1122 if (likedReplyId == null) {
1125 likedReplyIds.add(likedReplyId);
1129 Set<String> friends = new HashSet<String>();
1131 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1132 if (friendId == null) {
1135 friends.add(friendId);
1138 /* if we’re still here, Sone was loaded successfully. */
1139 synchronized (sone) {
1140 sone.setTime(soneTime);
1141 sone.setProfile(profile);
1142 sone.setPosts(posts);
1143 sone.setReplies(replies);
1144 sone.setLikePostIds(likedPostIds);
1145 sone.setLikeReplyIds(likedReplyIds);
1146 sone.setFriends(friends);
1147 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1149 synchronized (newSones) {
1150 for (String friend : friends) {
1151 knownSones.add(friend);
1154 synchronized (newPosts) {
1155 for (Post post : posts) {
1156 knownPosts.add(post.getId());
1159 synchronized (newReplies) {
1160 for (Reply reply : replies) {
1161 knownReplies.add(reply.getId());
1167 * Saves the given Sone. This will persist all local settings for the given
1168 * Sone, such as the friends list and similar, private options.
1173 public synchronized void saveSone(Sone sone) {
1174 if (!isLocalSone(sone)) {
1175 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1178 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1179 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1183 logger.log(Level.INFO, "Saving Sone: %s", sone);
1185 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1187 /* save Sone into configuration. */
1188 String sonePrefix = "Sone/" + sone.getId();
1189 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1190 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1193 Profile profile = sone.getProfile();
1194 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1195 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1196 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1197 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1198 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1199 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1202 int postCounter = 0;
1203 for (Post post : sone.getPosts()) {
1204 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1205 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1206 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1207 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1208 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1210 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1213 int replyCounter = 0;
1214 for (Reply reply : sone.getReplies()) {
1215 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1216 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1217 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1218 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1219 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1221 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1223 /* save post likes. */
1224 int postLikeCounter = 0;
1225 for (String postId : sone.getLikedPostIds()) {
1226 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1228 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1230 /* save reply likes. */
1231 int replyLikeCounter = 0;
1232 for (String replyId : sone.getLikedReplyIds()) {
1233 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1235 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1238 int friendCounter = 0;
1239 for (String friendId : sone.getFriends()) {
1240 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1242 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1244 configuration.save();
1245 logger.log(Level.INFO, "Sone %s saved.", sone);
1246 } catch (ConfigurationException ce1) {
1247 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1248 } catch (WebOfTrustException wote1) {
1249 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1254 * Creates a new post.
1257 * The Sone that creates the post
1259 * The text of the post
1260 * @return The created post
1262 public Post createPost(Sone sone, String text) {
1263 return createPost(sone, System.currentTimeMillis(), text);
1267 * Creates a new post.
1270 * The Sone that creates the post
1272 * The time of the post
1274 * The text of the post
1275 * @return The created post
1277 public Post createPost(Sone sone, long time, String text) {
1278 return createPost(sone, null, time, text);
1282 * Creates a new post.
1285 * The Sone that creates the post
1287 * The recipient Sone, or {@code null} if this post does not have
1290 * The text of the post
1291 * @return The created post
1293 public Post createPost(Sone sone, Sone recipient, String text) {
1294 return createPost(sone, recipient, System.currentTimeMillis(), text);
1298 * Creates a new post.
1301 * The Sone that creates the post
1303 * The recipient Sone, or {@code null} if this post does not have
1306 * The time of the post
1308 * The text of the post
1309 * @return The created post
1311 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1312 if (!isLocalSone(sone)) {
1313 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1316 Post post = new Post(sone, time, text);
1317 if (recipient != null) {
1318 post.setRecipient(recipient);
1320 synchronized (posts) {
1321 posts.put(post.getId(), post);
1323 synchronized (newPosts) {
1324 knownPosts.add(post.getId());
1332 * Deletes the given post.
1335 * The post to delete
1337 public void deletePost(Post post) {
1338 if (!isLocalSone(post.getSone())) {
1339 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1342 post.getSone().removePost(post);
1343 synchronized (posts) {
1344 posts.remove(post.getId());
1346 saveSone(post.getSone());
1350 * Marks the given post as known, if it is currently a new post (according
1351 * to {@link #isNewPost(String)}).
1354 * The post to mark as known
1356 public void markPostKnown(Post post) {
1357 synchronized (newPosts) {
1358 if (newPosts.remove(post.getId())) {
1359 knownPosts.add(post.getId());
1360 coreListenerManager.fireMarkPostKnown(post);
1361 saveConfiguration();
1367 * Creates a new reply.
1370 * The Sone that creates the reply
1372 * The post that this reply refers to
1374 * The text of the reply
1375 * @return The created reply
1377 public Reply createReply(Sone sone, Post post, String text) {
1378 return createReply(sone, post, System.currentTimeMillis(), text);
1382 * Creates a new reply.
1385 * The Sone that creates the reply
1387 * The post that this reply refers to
1389 * The time of the reply
1391 * The text of the reply
1392 * @return The created reply
1394 public Reply createReply(Sone sone, Post post, long time, String text) {
1395 if (!isLocalSone(sone)) {
1396 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1399 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1400 synchronized (replies) {
1401 replies.put(reply.getId(), reply);
1403 synchronized (newReplies) {
1404 knownReplies.add(reply.getId());
1406 sone.addReply(reply);
1412 * Deletes the given reply.
1415 * The reply to delete
1417 public void deleteReply(Reply reply) {
1418 Sone sone = reply.getSone();
1419 if (!isLocalSone(sone)) {
1420 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1423 synchronized (replies) {
1424 replies.remove(reply.getId());
1426 sone.removeReply(reply);
1431 * Marks the given reply as known, if it is currently a new reply (according
1432 * to {@link #isNewReply(String)}).
1435 * The reply to mark as known
1437 public void markReplyKnown(Reply reply) {
1438 synchronized (newReplies) {
1439 if (newReplies.remove(reply.getId())) {
1440 knownReplies.add(reply.getId());
1441 coreListenerManager.fireMarkReplyKnown(reply);
1442 saveConfiguration();
1450 public void start() {
1451 loadConfiguration();
1457 public void stop() {
1458 synchronized (localSones) {
1459 for (SoneInserter soneInserter : soneInserters.values()) {
1460 soneInserter.stop();
1463 soneDownloader.stop();
1464 saveConfiguration();
1469 * Saves the current options.
1471 public synchronized void saveConfiguration() {
1472 /* store the options first. */
1474 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1475 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1476 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1477 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1479 /* save known Sones. */
1480 int soneCounter = 0;
1481 synchronized (newSones) {
1482 for (String knownSoneId : knownSones) {
1483 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1485 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1488 /* save known posts. */
1489 int postCounter = 0;
1490 synchronized (newPosts) {
1491 for (String knownPostId : knownPosts) {
1492 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1494 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1497 /* save known replies. */
1498 int replyCounter = 0;
1499 synchronized (newReplies) {
1500 for (String knownReplyId : knownReplies) {
1501 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1503 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1507 configuration.save();
1509 } catch (ConfigurationException ce1) {
1510 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1519 * Loads the configuration.
1521 @SuppressWarnings("unchecked")
1522 private void loadConfiguration() {
1523 /* create options. */
1524 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1527 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1528 SoneInserter.setInsertionDelay(newValue);
1532 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1533 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1534 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1536 /* read options from configuration. */
1537 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1538 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1539 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1540 options.getBooleanOption("ClearOnNextRestart").set(null);
1541 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1542 if (clearConfiguration) {
1543 /* stop loading the configuration. */
1547 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1548 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1550 /* load known Sones. */
1551 int soneCounter = 0;
1553 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1554 if (knownSoneId == null) {
1557 synchronized (newSones) {
1558 knownSones.add(knownSoneId);
1562 /* load known posts. */
1563 int postCounter = 0;
1565 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1566 if (knownPostId == null) {
1569 synchronized (newPosts) {
1570 knownPosts.add(knownPostId);
1574 /* load known replies. */
1575 int replyCounter = 0;
1577 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1578 if (knownReplyId == null) {
1581 synchronized (newReplies) {
1582 knownReplies.add(knownReplyId);
1589 * Generate a Sone URI from the given URI and latest edition.
1592 * The URI to derive the Sone URI from
1593 * @return The derived URI
1595 private FreenetURI getSoneUri(String uriString) {
1597 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1599 } catch (MalformedURLException mue1) {
1600 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1606 // INTERFACE IdentityListener
1613 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1614 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1615 if (ownIdentity.hasContext("Sone")) {
1616 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1617 addLocalSone(ownIdentity);
1625 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1626 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1627 trustedIdentities.remove(ownIdentity);
1634 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1635 logger.log(Level.FINEST, "Adding Identity: " + identity);
1636 trustedIdentities.get(ownIdentity).add(identity);
1637 addRemoteSone(identity);
1644 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1645 new Thread(new Runnable() {
1648 @SuppressWarnings("synthetic-access")
1650 Sone sone = getRemoteSone(identity.getId());
1651 soneDownloader.fetchSone(sone);
1660 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1661 trustedIdentities.get(ownIdentity).remove(identity);