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 net.pterodactylus.util.validation.Validation;
51 import freenet.keys.FreenetURI;
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 public class Core implements IdentityListener {
61 * Enumeration for the possible states of a {@link Sone}.
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public enum SoneStatus {
67 /** The Sone is unknown, i.e. not yet downloaded. */
70 /** The Sone is idle, i.e. not being downloaded or inserted. */
73 /** The Sone is currently being inserted. */
76 /** The Sone is currently being downloaded. */
81 private static final Logger logger = Logging.getLogger(Core.class);
84 private final Options options = new Options();
86 /** The core listener manager. */
87 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
89 /** The configuration. */
90 private Configuration configuration;
92 /** Whether we’re currently saving the configuration. */
93 private boolean storingConfiguration = false;
95 /** The identity manager. */
96 private final IdentityManager identityManager;
98 /** Interface to freenet. */
99 private final FreenetInterface freenetInterface;
101 /** The Sone downloader. */
102 private final SoneDownloader soneDownloader;
104 /** Whether the core has been stopped. */
105 private volatile boolean stopped;
107 /** The Sones’ statuses. */
108 /* synchronize access on itself. */
109 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
111 /** Locked local Sones. */
112 /* synchronize on itself. */
113 private final Set<Sone> lockedSones = new HashSet<Sone>();
115 /** Sone inserters. */
116 /* synchronize access on this on localSones. */
117 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
119 /** All local Sones. */
120 /* synchronize access on this on itself. */
121 private Map<String, Sone> localSones = new HashMap<String, Sone>();
123 /** All remote Sones. */
124 /* synchronize access on this on itself. */
125 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
127 /** All new Sones. */
128 private Set<String> newSones = new HashSet<String>();
130 /** All known Sones. */
131 /* synchronize access on {@link #newSones}. */
132 private Set<String> knownSones = new HashSet<String>();
135 private Map<String, Post> posts = new HashMap<String, Post>();
137 /** All new posts. */
138 private Set<String> newPosts = new HashSet<String>();
140 /** All known posts. */
141 /* synchronize access on {@link #newPosts}. */
142 private Set<String> knownPosts = new HashSet<String>();
145 private Map<String, Reply> replies = new HashMap<String, Reply>();
147 /** All new replies. */
148 private Set<String> newReplies = new HashSet<String>();
150 /** All known replies. */
151 private Set<String> knownReplies = new HashSet<String>();
153 /** Trusted identities, sorted by own identities. */
154 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
157 * Creates a new core.
159 * @param configuration
160 * The configuration of the core
161 * @param freenetInterface
162 * The freenet interface
163 * @param identityManager
164 * The identity manager
166 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
167 this.configuration = configuration;
168 this.freenetInterface = freenetInterface;
169 this.identityManager = identityManager;
170 this.soneDownloader = new SoneDownloader(this, freenetInterface);
174 // LISTENER MANAGEMENT
178 * Adds a new core listener.
180 * @param coreListener
181 * The listener to add
183 public void addCoreListener(CoreListener coreListener) {
184 coreListenerManager.addListener(coreListener);
188 * Removes a core listener.
190 * @param coreListener
191 * The listener to remove
193 public void removeCoreListener(CoreListener coreListener) {
194 coreListenerManager.removeListener(coreListener);
202 * Sets the configuration to use. This will automatically save the current
203 * configuration to the given configuration.
205 * @param configuration
206 * The new configuration to use
208 public void setConfiguration(Configuration configuration) {
209 this.configuration = configuration;
214 * Returns the options used by the core.
216 * @return The options of the core
218 public Options getOptions() {
223 * Returns whether the “Sone rescue mode” is currently activated.
225 * @return {@code true} if the “Sone rescue mode” is currently activated,
226 * {@code false} if it is not
228 public boolean isSoneRescueMode() {
229 return options.getBooleanOption("SoneRescueMode").get();
233 * Returns the identity manager used by the core.
235 * @return The identity manager
237 public IdentityManager getIdentityManager() {
238 return identityManager;
242 * Returns the status of the given Sone.
245 * The Sone to get the status for
246 * @return The status of the Sone
248 public SoneStatus getSoneStatus(Sone sone) {
249 synchronized (soneStatuses) {
250 return soneStatuses.get(sone);
255 * Sets the status of the given Sone.
258 * The Sone to set the status of
262 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
263 synchronized (soneStatuses) {
264 soneStatuses.put(sone, soneStatus);
269 * Returns whether the given Sone is currently locked.
273 * @return {@code true} if the Sone is locked, {@code false} if it is not
275 public boolean isLocked(Sone sone) {
276 synchronized (lockedSones) {
277 return lockedSones.contains(sone);
282 * Returns all Sones, remote and local.
286 public Set<Sone> getSones() {
287 Set<Sone> allSones = new HashSet<Sone>();
288 allSones.addAll(getLocalSones());
289 allSones.addAll(getRemoteSones());
294 * Returns the Sone with the given ID, regardless whether it’s local or
298 * The ID of the Sone to get
299 * @return The Sone with the given ID, or {@code null} if there is no such
302 public Sone getSone(String id) {
303 return getSone(id, true);
307 * Returns the Sone with the given ID, regardless whether it’s local or
311 * The ID of the Sone to get
313 * {@code true} to create a new Sone if none exists,
314 * {@code false} to return {@code null} if a Sone with the given
316 * @return The Sone with the given ID, or {@code null} if there is no such
319 public Sone getSone(String id, boolean create) {
320 if (isLocalSone(id)) {
321 return getLocalSone(id);
323 return getRemoteSone(id, create);
327 * Checks whether the core knows a Sone with the given ID.
331 * @return {@code true} if there is a Sone with the given ID, {@code false}
334 public boolean hasSone(String id) {
335 return isLocalSone(id) || isRemoteSone(id);
339 * Returns whether the given Sone is a local Sone.
342 * The Sone to check for its locality
343 * @return {@code true} if the given Sone is local, {@code false} otherwise
345 public boolean isLocalSone(Sone sone) {
346 synchronized (localSones) {
347 return localSones.containsKey(sone.getId());
352 * Returns whether the given ID is the ID of a local Sone.
355 * The Sone ID to check for its locality
356 * @return {@code true} if the given ID is a local Sone, {@code false}
359 public boolean isLocalSone(String id) {
360 synchronized (localSones) {
361 return localSones.containsKey(id);
366 * Returns all local Sones.
368 * @return All local Sones
370 public Set<Sone> getLocalSones() {
371 synchronized (localSones) {
372 return new HashSet<Sone>(localSones.values());
377 * Returns the local Sone with the given ID.
380 * The ID of the Sone to get
381 * @return The Sone with the given ID
383 public Sone getLocalSone(String id) {
384 return getLocalSone(id, true);
388 * Returns the local Sone with the given ID, optionally creating a new Sone.
393 * {@code true} to create a new Sone if none exists,
394 * {@code false} to return null if none exists
395 * @return The Sone with the given ID, or {@code null}
397 public Sone getLocalSone(String id, boolean create) {
398 synchronized (localSones) {
399 Sone sone = localSones.get(id);
400 if ((sone == null) && create) {
402 localSones.put(id, sone);
409 * Returns all remote Sones.
411 * @return All remote Sones
413 public Set<Sone> getRemoteSones() {
414 synchronized (remoteSones) {
415 return new HashSet<Sone>(remoteSones.values());
420 * Returns the remote Sone with the given ID.
423 * The ID of the remote Sone to get
424 * @return The Sone with the given ID
426 public Sone getRemoteSone(String id) {
427 return getRemoteSone(id, true);
431 * Returns the remote Sone with the given ID.
434 * The ID of the remote Sone to get
436 * {@code true} to always create a Sone, {@code false} to return
437 * {@code null} if no Sone with the given ID exists
438 * @return The Sone with the given ID
440 public Sone getRemoteSone(String id, boolean create) {
441 synchronized (remoteSones) {
442 Sone sone = remoteSones.get(id);
443 if ((sone == null) && create) {
445 remoteSones.put(id, sone);
452 * Returns whether the given Sone is a remote Sone.
456 * @return {@code true} if the given Sone is a remote Sone, {@code false}
459 public boolean isRemoteSone(Sone sone) {
460 synchronized (remoteSones) {
461 return remoteSones.containsKey(sone.getId());
466 * Returns whether the Sone with the given ID is a remote Sone.
469 * The ID of the Sone to check
470 * @return {@code true} if the Sone with the given ID is a remote Sone,
471 * {@code false} otherwise
473 public boolean isRemoteSone(String id) {
474 synchronized (remoteSones) {
475 return remoteSones.containsKey(id);
480 * Returns whether the given Sone is a new Sone. After this check, the Sone
481 * is marked as known, i.e. a second call with the same parameters will
482 * always yield {@code false}.
485 * The sone to check for
486 * @return {@code true} if the given Sone is new, false otherwise
488 public boolean isNewSone(Sone sone) {
489 synchronized (newSones) {
490 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
491 knownSones.add(sone.getId());
493 coreListenerManager.fireMarkSoneKnown(sone);
500 * Returns whether the given Sone has been modified.
503 * The Sone to check for modifications
504 * @return {@code true} if a modification has been detected in the Sone,
505 * {@code false} otherwise
507 public boolean isModifiedSone(Sone sone) {
508 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
512 * Returns whether the target Sone is trusted by the origin Sone.
518 * @return {@code true} if the target Sone is trusted by the origin Sone
520 public boolean isSoneTrusted(Sone origin, Sone target) {
521 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
525 * Returns the post with the given ID.
528 * The ID of the post to get
529 * @return The post, or {@code null} if there is no such post
531 public Post getPost(String postId) {
532 return getPost(postId, true);
536 * Returns the post with the given ID, optionally creating a new post.
539 * The ID of the post to get
541 * {@code true} it create a new post if no post with the given ID
542 * exists, {@code false} to return {@code null}
543 * @return The post, or {@code null} if there is no such post
545 public Post getPost(String postId, boolean create) {
546 synchronized (posts) {
547 Post post = posts.get(postId);
548 if ((post == null) && create) {
549 post = new Post(postId);
550 posts.put(postId, post);
557 * Returns whether the given post ID is new. After this method returns it is
558 * marked a known post ID.
562 * @return {@code true} if the post is considered to be new, {@code false}
565 public boolean isNewPost(String postId) {
566 return isNewPost(postId, true);
570 * Returns whether the given post ID is new. If {@code markAsKnown} is
571 * {@code true} then after this method returns the post ID is marked a known
577 * {@code true} to mark the post ID as known, {@code false} to
578 * not to mark it as known
579 * @return {@code true} if the post is considered to be new, {@code false}
582 public boolean isNewPost(String postId, boolean markAsKnown) {
583 synchronized (newPosts) {
584 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
586 Post post = getPost(postId, false);
596 * Returns the reply with the given ID. If there is no reply with the given
597 * ID yet, a new one is created.
600 * The ID of the reply to get
603 public Reply getReply(String replyId) {
604 return getReply(replyId, true);
608 * Returns the reply with the given ID. If there is no reply with the given
609 * ID yet, a new one is created, unless {@code create} is false in which
610 * case {@code null} is returned.
613 * The ID of the reply to get
615 * {@code true} to always return a {@link Reply}, {@code false}
616 * to return {@code null} if no reply can be found
617 * @return The reply, or {@code null} if there is no such reply
619 public Reply getReply(String replyId, boolean create) {
620 synchronized (replies) {
621 Reply reply = replies.get(replyId);
622 if (create && (reply == null)) {
623 reply = new Reply(replyId);
624 replies.put(replyId, reply);
631 * Returns all replies for the given post, order ascending by time.
634 * The post to get all replies for
635 * @return All replies for the given post
637 public List<Reply> getReplies(Post post) {
638 Set<Sone> sones = getSones();
639 List<Reply> replies = new ArrayList<Reply>();
640 for (Sone sone : sones) {
641 for (Reply reply : sone.getReplies()) {
642 if (reply.getPost().equals(post)) {
647 Collections.sort(replies, Reply.TIME_COMPARATOR);
652 * Returns whether the reply with the given ID is new.
655 * The ID of the reply to check
656 * @return {@code true} if the reply is considered to be new, {@code false}
659 public boolean isNewReply(String replyId) {
660 return isNewReply(replyId, true);
664 * Returns whether the reply with the given ID is new.
667 * The ID of the reply to check
669 * {@code true} to mark the reply as known, {@code false} to not
670 * to mark it as known
671 * @return {@code true} if the reply is considered to be new, {@code false}
674 public boolean isNewReply(String replyId, boolean markAsKnown) {
675 synchronized (newReplies) {
676 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
678 Reply reply = getReply(replyId, false);
680 markReplyKnown(reply);
688 * Returns all Sones that have liked the given post.
691 * The post to get the liking Sones for
692 * @return The Sones that like the given post
694 public Set<Sone> getLikes(Post post) {
695 Set<Sone> sones = new HashSet<Sone>();
696 for (Sone sone : getSones()) {
697 if (sone.getLikedPostIds().contains(post.getId())) {
705 * Returns all Sones that have liked the given reply.
708 * The reply to get the liking Sones for
709 * @return The Sones that like the given reply
711 public Set<Sone> getLikes(Reply reply) {
712 Set<Sone> sones = new HashSet<Sone>();
713 for (Sone sone : getSones()) {
714 if (sone.getLikedReplyIds().contains(reply.getId())) {
726 * Locks the given Sone. A locked Sone will not be inserted by
727 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
733 public void lockSone(Sone sone) {
734 synchronized (lockedSones) {
735 if (lockedSones.add(sone)) {
736 coreListenerManager.fireSoneLocked(sone);
742 * Unlocks the given Sone.
744 * @see #lockSone(Sone)
748 public void unlockSone(Sone sone) {
749 synchronized (lockedSones) {
750 if (lockedSones.remove(sone)) {
751 coreListenerManager.fireSoneUnlocked(sone);
757 * Adds a local Sone from the given ID which has to be the ID of an own
761 * The ID of an own identity to add a Sone for
762 * @return The added (or already existing) Sone
764 public Sone addLocalSone(String id) {
765 synchronized (localSones) {
766 if (localSones.containsKey(id)) {
767 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
768 return localSones.get(id);
770 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
771 if (ownIdentity == null) {
772 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
775 return addLocalSone(ownIdentity);
780 * Adds a local Sone from the given own identity.
783 * The own identity to create a Sone from
784 * @return The added (or already existing) Sone
786 public Sone addLocalSone(OwnIdentity ownIdentity) {
787 if (ownIdentity == null) {
788 logger.log(Level.WARNING, "Given OwnIdentity is null!");
791 synchronized (localSones) {
794 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
795 } catch (MalformedURLException mue1) {
796 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
799 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
800 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
801 /* TODO - load posts ’n stuff */
802 localSones.put(ownIdentity.getId(), sone);
803 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
804 soneInserters.put(sone, soneInserter);
805 setSoneStatus(sone, SoneStatus.idle);
807 if (!isSoneRescueMode()) {
808 soneInserter.start();
810 new Thread(new Runnable() {
813 @SuppressWarnings("synthetic-access")
815 if (!isSoneRescueMode()) {
816 soneDownloader.fetchSone(sone);
819 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
820 coreListenerManager.fireRescuingSone(sone);
822 long edition = sone.getLatestEdition();
823 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
824 logger.log(Level.FINE, "Downloading edition " + edition + "…");
825 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
828 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
830 coreListenerManager.fireRescuedSone(sone);
831 soneInserter.start();
834 }, "Sone Downloader").start();
840 * Creates a new Sone for the given own identity.
843 * The own identity to create a Sone for
844 * @return The created Sone
846 public Sone createSone(OwnIdentity ownIdentity) {
848 ownIdentity.addContext("Sone");
849 } catch (WebOfTrustException wote1) {
850 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
853 Sone sone = addLocalSone(ownIdentity);
858 * Adds the Sone of the given identity.
861 * The identity whose Sone to add
862 * @return The added or already existing Sone
864 public Sone addRemoteSone(Identity identity) {
865 if (identity == null) {
866 logger.log(Level.WARNING, "Given Identity is null!");
869 synchronized (remoteSones) {
870 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
871 boolean newSone = sone.getRequestUri() == null;
872 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
873 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
875 synchronized (newSones) {
876 newSone = !knownSones.contains(sone.getId());
878 newSones.add(sone.getId());
882 coreListenerManager.fireNewSoneFound(sone);
885 remoteSones.put(identity.getId(), sone);
886 soneDownloader.addSone(sone);
887 setSoneStatus(sone, SoneStatus.unknown);
888 new Thread(new Runnable() {
891 @SuppressWarnings("synthetic-access")
893 soneDownloader.fetchSone(sone);
896 }, "Sone Downloader").start();
902 * Retrieves the trust relationship from the origin to the target.
905 * The origin of the trust tree
907 * The target of the trust
908 * @return The trust relationship
910 public Trust getTrust(Sone origin, Sone target) {
911 if (!isLocalSone(origin)) {
912 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
916 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
917 } catch (WebOfTrustException wote1) {
918 logger.log(Level.WARNING, "Could not get trust for Sone: " + target, wote1);
924 * Sets the trust value of the given origin Sone for the target Sone.
931 * The trust value (from {@code -100} to {@code 100})
933 public void setTrust(Sone origin, Sone target, int trustValue) {
934 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();
936 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, "Set from Sone Web Interface");
937 } catch (WebOfTrustException wote1) {
938 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
943 * Removes any trust assignment for the given target Sone.
950 public void removeTrust(Sone origin, Sone target) {
951 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
953 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
954 } catch (WebOfTrustException wote1) {
955 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
960 * Updates the stores Sone with the given Sone.
965 public void updateSone(Sone sone) {
966 if (hasSone(sone.getId())) {
967 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
968 Sone storedSone = getSone(sone.getId());
969 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
970 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
973 synchronized (posts) {
974 if (!soneRescueMode) {
975 for (Post post : storedSone.getPosts()) {
976 posts.remove(post.getId());
977 if (!sone.getPosts().contains(post)) {
978 coreListenerManager.firePostRemoved(post);
982 synchronized (newPosts) {
983 for (Post post : sone.getPosts()) {
984 post.setSone(getSone(post.getSone().getId()));
985 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
986 newPosts.add(post.getId());
987 coreListenerManager.fireNewPostFound(post);
989 posts.put(post.getId(), post);
993 synchronized (replies) {
994 if (!soneRescueMode) {
995 for (Reply reply : storedSone.getReplies()) {
996 replies.remove(reply.getId());
997 if (!sone.getReplies().contains(reply)) {
998 coreListenerManager.fireReplyRemoved(reply);
1002 synchronized (newReplies) {
1003 for (Reply reply : sone.getReplies()) {
1004 reply.setSone(getSone(reply.getSone().getId()));
1005 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
1006 newReplies.add(reply.getId());
1007 coreListenerManager.fireNewReplyFound(reply);
1009 replies.put(reply.getId(), reply);
1013 synchronized (storedSone) {
1014 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1015 storedSone.setTime(sone.getTime());
1017 storedSone.setClient(sone.getClient());
1018 storedSone.setProfile(sone.getProfile());
1019 if (soneRescueMode) {
1020 for (Post post : sone.getPosts()) {
1021 storedSone.addPost(post);
1023 for (Reply reply : sone.getReplies()) {
1024 storedSone.addReply(reply);
1026 for (String likedPostId : sone.getLikedPostIds()) {
1027 storedSone.addLikedPostId(likedPostId);
1029 for (String likedReplyId : sone.getLikedReplyIds()) {
1030 storedSone.addLikedReplyId(likedReplyId);
1033 storedSone.setPosts(sone.getPosts());
1034 storedSone.setReplies(sone.getReplies());
1035 storedSone.setLikePostIds(sone.getLikedPostIds());
1036 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1038 storedSone.setLatestEdition(sone.getLatestEdition());
1044 * Deletes the given Sone. This will remove the Sone from the
1045 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1046 * and remove the context from its identity.
1049 * The Sone to delete
1051 public void deleteSone(Sone sone) {
1052 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1053 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1056 synchronized (localSones) {
1057 if (!localSones.containsKey(sone.getId())) {
1058 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1061 localSones.remove(sone.getId());
1062 soneInserters.remove(sone).stop();
1065 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1066 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1067 } catch (WebOfTrustException wote1) {
1068 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1071 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1072 } catch (ConfigurationException ce1) {
1073 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1078 * Loads and updates the given Sone from the configuration. If any error is
1079 * encountered, loading is aborted and the given Sone is not changed.
1082 * The Sone to load and update
1084 public void loadSone(Sone sone) {
1085 if (!isLocalSone(sone)) {
1086 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1091 String sonePrefix = "Sone/" + sone.getId();
1092 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1093 if (soneTime == null) {
1094 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1097 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1100 Profile profile = new Profile();
1101 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1102 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1103 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1104 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1105 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1106 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1109 Set<Post> posts = new HashSet<Post>();
1111 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1112 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1113 if (postId == null) {
1116 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1117 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1118 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1119 if ((postTime == 0) || (postText == null)) {
1120 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1123 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1124 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1125 post.setRecipient(getSone(postRecipientId));
1131 Set<Reply> replies = new HashSet<Reply>();
1133 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1134 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1135 if (replyId == null) {
1138 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1139 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1140 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1141 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1142 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1145 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1148 /* load post likes. */
1149 Set<String> likedPostIds = new HashSet<String>();
1151 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1152 if (likedPostId == null) {
1155 likedPostIds.add(likedPostId);
1158 /* load reply likes. */
1159 Set<String> likedReplyIds = new HashSet<String>();
1161 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1162 if (likedReplyId == null) {
1165 likedReplyIds.add(likedReplyId);
1169 Set<String> friends = new HashSet<String>();
1171 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1172 if (friendId == null) {
1175 friends.add(friendId);
1178 /* if we’re still here, Sone was loaded successfully. */
1179 synchronized (sone) {
1180 sone.setTime(soneTime);
1181 sone.setProfile(profile);
1182 sone.setPosts(posts);
1183 sone.setReplies(replies);
1184 sone.setLikePostIds(likedPostIds);
1185 sone.setLikeReplyIds(likedReplyIds);
1186 sone.setFriends(friends);
1187 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1189 synchronized (newSones) {
1190 for (String friend : friends) {
1191 knownSones.add(friend);
1194 synchronized (newPosts) {
1195 for (Post post : posts) {
1196 knownPosts.add(post.getId());
1199 synchronized (newReplies) {
1200 for (Reply reply : replies) {
1201 knownReplies.add(reply.getId());
1207 * Saves the given Sone. This will persist all local settings for the given
1208 * Sone, such as the friends list and similar, private options.
1213 public synchronized void saveSone(Sone sone) {
1214 if (!isLocalSone(sone)) {
1215 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1218 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1219 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1223 logger.log(Level.INFO, "Saving Sone: %s", sone);
1225 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1227 /* save Sone into configuration. */
1228 String sonePrefix = "Sone/" + sone.getId();
1229 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1230 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1233 Profile profile = sone.getProfile();
1234 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1235 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1236 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1237 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1238 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1239 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1242 int postCounter = 0;
1243 for (Post post : sone.getPosts()) {
1244 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1245 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1246 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1247 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1248 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1250 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1253 int replyCounter = 0;
1254 for (Reply reply : sone.getReplies()) {
1255 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1256 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1257 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1258 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1259 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1261 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1263 /* save post likes. */
1264 int postLikeCounter = 0;
1265 for (String postId : sone.getLikedPostIds()) {
1266 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1268 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1270 /* save reply likes. */
1271 int replyLikeCounter = 0;
1272 for (String replyId : sone.getLikedReplyIds()) {
1273 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1275 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1278 int friendCounter = 0;
1279 for (String friendId : sone.getFriends()) {
1280 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1282 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1284 configuration.save();
1285 logger.log(Level.INFO, "Sone %s saved.", sone);
1286 } catch (ConfigurationException ce1) {
1287 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1288 } catch (WebOfTrustException wote1) {
1289 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1294 * Creates a new post.
1297 * The Sone that creates the post
1299 * The text of the post
1300 * @return The created post
1302 public Post createPost(Sone sone, String text) {
1303 return createPost(sone, System.currentTimeMillis(), text);
1307 * Creates a new post.
1310 * The Sone that creates the post
1312 * The time of the post
1314 * The text of the post
1315 * @return The created post
1317 public Post createPost(Sone sone, long time, String text) {
1318 return createPost(sone, null, time, text);
1322 * Creates a new post.
1325 * The Sone that creates the post
1327 * The recipient Sone, or {@code null} if this post does not have
1330 * The text of the post
1331 * @return The created post
1333 public Post createPost(Sone sone, Sone recipient, String text) {
1334 return createPost(sone, recipient, System.currentTimeMillis(), text);
1338 * Creates a new post.
1341 * The Sone that creates the post
1343 * The recipient Sone, or {@code null} if this post does not have
1346 * The time of the post
1348 * The text of the post
1349 * @return The created post
1351 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1352 if (!isLocalSone(sone)) {
1353 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1356 Post post = new Post(sone, time, text);
1357 if (recipient != null) {
1358 post.setRecipient(recipient);
1360 synchronized (posts) {
1361 posts.put(post.getId(), post);
1363 synchronized (newPosts) {
1364 knownPosts.add(post.getId());
1372 * Deletes the given post.
1375 * The post to delete
1377 public void deletePost(Post post) {
1378 if (!isLocalSone(post.getSone())) {
1379 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1382 post.getSone().removePost(post);
1383 synchronized (posts) {
1384 posts.remove(post.getId());
1386 saveSone(post.getSone());
1390 * Marks the given post as known, if it is currently a new post (according
1391 * to {@link #isNewPost(String)}).
1394 * The post to mark as known
1396 public void markPostKnown(Post post) {
1397 synchronized (newPosts) {
1398 if (newPosts.remove(post.getId())) {
1399 knownPosts.add(post.getId());
1400 coreListenerManager.fireMarkPostKnown(post);
1401 saveConfiguration();
1407 * Creates a new reply.
1410 * The Sone that creates the reply
1412 * The post that this reply refers to
1414 * The text of the reply
1415 * @return The created reply
1417 public Reply createReply(Sone sone, Post post, String text) {
1418 return createReply(sone, post, System.currentTimeMillis(), text);
1422 * Creates a new reply.
1425 * The Sone that creates the reply
1427 * The post that this reply refers to
1429 * The time of the reply
1431 * The text of the reply
1432 * @return The created reply
1434 public Reply createReply(Sone sone, Post post, long time, String text) {
1435 if (!isLocalSone(sone)) {
1436 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1439 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1440 synchronized (replies) {
1441 replies.put(reply.getId(), reply);
1443 synchronized (newReplies) {
1444 knownReplies.add(reply.getId());
1446 sone.addReply(reply);
1452 * Deletes the given reply.
1455 * The reply to delete
1457 public void deleteReply(Reply reply) {
1458 Sone sone = reply.getSone();
1459 if (!isLocalSone(sone)) {
1460 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1463 synchronized (replies) {
1464 replies.remove(reply.getId());
1466 sone.removeReply(reply);
1471 * Marks the given reply as known, if it is currently a new reply (according
1472 * to {@link #isNewReply(String)}).
1475 * The reply to mark as known
1477 public void markReplyKnown(Reply reply) {
1478 synchronized (newReplies) {
1479 if (newReplies.remove(reply.getId())) {
1480 knownReplies.add(reply.getId());
1481 coreListenerManager.fireMarkReplyKnown(reply);
1482 saveConfiguration();
1490 public void start() {
1491 loadConfiguration();
1497 public void stop() {
1498 synchronized (localSones) {
1499 for (SoneInserter soneInserter : soneInserters.values()) {
1500 soneInserter.stop();
1503 soneDownloader.stop();
1504 saveConfiguration();
1509 * Saves the current options.
1511 public void saveConfiguration() {
1512 synchronized (configuration) {
1513 if (storingConfiguration) {
1514 logger.log(Level.FINE, "Already storing configuration…");
1517 storingConfiguration = true;
1520 /* store the options first. */
1522 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1523 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1524 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1525 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1526 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1527 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1529 /* save known Sones. */
1530 int soneCounter = 0;
1531 synchronized (newSones) {
1532 for (String knownSoneId : knownSones) {
1533 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1535 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1538 /* save known posts. */
1539 int postCounter = 0;
1540 synchronized (newPosts) {
1541 for (String knownPostId : knownPosts) {
1542 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1544 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1547 /* save known replies. */
1548 int replyCounter = 0;
1549 synchronized (newReplies) {
1550 for (String knownReplyId : knownReplies) {
1551 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1553 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1557 configuration.save();
1559 } catch (ConfigurationException ce1) {
1560 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1562 synchronized (configuration) {
1563 storingConfiguration = false;
1573 * Loads the configuration.
1575 @SuppressWarnings("unchecked")
1576 private void loadConfiguration() {
1577 /* create options. */
1578 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1581 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1582 SoneInserter.setInsertionDelay(newValue);
1586 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1587 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
1588 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1589 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1590 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1592 /* read options from configuration. */
1593 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1594 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1595 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1596 options.getBooleanOption("ClearOnNextRestart").set(null);
1597 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1598 if (clearConfiguration) {
1599 /* stop loading the configuration. */
1603 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1604 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1605 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1606 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1608 /* load known Sones. */
1609 int soneCounter = 0;
1611 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1612 if (knownSoneId == null) {
1615 synchronized (newSones) {
1616 knownSones.add(knownSoneId);
1620 /* load known posts. */
1621 int postCounter = 0;
1623 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1624 if (knownPostId == null) {
1627 synchronized (newPosts) {
1628 knownPosts.add(knownPostId);
1632 /* load known replies. */
1633 int replyCounter = 0;
1635 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1636 if (knownReplyId == null) {
1639 synchronized (newReplies) {
1640 knownReplies.add(knownReplyId);
1647 * Generate a Sone URI from the given URI and latest edition.
1650 * The URI to derive the Sone URI from
1651 * @return The derived URI
1653 private FreenetURI getSoneUri(String uriString) {
1655 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1657 } catch (MalformedURLException mue1) {
1658 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1664 // INTERFACE IdentityListener
1671 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1672 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1673 if (ownIdentity.hasContext("Sone")) {
1674 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1675 addLocalSone(ownIdentity);
1683 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1684 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1685 trustedIdentities.remove(ownIdentity);
1692 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1693 logger.log(Level.FINEST, "Adding Identity: " + identity);
1694 trustedIdentities.get(ownIdentity).add(identity);
1695 addRemoteSone(identity);
1702 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1703 new Thread(new Runnable() {
1706 @SuppressWarnings("synthetic-access")
1708 Sone sone = getRemoteSone(identity.getId());
1709 soneDownloader.fetchSone(sone);
1718 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1719 trustedIdentities.get(ownIdentity).remove(identity);