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.WebOfTrustException;
44 import net.pterodactylus.sone.main.SonePlugin;
45 import net.pterodactylus.util.config.Configuration;
46 import net.pterodactylus.util.config.ConfigurationException;
47 import net.pterodactylus.util.logging.Logging;
48 import net.pterodactylus.util.number.Numbers;
49 import freenet.keys.FreenetURI;
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public class Core implements IdentityListener {
59 * Enumeration for the possible states of a {@link Sone}.
61 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63 public enum SoneStatus {
65 /** The Sone is unknown, i.e. not yet downloaded. */
68 /** The Sone is idle, i.e. not being downloaded or inserted. */
71 /** The Sone is currently being inserted. */
74 /** The Sone is currently being downloaded. */
79 private static final Logger logger = Logging.getLogger(Core.class);
82 private final Options options = new Options();
84 /** The core listener manager. */
85 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
87 /** The configuration. */
88 private Configuration configuration;
90 /** The identity manager. */
91 private final IdentityManager identityManager;
93 /** Interface to freenet. */
94 private final FreenetInterface freenetInterface;
96 /** The Sone downloader. */
97 private final SoneDownloader soneDownloader;
99 /** Whether the core has been stopped. */
100 private volatile boolean stopped;
102 /** The Sones’ statuses. */
103 /* synchronize access on itself. */
104 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
106 /** Locked local Sones. */
107 /* synchronize on itself. */
108 private final Set<Sone> lockedSones = new HashSet<Sone>();
110 /** Sone inserters. */
111 /* synchronize access on this on localSones. */
112 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
114 /** All local Sones. */
115 /* synchronize access on this on itself. */
116 private Map<String, Sone> localSones = new HashMap<String, Sone>();
118 /** All remote Sones. */
119 /* synchronize access on this on itself. */
120 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
122 /** All new Sones. */
123 private Set<String> newSones = new HashSet<String>();
125 /** All known Sones. */
126 /* synchronize access on {@link #newSones}. */
127 private Set<String> knownSones = new HashSet<String>();
130 private Map<String, Post> posts = new HashMap<String, Post>();
132 /** All new posts. */
133 private Set<String> newPosts = new HashSet<String>();
135 /** All known posts. */
136 /* synchronize access on {@link #newPosts}. */
137 private Set<String> knownPosts = new HashSet<String>();
140 private Map<String, Reply> replies = new HashMap<String, Reply>();
142 /** All new replies. */
143 private Set<String> newReplies = new HashSet<String>();
145 /** All known replies. */
146 private Set<String> knownReplies = new HashSet<String>();
148 /** Trusted identities, sorted by own identities. */
149 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
152 * Creates a new core.
154 * @param configuration
155 * The configuration of the core
156 * @param freenetInterface
157 * The freenet interface
158 * @param identityManager
159 * The identity manager
161 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
162 this.configuration = configuration;
163 this.freenetInterface = freenetInterface;
164 this.identityManager = identityManager;
165 this.soneDownloader = new SoneDownloader(this, freenetInterface);
169 // LISTENER MANAGEMENT
173 * Adds a new core listener.
175 * @param coreListener
176 * The listener to add
178 public void addCoreListener(CoreListener coreListener) {
179 coreListenerManager.addListener(coreListener);
183 * Removes a core listener.
185 * @param coreListener
186 * The listener to remove
188 public void removeCoreListener(CoreListener coreListener) {
189 coreListenerManager.removeListener(coreListener);
197 * Sets the configuration to use. This will automatically save the current
198 * configuration to the given configuration.
200 * @param configuration
201 * The new configuration to use
203 public void setConfiguration(Configuration configuration) {
204 this.configuration = configuration;
209 * Returns the options used by the core.
211 * @return The options of the core
213 public Options getOptions() {
218 * Returns whether the “Sone rescue mode” is currently activated.
220 * @return {@code true} if the “Sone rescue mode” is currently activated,
221 * {@code false} if it is not
223 public boolean isSoneRescueMode() {
224 return options.getBooleanOption("SoneRescueMode").get();
228 * Returns the identity manager used by the core.
230 * @return The identity manager
232 public IdentityManager getIdentityManager() {
233 return identityManager;
237 * Returns the status of the given Sone.
240 * The Sone to get the status for
241 * @return The status of the Sone
243 public SoneStatus getSoneStatus(Sone sone) {
244 synchronized (soneStatuses) {
245 return soneStatuses.get(sone);
250 * Sets the status of the given Sone.
253 * The Sone to set the status of
257 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
258 synchronized (soneStatuses) {
259 soneStatuses.put(sone, soneStatus);
264 * Returns whether the given Sone is currently locked.
268 * @return {@code true} if the Sone is locked, {@code false} if it is not
270 public boolean isLocked(Sone sone) {
271 synchronized (lockedSones) {
272 return lockedSones.contains(sone);
277 * Returns all Sones, remote and local.
281 public Set<Sone> getSones() {
282 Set<Sone> allSones = new HashSet<Sone>();
283 allSones.addAll(getLocalSones());
284 allSones.addAll(getRemoteSones());
289 * Returns the Sone with the given ID, regardless whether it’s local or
293 * The ID of the Sone to get
294 * @return The Sone with the given ID, or {@code null} if there is no such
297 public Sone getSone(String id) {
298 return getSone(id, true);
302 * Returns the Sone with the given ID, regardless whether it’s local or
306 * The ID of the Sone to get
308 * {@code true} to create a new Sone if none exists,
309 * {@code false} to return {@code null} if a Sone with the given
311 * @return The Sone with the given ID, or {@code null} if there is no such
314 public Sone getSone(String id, boolean create) {
315 if (isLocalSone(id)) {
316 return getLocalSone(id);
318 return getRemoteSone(id, create);
322 * Checks whether the core knows a Sone with the given ID.
326 * @return {@code true} if there is a Sone with the given ID, {@code false}
329 public boolean hasSone(String id) {
330 return isLocalSone(id) || isRemoteSone(id);
334 * Returns whether the given Sone is a local Sone.
337 * The Sone to check for its locality
338 * @return {@code true} if the given Sone is local, {@code false} otherwise
340 public boolean isLocalSone(Sone sone) {
341 synchronized (localSones) {
342 return localSones.containsKey(sone.getId());
347 * Returns whether the given ID is the ID of a local Sone.
350 * The Sone ID to check for its locality
351 * @return {@code true} if the given ID is a local Sone, {@code false}
354 public boolean isLocalSone(String id) {
355 synchronized (localSones) {
356 return localSones.containsKey(id);
361 * Returns all local Sones.
363 * @return All local Sones
365 public Set<Sone> getLocalSones() {
366 synchronized (localSones) {
367 return new HashSet<Sone>(localSones.values());
372 * Returns the local Sone with the given ID.
375 * The ID of the Sone to get
376 * @return The Sone with the given ID
378 public Sone getLocalSone(String id) {
379 return getLocalSone(id, true);
383 * Returns the local Sone with the given ID, optionally creating a new Sone.
388 * {@code true} to create a new Sone if none exists,
389 * {@code false} to return null if none exists
390 * @return The Sone with the given ID, or {@code null}
392 public Sone getLocalSone(String id, boolean create) {
393 synchronized (localSones) {
394 Sone sone = localSones.get(id);
395 if ((sone == null) && create) {
397 localSones.put(id, sone);
404 * Returns all remote Sones.
406 * @return All remote Sones
408 public Set<Sone> getRemoteSones() {
409 synchronized (remoteSones) {
410 return new HashSet<Sone>(remoteSones.values());
415 * Returns the remote Sone with the given ID.
418 * The ID of the remote Sone to get
419 * @return The Sone with the given ID
421 public Sone getRemoteSone(String id) {
422 return getRemoteSone(id, true);
426 * Returns the remote Sone with the given ID.
429 * The ID of the remote Sone to get
431 * {@code true} to always create a Sone, {@code false} to return
432 * {@code null} if no Sone with the given ID exists
433 * @return The Sone with the given ID
435 public Sone getRemoteSone(String id, boolean create) {
436 synchronized (remoteSones) {
437 Sone sone = remoteSones.get(id);
438 if ((sone == null) && create) {
440 remoteSones.put(id, sone);
447 * Returns whether the given Sone is a remote Sone.
451 * @return {@code true} if the given Sone is a remote Sone, {@code false}
454 public boolean isRemoteSone(Sone sone) {
455 synchronized (remoteSones) {
456 return remoteSones.containsKey(sone.getId());
461 * Returns whether the Sone with the given ID is a remote Sone.
464 * The ID of the Sone to check
465 * @return {@code true} if the Sone with the given ID is a remote Sone,
466 * {@code false} otherwise
468 public boolean isRemoteSone(String id) {
469 synchronized (remoteSones) {
470 return remoteSones.containsKey(id);
475 * Returns whether the given Sone is a new Sone. After this check, the Sone
476 * is marked as known, i.e. a second call with the same parameters will
477 * always yield {@code false}.
480 * The sone to check for
481 * @return {@code true} if the given Sone is new, false otherwise
483 public boolean isNewSone(Sone sone) {
484 synchronized (newSones) {
485 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
486 knownSones.add(sone.getId());
488 coreListenerManager.fireMarkSoneKnown(sone);
495 * Returns whether the given Sone has been modified.
498 * The Sone to check for modifications
499 * @return {@code true} if a modification has been detected in the Sone,
500 * {@code false} otherwise
502 public boolean isModifiedSone(Sone sone) {
503 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
507 * Returns whether the target Sone is trusted by the origin Sone.
513 * @return {@code true} if the target Sone is trusted by the origin Sone
515 public boolean isSoneTrusted(Sone origin, Sone target) {
516 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
520 * Returns the post with the given ID.
523 * The ID of the post to get
524 * @return The post, or {@code null} if there is no such post
526 public Post getPost(String postId) {
527 return getPost(postId, true);
531 * Returns the post with the given ID, optionally creating a new post.
534 * The ID of the post to get
536 * {@code true} it create a new post if no post with the given ID
537 * exists, {@code false} to return {@code null}
538 * @return The post, or {@code null} if there is no such post
540 public Post getPost(String postId, boolean create) {
541 synchronized (posts) {
542 Post post = posts.get(postId);
543 if ((post == null) && create) {
544 post = new Post(postId);
545 posts.put(postId, post);
552 * Returns whether the given post ID is new. After this method returns it is
553 * marked a known post ID.
557 * @return {@code true} if the post is considered to be new, {@code false}
560 public boolean isNewPost(String postId) {
561 return isNewPost(postId, true);
565 * Returns whether the given post ID is new. If {@code markAsKnown} is
566 * {@code true} then after this method returns the post ID is marked a known
572 * {@code true} to mark the post ID as known, {@code false} to
573 * not to mark it as known
574 * @return {@code true} if the post is considered to be new, {@code false}
577 public boolean isNewPost(String postId, boolean markAsKnown) {
578 synchronized (newPosts) {
579 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
581 Post post = getPost(postId, false);
591 * Returns the reply with the given ID. If there is no reply with the given
592 * ID yet, a new one is created.
595 * The ID of the reply to get
598 public Reply getReply(String replyId) {
599 return getReply(replyId, true);
603 * Returns the reply with the given ID. If there is no reply with the given
604 * ID yet, a new one is created, unless {@code create} is false in which
605 * case {@code null} is returned.
608 * The ID of the reply to get
610 * {@code true} to always return a {@link Reply}, {@code false}
611 * to return {@code null} if no reply can be found
612 * @return The reply, or {@code null} if there is no such reply
614 public Reply getReply(String replyId, boolean create) {
615 synchronized (replies) {
616 Reply reply = replies.get(replyId);
617 if (create && (reply == null)) {
618 reply = new Reply(replyId);
619 replies.put(replyId, reply);
626 * Returns all replies for the given post, order ascending by time.
629 * The post to get all replies for
630 * @return All replies for the given post
632 public List<Reply> getReplies(Post post) {
633 Set<Sone> sones = getSones();
634 List<Reply> replies = new ArrayList<Reply>();
635 for (Sone sone : sones) {
636 for (Reply reply : sone.getReplies()) {
637 if (reply.getPost().equals(post)) {
642 Collections.sort(replies, Reply.TIME_COMPARATOR);
647 * Returns whether the reply with the given ID is new.
650 * The ID of the reply to check
651 * @return {@code true} if the reply is considered to be new, {@code false}
654 public boolean isNewReply(String replyId) {
655 return isNewReply(replyId, true);
659 * Returns whether the reply with the given ID is new.
662 * The ID of the reply to check
664 * {@code true} to mark the reply as known, {@code false} to not
665 * to mark it as known
666 * @return {@code true} if the reply is considered to be new, {@code false}
669 public boolean isNewReply(String replyId, boolean markAsKnown) {
670 synchronized (newReplies) {
671 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
673 Reply reply = getReply(replyId, false);
675 markReplyKnown(reply);
683 * Returns all Sones that have liked the given post.
686 * The post to get the liking Sones for
687 * @return The Sones that like the given post
689 public Set<Sone> getLikes(Post post) {
690 Set<Sone> sones = new HashSet<Sone>();
691 for (Sone sone : getSones()) {
692 if (sone.getLikedPostIds().contains(post.getId())) {
700 * Returns all Sones that have liked the given reply.
703 * The reply to get the liking Sones for
704 * @return The Sones that like the given reply
706 public Set<Sone> getLikes(Reply reply) {
707 Set<Sone> sones = new HashSet<Sone>();
708 for (Sone sone : getSones()) {
709 if (sone.getLikedReplyIds().contains(reply.getId())) {
721 * Locks the given Sone. A locked Sone will not be inserted by
722 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
728 public void lockSone(Sone sone) {
729 synchronized (lockedSones) {
730 lockedSones.add(sone);
735 * Unlocks the given Sone.
737 * @see #lockSone(Sone)
741 public void unlockSone(Sone sone) {
742 synchronized (lockedSones) {
743 lockedSones.remove(sone);
748 * Adds a local Sone from the given ID which has to be the ID of an own
752 * The ID of an own identity to add a Sone for
753 * @return The added (or already existing) Sone
755 public Sone addLocalSone(String id) {
756 synchronized (localSones) {
757 if (localSones.containsKey(id)) {
758 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
759 return localSones.get(id);
761 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
762 if (ownIdentity == null) {
763 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
766 return addLocalSone(ownIdentity);
771 * Adds a local Sone from the given own identity.
774 * The own identity to create a Sone from
775 * @return The added (or already existing) Sone
777 public Sone addLocalSone(OwnIdentity ownIdentity) {
778 if (ownIdentity == null) {
779 logger.log(Level.WARNING, "Given OwnIdentity is null!");
782 synchronized (localSones) {
785 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
786 } catch (MalformedURLException mue1) {
787 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
790 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
791 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
792 /* TODO - load posts ’n stuff */
793 localSones.put(ownIdentity.getId(), sone);
794 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
795 soneInserters.put(sone, soneInserter);
796 setSoneStatus(sone, SoneStatus.idle);
798 if (!isSoneRescueMode()) {
799 soneInserter.start();
801 new Thread(new Runnable() {
804 @SuppressWarnings("synthetic-access")
806 if (!isSoneRescueMode()) {
807 soneDownloader.fetchSone(sone);
810 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
811 coreListenerManager.fireRescuingSone(sone);
813 long edition = sone.getLatestEdition();
814 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
815 logger.log(Level.FINE, "Downloading edition " + edition + "…");
816 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
819 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
821 coreListenerManager.fireRescuedSone(sone);
822 soneInserter.start();
825 }, "Sone Downloader").start();
831 * Creates a new Sone for the given own identity.
834 * The own identity to create a Sone for
835 * @return The created Sone
837 public Sone createSone(OwnIdentity ownIdentity) {
839 ownIdentity.addContext("Sone");
840 } catch (WebOfTrustException wote1) {
841 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
844 Sone sone = addLocalSone(ownIdentity);
849 * Adds the Sone of the given identity.
852 * The identity whose Sone to add
853 * @return The added or already existing Sone
855 public Sone addRemoteSone(Identity identity) {
856 if (identity == null) {
857 logger.log(Level.WARNING, "Given Identity is null!");
860 synchronized (remoteSones) {
861 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
862 boolean newSone = sone.getRequestUri() == null;
863 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
864 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
866 synchronized (newSones) {
867 newSone = !knownSones.contains(sone.getId());
869 newSones.add(sone.getId());
873 coreListenerManager.fireNewSoneFound(sone);
876 remoteSones.put(identity.getId(), sone);
877 soneDownloader.addSone(sone);
878 setSoneStatus(sone, SoneStatus.unknown);
879 new Thread(new Runnable() {
882 @SuppressWarnings("synthetic-access")
884 soneDownloader.fetchSone(sone);
887 }, "Sone Downloader").start();
893 * Updates the stores Sone with the given Sone.
898 public void updateSone(Sone sone) {
899 if (hasSone(sone.getId())) {
900 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
901 Sone storedSone = getSone(sone.getId());
902 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
903 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
906 synchronized (posts) {
907 if (!soneRescueMode) {
908 for (Post post : storedSone.getPosts()) {
909 posts.remove(post.getId());
910 if (!sone.getPosts().contains(post)) {
911 coreListenerManager.firePostRemoved(post);
915 synchronized (newPosts) {
916 for (Post post : sone.getPosts()) {
917 post.setSone(getSone(post.getSone().getId()));
918 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
919 newPosts.add(post.getId());
920 coreListenerManager.fireNewPostFound(post);
922 posts.put(post.getId(), post);
926 synchronized (replies) {
927 if (!soneRescueMode) {
928 for (Reply reply : storedSone.getReplies()) {
929 replies.remove(reply.getId());
930 if (!sone.getReplies().contains(reply)) {
931 coreListenerManager.fireReplyRemoved(reply);
935 synchronized (newReplies) {
936 for (Reply reply : sone.getReplies()) {
937 reply.setSone(getSone(reply.getSone().getId()));
938 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
939 newReplies.add(reply.getId());
940 coreListenerManager.fireNewReplyFound(reply);
942 replies.put(reply.getId(), reply);
946 synchronized (storedSone) {
947 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
948 storedSone.setTime(sone.getTime());
950 storedSone.setClient(sone.getClient());
951 storedSone.setProfile(sone.getProfile());
952 if (soneRescueMode) {
953 for (Post post : sone.getPosts()) {
954 storedSone.addPost(post);
956 for (Reply reply : sone.getReplies()) {
957 storedSone.addReply(reply);
959 for (String likedPostId : sone.getLikedPostIds()) {
960 storedSone.addLikedPostId(likedPostId);
962 for (String likedReplyId : sone.getLikedReplyIds()) {
963 storedSone.addLikedReplyId(likedReplyId);
966 storedSone.setPosts(sone.getPosts());
967 storedSone.setReplies(sone.getReplies());
968 storedSone.setLikePostIds(sone.getLikedPostIds());
969 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
971 storedSone.setLatestEdition(sone.getLatestEdition());
977 * Deletes the given Sone. This will remove the Sone from the
978 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
979 * and remove the context from its identity.
984 public void deleteSone(Sone sone) {
985 if (!(sone.getIdentity() instanceof OwnIdentity)) {
986 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
989 synchronized (localSones) {
990 if (!localSones.containsKey(sone.getId())) {
991 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
994 localSones.remove(sone.getId());
995 soneInserters.remove(sone).stop();
998 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
999 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1000 } catch (WebOfTrustException wote1) {
1001 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1004 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1005 } catch (ConfigurationException ce1) {
1006 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1011 * Loads and updates the given Sone from the configuration. If any error is
1012 * encountered, loading is aborted and the given Sone is not changed.
1015 * The Sone to load and update
1017 public void loadSone(Sone sone) {
1018 if (!isLocalSone(sone)) {
1019 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1024 String sonePrefix = "Sone/" + sone.getId();
1025 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1026 if (soneTime == null) {
1027 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1030 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1033 Profile profile = new Profile();
1034 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1035 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1036 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1037 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1038 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1039 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1042 Set<Post> posts = new HashSet<Post>();
1044 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1045 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1046 if (postId == null) {
1049 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1050 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1051 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1052 if ((postTime == 0) || (postText == null)) {
1053 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1056 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1057 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1058 post.setRecipient(getSone(postRecipientId));
1064 Set<Reply> replies = new HashSet<Reply>();
1066 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1067 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1068 if (replyId == null) {
1071 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1072 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1073 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1074 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1075 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1078 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1081 /* load post likes. */
1082 Set<String> likedPostIds = new HashSet<String>();
1084 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1085 if (likedPostId == null) {
1088 likedPostIds.add(likedPostId);
1091 /* load reply likes. */
1092 Set<String> likedReplyIds = new HashSet<String>();
1094 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1095 if (likedReplyId == null) {
1098 likedReplyIds.add(likedReplyId);
1102 Set<String> friends = new HashSet<String>();
1104 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1105 if (friendId == null) {
1108 friends.add(friendId);
1111 /* if we’re still here, Sone was loaded successfully. */
1112 synchronized (sone) {
1113 sone.setTime(soneTime);
1114 sone.setProfile(profile);
1115 sone.setPosts(posts);
1116 sone.setReplies(replies);
1117 sone.setLikePostIds(likedPostIds);
1118 sone.setLikeReplyIds(likedReplyIds);
1119 sone.setFriends(friends);
1120 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1122 synchronized (newSones) {
1123 for (String friend : friends) {
1124 knownSones.add(friend);
1127 synchronized (newPosts) {
1128 for (Post post : posts) {
1129 knownPosts.add(post.getId());
1132 synchronized (newReplies) {
1133 for (Reply reply : replies) {
1134 knownReplies.add(reply.getId());
1140 * Saves the given Sone. This will persist all local settings for the given
1141 * Sone, such as the friends list and similar, private options.
1146 public void saveSone(Sone sone) {
1147 if (!isLocalSone(sone)) {
1148 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1151 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1152 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1156 logger.log(Level.INFO, "Saving Sone: %s", sone);
1158 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1160 /* save Sone into configuration. */
1161 String sonePrefix = "Sone/" + sone.getId();
1162 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1163 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1166 Profile profile = sone.getProfile();
1167 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1168 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1169 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1170 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1171 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1172 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1175 int postCounter = 0;
1176 for (Post post : sone.getPosts()) {
1177 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1178 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1179 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1180 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1181 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1183 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1186 int replyCounter = 0;
1187 for (Reply reply : sone.getReplies()) {
1188 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1189 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1190 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1191 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1192 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1194 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1196 /* save post likes. */
1197 int postLikeCounter = 0;
1198 for (String postId : sone.getLikedPostIds()) {
1199 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1201 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1203 /* save reply likes. */
1204 int replyLikeCounter = 0;
1205 for (String replyId : sone.getLikedReplyIds()) {
1206 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1208 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1211 int friendCounter = 0;
1212 for (String friendId : sone.getFriends()) {
1213 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1215 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1217 logger.log(Level.INFO, "Sone %s saved.", sone);
1218 } catch (ConfigurationException ce1) {
1219 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1220 } catch (WebOfTrustException wote1) {
1221 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1226 * Creates a new post.
1229 * The Sone that creates the post
1231 * The text of the post
1232 * @return The created post
1234 public Post createPost(Sone sone, String text) {
1235 return createPost(sone, System.currentTimeMillis(), text);
1239 * Creates a new post.
1242 * The Sone that creates the post
1244 * The time of the post
1246 * The text of the post
1247 * @return The created post
1249 public Post createPost(Sone sone, long time, String text) {
1250 return createPost(sone, null, time, text);
1254 * Creates a new post.
1257 * The Sone that creates the post
1259 * The recipient Sone, or {@code null} if this post does not have
1262 * The text of the post
1263 * @return The created post
1265 public Post createPost(Sone sone, Sone recipient, String text) {
1266 return createPost(sone, recipient, System.currentTimeMillis(), text);
1270 * Creates a new post.
1273 * The Sone that creates the post
1275 * The recipient Sone, or {@code null} if this post does not have
1278 * The time of the post
1280 * The text of the post
1281 * @return The created post
1283 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1284 if (!isLocalSone(sone)) {
1285 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1288 Post post = new Post(sone, time, text);
1289 if (recipient != null) {
1290 post.setRecipient(recipient);
1292 synchronized (posts) {
1293 posts.put(post.getId(), post);
1295 synchronized (newPosts) {
1296 knownPosts.add(post.getId());
1304 * Deletes the given post.
1307 * The post to delete
1309 public void deletePost(Post post) {
1310 if (!isLocalSone(post.getSone())) {
1311 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1314 post.getSone().removePost(post);
1315 synchronized (posts) {
1316 posts.remove(post.getId());
1318 saveSone(post.getSone());
1322 * Marks the given post as known, if it is currently a new post (according
1323 * to {@link #isNewPost(String)}).
1326 * The post to mark as known
1328 public void markPostKnown(Post post) {
1329 synchronized (newPosts) {
1330 if (newPosts.remove(post.getId())) {
1331 knownPosts.add(post.getId());
1332 coreListenerManager.fireMarkPostKnown(post);
1338 * Creates a new reply.
1341 * The Sone that creates the reply
1343 * The post that this reply refers to
1345 * The text of the reply
1346 * @return The created reply
1348 public Reply createReply(Sone sone, Post post, String text) {
1349 return createReply(sone, post, System.currentTimeMillis(), text);
1353 * Creates a new reply.
1356 * The Sone that creates the reply
1358 * The post that this reply refers to
1360 * The time of the reply
1362 * The text of the reply
1363 * @return The created reply
1365 public Reply createReply(Sone sone, Post post, long time, String text) {
1366 if (!isLocalSone(sone)) {
1367 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1370 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1371 synchronized (replies) {
1372 replies.put(reply.getId(), reply);
1374 synchronized (newReplies) {
1375 knownReplies.add(reply.getId());
1377 sone.addReply(reply);
1383 * Deletes the given reply.
1386 * The reply to delete
1388 public void deleteReply(Reply reply) {
1389 Sone sone = reply.getSone();
1390 if (!isLocalSone(sone)) {
1391 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1394 synchronized (replies) {
1395 replies.remove(reply.getId());
1397 sone.removeReply(reply);
1402 * Marks the given reply as known, if it is currently a new reply (according
1403 * to {@link #isNewReply(String)}).
1406 * The reply to mark as known
1408 public void markReplyKnown(Reply reply) {
1409 synchronized (newReplies) {
1410 if (newReplies.remove(reply.getId())) {
1411 knownReplies.add(reply.getId());
1412 coreListenerManager.fireMarkReplyKnown(reply);
1420 public void start() {
1421 loadConfiguration();
1427 public void stop() {
1428 synchronized (localSones) {
1429 for (SoneInserter soneInserter : soneInserters.values()) {
1430 soneInserter.stop();
1433 saveConfiguration();
1438 * Saves the current options.
1440 public void saveConfiguration() {
1441 /* store the options first. */
1443 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1444 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1445 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1446 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1448 /* save known Sones. */
1449 int soneCounter = 0;
1450 synchronized (newSones) {
1451 for (String knownSoneId : knownSones) {
1452 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1454 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1457 /* save known posts. */
1458 int postCounter = 0;
1459 synchronized (newPosts) {
1460 for (String knownPostId : knownPosts) {
1461 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1463 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1466 /* save known replies. */
1467 int replyCounter = 0;
1468 synchronized (newReplies) {
1469 for (String knownReplyId : knownReplies) {
1470 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1472 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1476 configuration.save();
1478 } catch (ConfigurationException ce1) {
1479 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1488 * Loads the configuration.
1490 @SuppressWarnings("unchecked")
1491 private void loadConfiguration() {
1492 /* create options. */
1493 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1496 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1497 SoneInserter.setInsertionDelay(newValue);
1501 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1502 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1503 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1505 /* read options from configuration. */
1506 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1507 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1508 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1509 options.getBooleanOption("ClearOnNextRestart").set(null);
1510 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1511 if (clearConfiguration) {
1512 /* stop loading the configuration. */
1516 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1517 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1519 /* load known Sones. */
1520 int soneCounter = 0;
1522 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1523 if (knownSoneId == null) {
1526 synchronized (newSones) {
1527 knownSones.add(knownSoneId);
1531 /* load known posts. */
1532 int postCounter = 0;
1534 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1535 if (knownPostId == null) {
1538 synchronized (newPosts) {
1539 knownPosts.add(knownPostId);
1543 /* load known replies. */
1544 int replyCounter = 0;
1546 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1547 if (knownReplyId == null) {
1550 synchronized (newReplies) {
1551 knownReplies.add(knownReplyId);
1558 * Generate a Sone URI from the given URI and latest edition.
1561 * The URI to derive the Sone URI from
1562 * @return The derived URI
1564 private FreenetURI getSoneUri(String uriString) {
1566 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1568 } catch (MalformedURLException mue1) {
1569 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1575 // INTERFACE IdentityListener
1582 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1583 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1584 if (ownIdentity.hasContext("Sone")) {
1585 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1586 addLocalSone(ownIdentity);
1594 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1595 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1596 trustedIdentities.remove(ownIdentity);
1603 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1604 logger.log(Level.FINEST, "Adding Identity: " + identity);
1605 trustedIdentities.get(ownIdentity).add(identity);
1606 addRemoteSone(identity);
1613 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1614 new Thread(new Runnable() {
1617 @SuppressWarnings("synthetic-access")
1619 Sone sone = getRemoteSone(identity.getId());
1620 soneDownloader.fetchSone(sone);
1629 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1630 trustedIdentities.get(ownIdentity).remove(identity);