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 /** Whether we’re currently saving the configuration. */
92 private boolean storingConfiguration = false;
94 /** The identity manager. */
95 private final IdentityManager identityManager;
97 /** Interface to freenet. */
98 private final FreenetInterface freenetInterface;
100 /** The Sone downloader. */
101 private final SoneDownloader soneDownloader;
103 /** Whether the core has been stopped. */
104 private volatile boolean stopped;
106 /** The Sones’ statuses. */
107 /* synchronize access on itself. */
108 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
110 /** Locked local Sones. */
111 /* synchronize on itself. */
112 private final Set<Sone> lockedSones = new HashSet<Sone>();
114 /** Sone inserters. */
115 /* synchronize access on this on localSones. */
116 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
118 /** All local Sones. */
119 /* synchronize access on this on itself. */
120 private Map<String, Sone> localSones = new HashMap<String, Sone>();
122 /** All remote Sones. */
123 /* synchronize access on this on itself. */
124 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
126 /** All new Sones. */
127 private Set<String> newSones = new HashSet<String>();
129 /** All known Sones. */
130 /* synchronize access on {@link #newSones}. */
131 private Set<String> knownSones = new HashSet<String>();
134 private Map<String, Post> posts = new HashMap<String, Post>();
136 /** All new posts. */
137 private Set<String> newPosts = new HashSet<String>();
139 /** All known posts. */
140 /* synchronize access on {@link #newPosts}. */
141 private Set<String> knownPosts = new HashSet<String>();
144 private Map<String, Reply> replies = new HashMap<String, Reply>();
146 /** All new replies. */
147 private Set<String> newReplies = new HashSet<String>();
149 /** All known replies. */
150 private Set<String> knownReplies = new HashSet<String>();
152 /** Trusted identities, sorted by own identities. */
153 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
156 * Creates a new core.
158 * @param configuration
159 * The configuration of the core
160 * @param freenetInterface
161 * The freenet interface
162 * @param identityManager
163 * The identity manager
165 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
166 this.configuration = configuration;
167 this.freenetInterface = freenetInterface;
168 this.identityManager = identityManager;
169 this.soneDownloader = new SoneDownloader(this, freenetInterface);
173 // LISTENER MANAGEMENT
177 * Adds a new core listener.
179 * @param coreListener
180 * The listener to add
182 public void addCoreListener(CoreListener coreListener) {
183 coreListenerManager.addListener(coreListener);
187 * Removes a core listener.
189 * @param coreListener
190 * The listener to remove
192 public void removeCoreListener(CoreListener coreListener) {
193 coreListenerManager.removeListener(coreListener);
201 * Sets the configuration to use. This will automatically save the current
202 * configuration to the given configuration.
204 * @param configuration
205 * The new configuration to use
207 public void setConfiguration(Configuration configuration) {
208 this.configuration = configuration;
213 * Returns the options used by the core.
215 * @return The options of the core
217 public Options getOptions() {
222 * Returns whether the “Sone rescue mode” is currently activated.
224 * @return {@code true} if the “Sone rescue mode” is currently activated,
225 * {@code false} if it is not
227 public boolean isSoneRescueMode() {
228 return options.getBooleanOption("SoneRescueMode").get();
232 * Returns the identity manager used by the core.
234 * @return The identity manager
236 public IdentityManager getIdentityManager() {
237 return identityManager;
241 * Returns the status of the given Sone.
244 * The Sone to get the status for
245 * @return The status of the Sone
247 public SoneStatus getSoneStatus(Sone sone) {
248 synchronized (soneStatuses) {
249 return soneStatuses.get(sone);
254 * Sets the status of the given Sone.
257 * The Sone to set the status of
261 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
262 synchronized (soneStatuses) {
263 soneStatuses.put(sone, soneStatus);
268 * Returns whether the given Sone is currently locked.
272 * @return {@code true} if the Sone is locked, {@code false} if it is not
274 public boolean isLocked(Sone sone) {
275 synchronized (lockedSones) {
276 return lockedSones.contains(sone);
281 * Returns all Sones, remote and local.
285 public Set<Sone> getSones() {
286 Set<Sone> allSones = new HashSet<Sone>();
287 allSones.addAll(getLocalSones());
288 allSones.addAll(getRemoteSones());
293 * Returns the Sone with the given ID, regardless whether it’s local or
297 * The ID of the Sone to get
298 * @return The Sone with the given ID, or {@code null} if there is no such
301 public Sone getSone(String id) {
302 return getSone(id, true);
306 * Returns the Sone with the given ID, regardless whether it’s local or
310 * The ID of the Sone to get
312 * {@code true} to create a new Sone if none exists,
313 * {@code false} to return {@code null} if a Sone with the given
315 * @return The Sone with the given ID, or {@code null} if there is no such
318 public Sone getSone(String id, boolean create) {
319 if (isLocalSone(id)) {
320 return getLocalSone(id);
322 return getRemoteSone(id, create);
326 * Checks whether the core knows a Sone with the given ID.
330 * @return {@code true} if there is a Sone with the given ID, {@code false}
333 public boolean hasSone(String id) {
334 return isLocalSone(id) || isRemoteSone(id);
338 * Returns whether the given Sone is a local Sone.
341 * The Sone to check for its locality
342 * @return {@code true} if the given Sone is local, {@code false} otherwise
344 public boolean isLocalSone(Sone sone) {
345 synchronized (localSones) {
346 return localSones.containsKey(sone.getId());
351 * Returns whether the given ID is the ID of a local Sone.
354 * The Sone ID to check for its locality
355 * @return {@code true} if the given ID is a local Sone, {@code false}
358 public boolean isLocalSone(String id) {
359 synchronized (localSones) {
360 return localSones.containsKey(id);
365 * Returns all local Sones.
367 * @return All local Sones
369 public Set<Sone> getLocalSones() {
370 synchronized (localSones) {
371 return new HashSet<Sone>(localSones.values());
376 * Returns the local Sone with the given ID.
379 * The ID of the Sone to get
380 * @return The Sone with the given ID
382 public Sone getLocalSone(String id) {
383 return getLocalSone(id, true);
387 * Returns the local Sone with the given ID, optionally creating a new Sone.
392 * {@code true} to create a new Sone if none exists,
393 * {@code false} to return null if none exists
394 * @return The Sone with the given ID, or {@code null}
396 public Sone getLocalSone(String id, boolean create) {
397 synchronized (localSones) {
398 Sone sone = localSones.get(id);
399 if ((sone == null) && create) {
401 localSones.put(id, sone);
408 * Returns all remote Sones.
410 * @return All remote Sones
412 public Set<Sone> getRemoteSones() {
413 synchronized (remoteSones) {
414 return new HashSet<Sone>(remoteSones.values());
419 * Returns the remote Sone with the given ID.
422 * The ID of the remote Sone to get
423 * @return The Sone with the given ID
425 public Sone getRemoteSone(String id) {
426 return getRemoteSone(id, true);
430 * Returns the remote Sone with the given ID.
433 * The ID of the remote Sone to get
435 * {@code true} to always create a Sone, {@code false} to return
436 * {@code null} if no Sone with the given ID exists
437 * @return The Sone with the given ID
439 public Sone getRemoteSone(String id, boolean create) {
440 synchronized (remoteSones) {
441 Sone sone = remoteSones.get(id);
442 if ((sone == null) && create) {
444 remoteSones.put(id, sone);
451 * Returns whether the given Sone is a remote Sone.
455 * @return {@code true} if the given Sone is a remote Sone, {@code false}
458 public boolean isRemoteSone(Sone sone) {
459 synchronized (remoteSones) {
460 return remoteSones.containsKey(sone.getId());
465 * Returns whether the Sone with the given ID is a remote Sone.
468 * The ID of the Sone to check
469 * @return {@code true} if the Sone with the given ID is a remote Sone,
470 * {@code false} otherwise
472 public boolean isRemoteSone(String id) {
473 synchronized (remoteSones) {
474 return remoteSones.containsKey(id);
479 * Returns whether the given Sone is a new Sone. After this check, the Sone
480 * is marked as known, i.e. a second call with the same parameters will
481 * always yield {@code false}.
484 * The sone to check for
485 * @return {@code true} if the given Sone is new, false otherwise
487 public boolean isNewSone(Sone sone) {
488 synchronized (newSones) {
489 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
490 knownSones.add(sone.getId());
492 coreListenerManager.fireMarkSoneKnown(sone);
499 * Returns whether the given Sone has been modified.
502 * The Sone to check for modifications
503 * @return {@code true} if a modification has been detected in the Sone,
504 * {@code false} otherwise
506 public boolean isModifiedSone(Sone sone) {
507 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
511 * Returns whether the target Sone is trusted by the origin Sone.
517 * @return {@code true} if the target Sone is trusted by the origin Sone
519 public boolean isSoneTrusted(Sone origin, Sone target) {
520 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
524 * Returns the post with the given ID.
527 * The ID of the post to get
528 * @return The post, or {@code null} if there is no such post
530 public Post getPost(String postId) {
531 return getPost(postId, true);
535 * Returns the post with the given ID, optionally creating a new post.
538 * The ID of the post to get
540 * {@code true} it create a new post if no post with the given ID
541 * exists, {@code false} to return {@code null}
542 * @return The post, or {@code null} if there is no such post
544 public Post getPost(String postId, boolean create) {
545 synchronized (posts) {
546 Post post = posts.get(postId);
547 if ((post == null) && create) {
548 post = new Post(postId);
549 posts.put(postId, post);
556 * Returns whether the given post ID is new. After this method returns it is
557 * marked a known post ID.
561 * @return {@code true} if the post is considered to be new, {@code false}
564 public boolean isNewPost(String postId) {
565 return isNewPost(postId, true);
569 * Returns whether the given post ID is new. If {@code markAsKnown} is
570 * {@code true} then after this method returns the post ID is marked a known
576 * {@code true} to mark the post ID as known, {@code false} to
577 * not to mark it as known
578 * @return {@code true} if the post is considered to be new, {@code false}
581 public boolean isNewPost(String postId, boolean markAsKnown) {
582 synchronized (newPosts) {
583 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
585 Post post = getPost(postId, false);
595 * Returns the reply with the given ID. If there is no reply with the given
596 * ID yet, a new one is created.
599 * The ID of the reply to get
602 public Reply getReply(String replyId) {
603 return getReply(replyId, true);
607 * Returns the reply with the given ID. If there is no reply with the given
608 * ID yet, a new one is created, unless {@code create} is false in which
609 * case {@code null} is returned.
612 * The ID of the reply to get
614 * {@code true} to always return a {@link Reply}, {@code false}
615 * to return {@code null} if no reply can be found
616 * @return The reply, or {@code null} if there is no such reply
618 public Reply getReply(String replyId, boolean create) {
619 synchronized (replies) {
620 Reply reply = replies.get(replyId);
621 if (create && (reply == null)) {
622 reply = new Reply(replyId);
623 replies.put(replyId, reply);
630 * Returns all replies for the given post, order ascending by time.
633 * The post to get all replies for
634 * @return All replies for the given post
636 public List<Reply> getReplies(Post post) {
637 Set<Sone> sones = getSones();
638 List<Reply> replies = new ArrayList<Reply>();
639 for (Sone sone : sones) {
640 for (Reply reply : sone.getReplies()) {
641 if (reply.getPost().equals(post)) {
646 Collections.sort(replies, Reply.TIME_COMPARATOR);
651 * Returns whether the reply with the given ID is new.
654 * The ID of the reply to check
655 * @return {@code true} if the reply is considered to be new, {@code false}
658 public boolean isNewReply(String replyId) {
659 return isNewReply(replyId, true);
663 * Returns whether the reply with the given ID is new.
666 * The ID of the reply to check
668 * {@code true} to mark the reply as known, {@code false} to not
669 * to mark it as known
670 * @return {@code true} if the reply is considered to be new, {@code false}
673 public boolean isNewReply(String replyId, boolean markAsKnown) {
674 synchronized (newReplies) {
675 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
677 Reply reply = getReply(replyId, false);
679 markReplyKnown(reply);
687 * Returns all Sones that have liked the given post.
690 * The post to get the liking Sones for
691 * @return The Sones that like the given post
693 public Set<Sone> getLikes(Post post) {
694 Set<Sone> sones = new HashSet<Sone>();
695 for (Sone sone : getSones()) {
696 if (sone.getLikedPostIds().contains(post.getId())) {
704 * Returns all Sones that have liked the given reply.
707 * The reply to get the liking Sones for
708 * @return The Sones that like the given reply
710 public Set<Sone> getLikes(Reply reply) {
711 Set<Sone> sones = new HashSet<Sone>();
712 for (Sone sone : getSones()) {
713 if (sone.getLikedReplyIds().contains(reply.getId())) {
725 * Locks the given Sone. A locked Sone will not be inserted by
726 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
732 public void lockSone(Sone sone) {
733 synchronized (lockedSones) {
734 if (lockedSones.add(sone)) {
735 coreListenerManager.fireSoneLocked(sone);
741 * Unlocks the given Sone.
743 * @see #lockSone(Sone)
747 public void unlockSone(Sone sone) {
748 synchronized (lockedSones) {
749 if (lockedSones.remove(sone)) {
750 coreListenerManager.fireSoneUnlocked(sone);
756 * Adds a local Sone from the given ID which has to be the ID of an own
760 * The ID of an own identity to add a Sone for
761 * @return The added (or already existing) Sone
763 public Sone addLocalSone(String id) {
764 synchronized (localSones) {
765 if (localSones.containsKey(id)) {
766 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
767 return localSones.get(id);
769 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
770 if (ownIdentity == null) {
771 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
774 return addLocalSone(ownIdentity);
779 * Adds a local Sone from the given own identity.
782 * The own identity to create a Sone from
783 * @return The added (or already existing) Sone
785 public Sone addLocalSone(OwnIdentity ownIdentity) {
786 if (ownIdentity == null) {
787 logger.log(Level.WARNING, "Given OwnIdentity is null!");
790 synchronized (localSones) {
793 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
794 } catch (MalformedURLException mue1) {
795 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
798 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
799 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
800 /* TODO - load posts ’n stuff */
801 localSones.put(ownIdentity.getId(), sone);
802 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
803 soneInserters.put(sone, soneInserter);
804 setSoneStatus(sone, SoneStatus.idle);
806 if (!isSoneRescueMode()) {
807 soneInserter.start();
809 new Thread(new Runnable() {
812 @SuppressWarnings("synthetic-access")
814 if (!isSoneRescueMode()) {
815 soneDownloader.fetchSone(sone);
818 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
819 coreListenerManager.fireRescuingSone(sone);
821 long edition = sone.getLatestEdition();
822 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
823 logger.log(Level.FINE, "Downloading edition " + edition + "…");
824 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
827 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
829 coreListenerManager.fireRescuedSone(sone);
830 soneInserter.start();
833 }, "Sone Downloader").start();
839 * Creates a new Sone for the given own identity.
842 * The own identity to create a Sone for
843 * @return The created Sone
845 public Sone createSone(OwnIdentity ownIdentity) {
847 ownIdentity.addContext("Sone");
848 } catch (WebOfTrustException wote1) {
849 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
852 Sone sone = addLocalSone(ownIdentity);
857 * Adds the Sone of the given identity.
860 * The identity whose Sone to add
861 * @return The added or already existing Sone
863 public Sone addRemoteSone(Identity identity) {
864 if (identity == null) {
865 logger.log(Level.WARNING, "Given Identity is null!");
868 synchronized (remoteSones) {
869 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
870 boolean newSone = sone.getRequestUri() == null;
871 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
872 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
874 synchronized (newSones) {
875 newSone = !knownSones.contains(sone.getId());
877 newSones.add(sone.getId());
881 coreListenerManager.fireNewSoneFound(sone);
884 remoteSones.put(identity.getId(), sone);
885 soneDownloader.addSone(sone);
886 setSoneStatus(sone, SoneStatus.unknown);
887 new Thread(new Runnable() {
890 @SuppressWarnings("synthetic-access")
892 soneDownloader.fetchSone(sone);
895 }, "Sone Downloader").start();
901 * Retrieves the trust relationship from the origin to the target.
904 * The origin of the trust tree
906 * The target of the trust
907 * @return The trust relationship
909 public Trust getTrust(Sone origin, Sone target) {
910 if (!isLocalSone(origin)) {
911 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
915 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
916 } catch (WebOfTrustException wote1) {
917 logger.log(Level.WARNING, "Could not get trust for Sone: " + target, wote1);
923 * Updates the stores Sone with the given Sone.
928 public void updateSone(Sone sone) {
929 if (hasSone(sone.getId())) {
930 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
931 Sone storedSone = getSone(sone.getId());
932 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
933 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
936 synchronized (posts) {
937 if (!soneRescueMode) {
938 for (Post post : storedSone.getPosts()) {
939 posts.remove(post.getId());
940 if (!sone.getPosts().contains(post)) {
941 coreListenerManager.firePostRemoved(post);
945 synchronized (newPosts) {
946 for (Post post : sone.getPosts()) {
947 post.setSone(getSone(post.getSone().getId()));
948 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
949 newPosts.add(post.getId());
950 coreListenerManager.fireNewPostFound(post);
952 posts.put(post.getId(), post);
956 synchronized (replies) {
957 if (!soneRescueMode) {
958 for (Reply reply : storedSone.getReplies()) {
959 replies.remove(reply.getId());
960 if (!sone.getReplies().contains(reply)) {
961 coreListenerManager.fireReplyRemoved(reply);
965 synchronized (newReplies) {
966 for (Reply reply : sone.getReplies()) {
967 reply.setSone(getSone(reply.getSone().getId()));
968 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
969 newReplies.add(reply.getId());
970 coreListenerManager.fireNewReplyFound(reply);
972 replies.put(reply.getId(), reply);
976 synchronized (storedSone) {
977 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
978 storedSone.setTime(sone.getTime());
980 storedSone.setClient(sone.getClient());
981 storedSone.setProfile(sone.getProfile());
982 if (soneRescueMode) {
983 for (Post post : sone.getPosts()) {
984 storedSone.addPost(post);
986 for (Reply reply : sone.getReplies()) {
987 storedSone.addReply(reply);
989 for (String likedPostId : sone.getLikedPostIds()) {
990 storedSone.addLikedPostId(likedPostId);
992 for (String likedReplyId : sone.getLikedReplyIds()) {
993 storedSone.addLikedReplyId(likedReplyId);
996 storedSone.setPosts(sone.getPosts());
997 storedSone.setReplies(sone.getReplies());
998 storedSone.setLikePostIds(sone.getLikedPostIds());
999 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1001 storedSone.setLatestEdition(sone.getLatestEdition());
1007 * Deletes the given Sone. This will remove the Sone from the
1008 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1009 * and remove the context from its identity.
1012 * The Sone to delete
1014 public void deleteSone(Sone sone) {
1015 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1016 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1019 synchronized (localSones) {
1020 if (!localSones.containsKey(sone.getId())) {
1021 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1024 localSones.remove(sone.getId());
1025 soneInserters.remove(sone).stop();
1028 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1029 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1030 } catch (WebOfTrustException wote1) {
1031 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1034 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1035 } catch (ConfigurationException ce1) {
1036 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1041 * Loads and updates the given Sone from the configuration. If any error is
1042 * encountered, loading is aborted and the given Sone is not changed.
1045 * The Sone to load and update
1047 public void loadSone(Sone sone) {
1048 if (!isLocalSone(sone)) {
1049 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1054 String sonePrefix = "Sone/" + sone.getId();
1055 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1056 if (soneTime == null) {
1057 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1060 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1063 Profile profile = new Profile();
1064 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1065 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1066 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1067 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1068 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1069 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1072 Set<Post> posts = new HashSet<Post>();
1074 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1075 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1076 if (postId == null) {
1079 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1080 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1081 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1082 if ((postTime == 0) || (postText == null)) {
1083 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1086 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1087 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1088 post.setRecipient(getSone(postRecipientId));
1094 Set<Reply> replies = new HashSet<Reply>();
1096 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1097 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1098 if (replyId == null) {
1101 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1102 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1103 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1104 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1105 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1108 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1111 /* load post likes. */
1112 Set<String> likedPostIds = new HashSet<String>();
1114 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1115 if (likedPostId == null) {
1118 likedPostIds.add(likedPostId);
1121 /* load reply likes. */
1122 Set<String> likedReplyIds = new HashSet<String>();
1124 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1125 if (likedReplyId == null) {
1128 likedReplyIds.add(likedReplyId);
1132 Set<String> friends = new HashSet<String>();
1134 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1135 if (friendId == null) {
1138 friends.add(friendId);
1141 /* if we’re still here, Sone was loaded successfully. */
1142 synchronized (sone) {
1143 sone.setTime(soneTime);
1144 sone.setProfile(profile);
1145 sone.setPosts(posts);
1146 sone.setReplies(replies);
1147 sone.setLikePostIds(likedPostIds);
1148 sone.setLikeReplyIds(likedReplyIds);
1149 sone.setFriends(friends);
1150 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1152 synchronized (newSones) {
1153 for (String friend : friends) {
1154 knownSones.add(friend);
1157 synchronized (newPosts) {
1158 for (Post post : posts) {
1159 knownPosts.add(post.getId());
1162 synchronized (newReplies) {
1163 for (Reply reply : replies) {
1164 knownReplies.add(reply.getId());
1170 * Saves the given Sone. This will persist all local settings for the given
1171 * Sone, such as the friends list and similar, private options.
1176 public synchronized void saveSone(Sone sone) {
1177 if (!isLocalSone(sone)) {
1178 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1181 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1182 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1186 logger.log(Level.INFO, "Saving Sone: %s", sone);
1188 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1190 /* save Sone into configuration. */
1191 String sonePrefix = "Sone/" + sone.getId();
1192 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1193 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1196 Profile profile = sone.getProfile();
1197 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1198 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1199 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1200 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1201 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1202 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1205 int postCounter = 0;
1206 for (Post post : sone.getPosts()) {
1207 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1208 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1209 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1210 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1211 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1213 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1216 int replyCounter = 0;
1217 for (Reply reply : sone.getReplies()) {
1218 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1219 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1220 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1221 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1222 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1224 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1226 /* save post likes. */
1227 int postLikeCounter = 0;
1228 for (String postId : sone.getLikedPostIds()) {
1229 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1231 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1233 /* save reply likes. */
1234 int replyLikeCounter = 0;
1235 for (String replyId : sone.getLikedReplyIds()) {
1236 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1238 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1241 int friendCounter = 0;
1242 for (String friendId : sone.getFriends()) {
1243 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1245 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1247 configuration.save();
1248 logger.log(Level.INFO, "Sone %s saved.", sone);
1249 } catch (ConfigurationException ce1) {
1250 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1251 } catch (WebOfTrustException wote1) {
1252 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1257 * Creates a new post.
1260 * The Sone that creates the post
1262 * The text of the post
1263 * @return The created post
1265 public Post createPost(Sone sone, String text) {
1266 return createPost(sone, System.currentTimeMillis(), text);
1270 * Creates a new post.
1273 * The Sone that creates the post
1275 * The time of the post
1277 * The text of the post
1278 * @return The created post
1280 public Post createPost(Sone sone, long time, String text) {
1281 return createPost(sone, null, time, text);
1285 * Creates a new post.
1288 * The Sone that creates the post
1290 * The recipient Sone, or {@code null} if this post does not have
1293 * The text of the post
1294 * @return The created post
1296 public Post createPost(Sone sone, Sone recipient, String text) {
1297 return createPost(sone, recipient, System.currentTimeMillis(), text);
1301 * Creates a new post.
1304 * The Sone that creates the post
1306 * The recipient Sone, or {@code null} if this post does not have
1309 * The time of the post
1311 * The text of the post
1312 * @return The created post
1314 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1315 if (!isLocalSone(sone)) {
1316 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1319 Post post = new Post(sone, time, text);
1320 if (recipient != null) {
1321 post.setRecipient(recipient);
1323 synchronized (posts) {
1324 posts.put(post.getId(), post);
1326 synchronized (newPosts) {
1327 knownPosts.add(post.getId());
1335 * Deletes the given post.
1338 * The post to delete
1340 public void deletePost(Post post) {
1341 if (!isLocalSone(post.getSone())) {
1342 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1345 post.getSone().removePost(post);
1346 synchronized (posts) {
1347 posts.remove(post.getId());
1349 saveSone(post.getSone());
1353 * Marks the given post as known, if it is currently a new post (according
1354 * to {@link #isNewPost(String)}).
1357 * The post to mark as known
1359 public void markPostKnown(Post post) {
1360 synchronized (newPosts) {
1361 if (newPosts.remove(post.getId())) {
1362 knownPosts.add(post.getId());
1363 coreListenerManager.fireMarkPostKnown(post);
1364 saveConfiguration();
1370 * Creates a new reply.
1373 * The Sone that creates the reply
1375 * The post that this reply refers to
1377 * The text of the reply
1378 * @return The created reply
1380 public Reply createReply(Sone sone, Post post, String text) {
1381 return createReply(sone, post, System.currentTimeMillis(), text);
1385 * Creates a new reply.
1388 * The Sone that creates the reply
1390 * The post that this reply refers to
1392 * The time of the reply
1394 * The text of the reply
1395 * @return The created reply
1397 public Reply createReply(Sone sone, Post post, long time, String text) {
1398 if (!isLocalSone(sone)) {
1399 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1402 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1403 synchronized (replies) {
1404 replies.put(reply.getId(), reply);
1406 synchronized (newReplies) {
1407 knownReplies.add(reply.getId());
1409 sone.addReply(reply);
1415 * Deletes the given reply.
1418 * The reply to delete
1420 public void deleteReply(Reply reply) {
1421 Sone sone = reply.getSone();
1422 if (!isLocalSone(sone)) {
1423 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1426 synchronized (replies) {
1427 replies.remove(reply.getId());
1429 sone.removeReply(reply);
1434 * Marks the given reply as known, if it is currently a new reply (according
1435 * to {@link #isNewReply(String)}).
1438 * The reply to mark as known
1440 public void markReplyKnown(Reply reply) {
1441 synchronized (newReplies) {
1442 if (newReplies.remove(reply.getId())) {
1443 knownReplies.add(reply.getId());
1444 coreListenerManager.fireMarkReplyKnown(reply);
1445 saveConfiguration();
1453 public void start() {
1454 loadConfiguration();
1460 public void stop() {
1461 synchronized (localSones) {
1462 for (SoneInserter soneInserter : soneInserters.values()) {
1463 soneInserter.stop();
1466 soneDownloader.stop();
1467 saveConfiguration();
1472 * Saves the current options.
1474 public void saveConfiguration() {
1475 synchronized (configuration) {
1476 if (storingConfiguration) {
1477 logger.log(Level.FINE, "Already storing configuration…");
1480 storingConfiguration = true;
1483 /* store the options first. */
1485 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1486 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1487 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1488 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1490 /* save known Sones. */
1491 int soneCounter = 0;
1492 synchronized (newSones) {
1493 for (String knownSoneId : knownSones) {
1494 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1496 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1499 /* save known posts. */
1500 int postCounter = 0;
1501 synchronized (newPosts) {
1502 for (String knownPostId : knownPosts) {
1503 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1505 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1508 /* save known replies. */
1509 int replyCounter = 0;
1510 synchronized (newReplies) {
1511 for (String knownReplyId : knownReplies) {
1512 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1514 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1518 configuration.save();
1520 } catch (ConfigurationException ce1) {
1521 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1523 synchronized (configuration) {
1524 storingConfiguration = false;
1534 * Loads the configuration.
1536 @SuppressWarnings("unchecked")
1537 private void loadConfiguration() {
1538 /* create options. */
1539 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1542 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1543 SoneInserter.setInsertionDelay(newValue);
1547 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1548 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1549 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1551 /* read options from configuration. */
1552 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1553 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1554 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1555 options.getBooleanOption("ClearOnNextRestart").set(null);
1556 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1557 if (clearConfiguration) {
1558 /* stop loading the configuration. */
1562 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1563 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1565 /* load known Sones. */
1566 int soneCounter = 0;
1568 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1569 if (knownSoneId == null) {
1572 synchronized (newSones) {
1573 knownSones.add(knownSoneId);
1577 /* load known posts. */
1578 int postCounter = 0;
1580 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1581 if (knownPostId == null) {
1584 synchronized (newPosts) {
1585 knownPosts.add(knownPostId);
1589 /* load known replies. */
1590 int replyCounter = 0;
1592 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1593 if (knownReplyId == null) {
1596 synchronized (newReplies) {
1597 knownReplies.add(knownReplyId);
1604 * Generate a Sone URI from the given URI and latest edition.
1607 * The URI to derive the Sone URI from
1608 * @return The derived URI
1610 private FreenetURI getSoneUri(String uriString) {
1612 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1614 } catch (MalformedURLException mue1) {
1615 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1621 // INTERFACE IdentityListener
1628 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1629 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1630 if (ownIdentity.hasContext("Sone")) {
1631 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1632 addLocalSone(ownIdentity);
1640 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1641 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1642 trustedIdentities.remove(ownIdentity);
1649 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1650 logger.log(Level.FINEST, "Adding Identity: " + identity);
1651 trustedIdentities.get(ownIdentity).add(identity);
1652 addRemoteSone(identity);
1659 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1660 new Thread(new Runnable() {
1663 @SuppressWarnings("synthetic-access")
1665 Sone sone = getRemoteSone(identity.getId());
1666 soneDownloader.fetchSone(sone);
1675 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1676 trustedIdentities.get(ownIdentity).remove(identity);