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.main.SonePlugin;
44 import net.pterodactylus.util.config.Configuration;
45 import net.pterodactylus.util.config.ConfigurationException;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.number.Numbers;
48 import net.pterodactylus.util.version.Version;
49 import freenet.keys.FreenetURI;
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public class Core implements IdentityListener, UpdateListener {
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 /** Whether we’re currently saving the configuration. */
91 private boolean storingConfiguration = false;
93 /** The identity manager. */
94 private final IdentityManager identityManager;
96 /** Interface to freenet. */
97 private final FreenetInterface freenetInterface;
99 /** The Sone downloader. */
100 private final SoneDownloader soneDownloader;
102 /** The update checker. */
103 private final UpdateChecker updateChecker;
105 /** Whether the core has been stopped. */
106 private volatile boolean stopped;
108 /** The Sones’ statuses. */
109 /* synchronize access on itself. */
110 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
112 /** Locked local Sones. */
113 /* synchronize on itself. */
114 private final Set<Sone> lockedSones = new HashSet<Sone>();
116 /** Sone inserters. */
117 /* synchronize access on this on localSones. */
118 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
120 /** All local Sones. */
121 /* synchronize access on this on itself. */
122 private Map<String, Sone> localSones = new HashMap<String, Sone>();
124 /** All remote Sones. */
125 /* synchronize access on this on itself. */
126 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
128 /** All new Sones. */
129 private Set<String> newSones = new HashSet<String>();
131 /** All known Sones. */
132 /* synchronize access on {@link #newSones}. */
133 private Set<String> knownSones = new HashSet<String>();
136 private Map<String, Post> posts = new HashMap<String, Post>();
138 /** All new posts. */
139 private Set<String> newPosts = new HashSet<String>();
141 /** All known posts. */
142 /* synchronize access on {@link #newPosts}. */
143 private Set<String> knownPosts = new HashSet<String>();
146 private Map<String, Reply> replies = new HashMap<String, Reply>();
148 /** All new replies. */
149 private Set<String> newReplies = new HashSet<String>();
151 /** All known replies. */
152 private Set<String> knownReplies = new HashSet<String>();
155 * Creates a new core.
157 * @param configuration
158 * The configuration of the core
159 * @param freenetInterface
160 * The freenet interface
161 * @param identityManager
162 * The identity manager
164 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
165 this.configuration = configuration;
166 this.freenetInterface = freenetInterface;
167 this.identityManager = identityManager;
168 this.soneDownloader = new SoneDownloader(this, freenetInterface);
169 this.updateChecker = new UpdateChecker(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 update checker.
243 * @return The update checker
245 public UpdateChecker getUpdateChecker() {
246 return updateChecker;
250 * Returns the status of the given Sone.
253 * The Sone to get the status for
254 * @return The status of the Sone
256 public SoneStatus getSoneStatus(Sone sone) {
257 synchronized (soneStatuses) {
258 return soneStatuses.get(sone);
263 * Sets the status of the given Sone.
266 * The Sone to set the status of
270 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
271 synchronized (soneStatuses) {
272 soneStatuses.put(sone, soneStatus);
277 * Returns whether the given Sone is currently locked.
281 * @return {@code true} if the Sone is locked, {@code false} if it is not
283 public boolean isLocked(Sone sone) {
284 synchronized (lockedSones) {
285 return lockedSones.contains(sone);
290 * Returns all Sones, remote and local.
294 public Set<Sone> getSones() {
295 Set<Sone> allSones = new HashSet<Sone>();
296 allSones.addAll(getLocalSones());
297 allSones.addAll(getRemoteSones());
302 * Returns the Sone with the given ID, regardless whether it’s local or
306 * The ID of the Sone to get
307 * @return The Sone with the given ID, or {@code null} if there is no such
310 public Sone getSone(String id) {
311 return getSone(id, true);
315 * Returns the Sone with the given ID, regardless whether it’s local or
319 * The ID of the Sone to get
321 * {@code true} to create a new Sone if none exists,
322 * {@code false} to return {@code null} if a Sone with the given
324 * @return The Sone with the given ID, or {@code null} if there is no such
327 public Sone getSone(String id, boolean create) {
328 if (isLocalSone(id)) {
329 return getLocalSone(id);
331 return getRemoteSone(id, create);
335 * Checks whether the core knows a Sone with the given ID.
339 * @return {@code true} if there is a Sone with the given ID, {@code false}
342 public boolean hasSone(String id) {
343 return isLocalSone(id) || isRemoteSone(id);
347 * Returns whether the given Sone is a local Sone.
350 * The Sone to check for its locality
351 * @return {@code true} if the given Sone is local, {@code false} otherwise
353 public boolean isLocalSone(Sone sone) {
354 synchronized (localSones) {
355 return localSones.containsKey(sone.getId());
360 * Returns whether the given ID is the ID of a local Sone.
363 * The Sone ID to check for its locality
364 * @return {@code true} if the given ID is a local Sone, {@code false}
367 public boolean isLocalSone(String id) {
368 synchronized (localSones) {
369 return localSones.containsKey(id);
374 * Returns all local Sones.
376 * @return All local Sones
378 public Set<Sone> getLocalSones() {
379 synchronized (localSones) {
380 return new HashSet<Sone>(localSones.values());
385 * Returns the local Sone with the given ID.
388 * The ID of the Sone to get
389 * @return The Sone with the given ID
391 public Sone getLocalSone(String id) {
392 return getLocalSone(id, true);
396 * Returns the local Sone with the given ID, optionally creating a new Sone.
401 * {@code true} to create a new Sone if none exists,
402 * {@code false} to return null if none exists
403 * @return The Sone with the given ID, or {@code null}
405 public Sone getLocalSone(String id, boolean create) {
406 synchronized (localSones) {
407 Sone sone = localSones.get(id);
408 if ((sone == null) && create) {
410 localSones.put(id, sone);
417 * Returns all remote Sones.
419 * @return All remote Sones
421 public Set<Sone> getRemoteSones() {
422 synchronized (remoteSones) {
423 return new HashSet<Sone>(remoteSones.values());
428 * Returns the remote Sone with the given ID.
431 * The ID of the remote Sone to get
432 * @return The Sone with the given ID
434 public Sone getRemoteSone(String id) {
435 return getRemoteSone(id, true);
439 * Returns the remote Sone with the given ID.
442 * The ID of the remote Sone to get
444 * {@code true} to always create a Sone, {@code false} to return
445 * {@code null} if no Sone with the given ID exists
446 * @return The Sone with the given ID
448 public Sone getRemoteSone(String id, boolean create) {
449 synchronized (remoteSones) {
450 Sone sone = remoteSones.get(id);
451 if ((sone == null) && create) {
453 remoteSones.put(id, sone);
460 * Returns whether the given Sone is a remote Sone.
464 * @return {@code true} if the given Sone is a remote Sone, {@code false}
467 public boolean isRemoteSone(Sone sone) {
468 synchronized (remoteSones) {
469 return remoteSones.containsKey(sone.getId());
474 * Returns whether the Sone with the given ID is a remote Sone.
477 * The ID of the Sone to check
478 * @return {@code true} if the Sone with the given ID is a remote Sone,
479 * {@code false} otherwise
481 public boolean isRemoteSone(String id) {
482 synchronized (remoteSones) {
483 return remoteSones.containsKey(id);
488 * Returns whether the given Sone is a new Sone. After this check, the Sone
489 * is marked as known, i.e. a second call with the same parameters will
490 * always yield {@code false}.
493 * The sone to check for
494 * @return {@code true} if the given Sone is new, false otherwise
496 public boolean isNewSone(Sone sone) {
497 synchronized (newSones) {
498 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
499 knownSones.add(sone.getId());
501 coreListenerManager.fireMarkSoneKnown(sone);
508 * Returns whether the given Sone has been modified.
511 * The Sone to check for modifications
512 * @return {@code true} if a modification has been detected in the Sone,
513 * {@code false} otherwise
515 public boolean isModifiedSone(Sone sone) {
516 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
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 if (lockedSones.add(sone)) {
731 coreListenerManager.fireSoneLocked(sone);
737 * Unlocks the given Sone.
739 * @see #lockSone(Sone)
743 public void unlockSone(Sone sone) {
744 synchronized (lockedSones) {
745 if (lockedSones.remove(sone)) {
746 coreListenerManager.fireSoneUnlocked(sone);
752 * Adds a local Sone from the given ID which has to be the ID of an own
756 * The ID of an own identity to add a Sone for
757 * @return The added (or already existing) Sone
759 public Sone addLocalSone(String id) {
760 synchronized (localSones) {
761 if (localSones.containsKey(id)) {
762 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
763 return localSones.get(id);
765 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
766 if (ownIdentity == null) {
767 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
770 return addLocalSone(ownIdentity);
775 * Adds a local Sone from the given own identity.
778 * The own identity to create a Sone from
779 * @return The added (or already existing) Sone
781 public Sone addLocalSone(OwnIdentity ownIdentity) {
782 if (ownIdentity == null) {
783 logger.log(Level.WARNING, "Given OwnIdentity is null!");
786 synchronized (localSones) {
789 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
790 } catch (MalformedURLException mue1) {
791 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
794 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
795 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
796 /* TODO - load posts ’n stuff */
797 localSones.put(ownIdentity.getId(), sone);
798 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
799 soneInserters.put(sone, soneInserter);
800 setSoneStatus(sone, SoneStatus.idle);
802 if (!isSoneRescueMode()) {
803 soneInserter.start();
805 new Thread(new Runnable() {
808 @SuppressWarnings("synthetic-access")
810 if (!isSoneRescueMode()) {
811 soneDownloader.fetchSone(sone);
814 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
815 coreListenerManager.fireRescuingSone(sone);
817 long edition = sone.getLatestEdition();
818 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
819 logger.log(Level.FINE, "Downloading edition " + edition + "…");
820 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
823 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
825 coreListenerManager.fireRescuedSone(sone);
826 soneInserter.start();
829 }, "Sone Downloader").start();
835 * Creates a new Sone for the given own identity.
838 * The own identity to create a Sone for
839 * @return The created Sone
841 public Sone createSone(OwnIdentity ownIdentity) {
842 identityManager.addContext(ownIdentity, "Sone");
843 Sone sone = addLocalSone(ownIdentity);
848 * Adds the Sone of the given identity.
851 * The identity whose Sone to add
852 * @return The added or already existing Sone
854 public Sone addRemoteSone(Identity identity) {
855 if (identity == null) {
856 logger.log(Level.WARNING, "Given Identity is null!");
859 synchronized (remoteSones) {
860 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
861 boolean newSone = sone.getRequestUri() == null;
862 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
863 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
865 synchronized (newSones) {
866 newSone = !knownSones.contains(sone.getId());
868 newSones.add(sone.getId());
872 coreListenerManager.fireNewSoneFound(sone);
875 remoteSones.put(identity.getId(), sone);
876 soneDownloader.addSone(sone);
877 setSoneStatus(sone, SoneStatus.unknown);
878 new Thread(new Runnable() {
881 @SuppressWarnings("synthetic-access")
883 soneDownloader.fetchSone(sone);
886 }, "Sone Downloader").start();
892 * Updates the stores Sone with the given Sone.
897 public void updateSone(Sone sone) {
898 if (hasSone(sone.getId())) {
899 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
900 Sone storedSone = getSone(sone.getId());
901 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
902 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
905 synchronized (posts) {
906 if (!soneRescueMode) {
907 for (Post post : storedSone.getPosts()) {
908 posts.remove(post.getId());
909 if (!sone.getPosts().contains(post)) {
910 coreListenerManager.firePostRemoved(post);
914 synchronized (newPosts) {
915 for (Post post : sone.getPosts()) {
916 post.setSone(getSone(post.getSone().getId()));
917 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
918 newPosts.add(post.getId());
919 coreListenerManager.fireNewPostFound(post);
921 posts.put(post.getId(), post);
925 synchronized (replies) {
926 if (!soneRescueMode) {
927 for (Reply reply : storedSone.getReplies()) {
928 replies.remove(reply.getId());
929 if (!sone.getReplies().contains(reply)) {
930 coreListenerManager.fireReplyRemoved(reply);
934 synchronized (newReplies) {
935 for (Reply reply : sone.getReplies()) {
936 reply.setSone(getSone(reply.getSone().getId()));
937 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
938 newReplies.add(reply.getId());
939 coreListenerManager.fireNewReplyFound(reply);
941 replies.put(reply.getId(), reply);
945 synchronized (storedSone) {
946 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
947 storedSone.setTime(sone.getTime());
949 storedSone.setClient(sone.getClient());
950 storedSone.setProfile(sone.getProfile());
951 if (soneRescueMode) {
952 for (Post post : sone.getPosts()) {
953 storedSone.addPost(post);
955 for (Reply reply : sone.getReplies()) {
956 storedSone.addReply(reply);
958 for (String likedPostId : sone.getLikedPostIds()) {
959 storedSone.addLikedPostId(likedPostId);
961 for (String likedReplyId : sone.getLikedReplyIds()) {
962 storedSone.addLikedReplyId(likedReplyId);
965 storedSone.setPosts(sone.getPosts());
966 storedSone.setReplies(sone.getReplies());
967 storedSone.setLikePostIds(sone.getLikedPostIds());
968 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
970 storedSone.setLatestEdition(sone.getLatestEdition());
976 * Deletes the given Sone. This will remove the Sone from the
977 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
978 * and remove the context from its identity.
983 public void deleteSone(Sone sone) {
984 if (!(sone.getIdentity() instanceof OwnIdentity)) {
985 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
988 synchronized (localSones) {
989 if (!localSones.containsKey(sone.getId())) {
990 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
993 localSones.remove(sone.getId());
994 soneInserters.remove(sone).stop();
996 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
997 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
999 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1000 } catch (ConfigurationException ce1) {
1001 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1006 * Loads and updates the given Sone from the configuration. If any error is
1007 * encountered, loading is aborted and the given Sone is not changed.
1010 * The Sone to load and update
1012 public void loadSone(Sone sone) {
1013 if (!isLocalSone(sone)) {
1014 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1019 String sonePrefix = "Sone/" + sone.getId();
1020 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1021 if (soneTime == null) {
1022 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1025 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1028 Profile profile = new Profile();
1029 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1030 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1031 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1032 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1033 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1034 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1037 Set<Post> posts = new HashSet<Post>();
1039 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1040 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1041 if (postId == null) {
1044 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1045 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1046 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1047 if ((postTime == 0) || (postText == null)) {
1048 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1051 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1052 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1053 post.setRecipient(getSone(postRecipientId));
1059 Set<Reply> replies = new HashSet<Reply>();
1061 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1062 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1063 if (replyId == null) {
1066 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1067 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1068 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1069 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1070 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1073 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1076 /* load post likes. */
1077 Set<String> likedPostIds = new HashSet<String>();
1079 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1080 if (likedPostId == null) {
1083 likedPostIds.add(likedPostId);
1086 /* load reply likes. */
1087 Set<String> likedReplyIds = new HashSet<String>();
1089 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1090 if (likedReplyId == null) {
1093 likedReplyIds.add(likedReplyId);
1097 Set<String> friends = new HashSet<String>();
1099 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1100 if (friendId == null) {
1103 friends.add(friendId);
1106 /* if we’re still here, Sone was loaded successfully. */
1107 synchronized (sone) {
1108 sone.setTime(soneTime);
1109 sone.setProfile(profile);
1110 sone.setPosts(posts);
1111 sone.setReplies(replies);
1112 sone.setLikePostIds(likedPostIds);
1113 sone.setLikeReplyIds(likedReplyIds);
1114 sone.setFriends(friends);
1115 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1117 synchronized (newSones) {
1118 for (String friend : friends) {
1119 knownSones.add(friend);
1122 synchronized (newPosts) {
1123 for (Post post : posts) {
1124 knownPosts.add(post.getId());
1127 synchronized (newReplies) {
1128 for (Reply reply : replies) {
1129 knownReplies.add(reply.getId());
1135 * Saves the given Sone. This will persist all local settings for the given
1136 * Sone, such as the friends list and similar, private options.
1141 public synchronized void saveSone(Sone sone) {
1142 if (!isLocalSone(sone)) {
1143 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1146 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1147 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1151 logger.log(Level.INFO, "Saving Sone: %s", sone);
1152 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1154 /* save Sone into configuration. */
1155 String sonePrefix = "Sone/" + sone.getId();
1156 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1157 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1160 Profile profile = sone.getProfile();
1161 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1162 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1163 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1164 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1165 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1166 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1169 int postCounter = 0;
1170 for (Post post : sone.getPosts()) {
1171 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1172 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1173 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1174 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1175 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1177 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1180 int replyCounter = 0;
1181 for (Reply reply : sone.getReplies()) {
1182 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1183 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1184 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1185 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1186 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1188 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1190 /* save post likes. */
1191 int postLikeCounter = 0;
1192 for (String postId : sone.getLikedPostIds()) {
1193 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1195 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1197 /* save reply likes. */
1198 int replyLikeCounter = 0;
1199 for (String replyId : sone.getLikedReplyIds()) {
1200 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1202 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1205 int friendCounter = 0;
1206 for (String friendId : sone.getFriends()) {
1207 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1209 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1211 configuration.save();
1212 logger.log(Level.INFO, "Sone %s saved.", sone);
1213 } catch (ConfigurationException ce1) {
1214 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1219 * Creates a new post.
1222 * The Sone that creates the post
1224 * The text of the post
1225 * @return The created post
1227 public Post createPost(Sone sone, String text) {
1228 return createPost(sone, System.currentTimeMillis(), text);
1232 * Creates a new post.
1235 * The Sone that creates the post
1237 * The time of the post
1239 * The text of the post
1240 * @return The created post
1242 public Post createPost(Sone sone, long time, String text) {
1243 return createPost(sone, null, time, text);
1247 * Creates a new post.
1250 * The Sone that creates the post
1252 * The recipient Sone, or {@code null} if this post does not have
1255 * The text of the post
1256 * @return The created post
1258 public Post createPost(Sone sone, Sone recipient, String text) {
1259 return createPost(sone, recipient, System.currentTimeMillis(), text);
1263 * Creates a new post.
1266 * The Sone that creates the post
1268 * The recipient Sone, or {@code null} if this post does not have
1271 * The time of the post
1273 * The text of the post
1274 * @return The created post
1276 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1277 if (!isLocalSone(sone)) {
1278 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1281 Post post = new Post(sone, time, text);
1282 if (recipient != null) {
1283 post.setRecipient(recipient);
1285 synchronized (posts) {
1286 posts.put(post.getId(), post);
1288 synchronized (newPosts) {
1289 knownPosts.add(post.getId());
1297 * Deletes the given post.
1300 * The post to delete
1302 public void deletePost(Post post) {
1303 if (!isLocalSone(post.getSone())) {
1304 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1307 post.getSone().removePost(post);
1308 synchronized (posts) {
1309 posts.remove(post.getId());
1311 saveSone(post.getSone());
1315 * Marks the given post as known, if it is currently a new post (according
1316 * to {@link #isNewPost(String)}).
1319 * The post to mark as known
1321 public void markPostKnown(Post post) {
1322 synchronized (newPosts) {
1323 if (newPosts.remove(post.getId())) {
1324 knownPosts.add(post.getId());
1325 coreListenerManager.fireMarkPostKnown(post);
1326 saveConfiguration();
1332 * Creates a new reply.
1335 * The Sone that creates the reply
1337 * The post that this reply refers to
1339 * The text of the reply
1340 * @return The created reply
1342 public Reply createReply(Sone sone, Post post, String text) {
1343 return createReply(sone, post, System.currentTimeMillis(), text);
1347 * Creates a new reply.
1350 * The Sone that creates the reply
1352 * The post that this reply refers to
1354 * The time of the reply
1356 * The text of the reply
1357 * @return The created reply
1359 public Reply createReply(Sone sone, Post post, long time, String text) {
1360 if (!isLocalSone(sone)) {
1361 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1364 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1365 synchronized (replies) {
1366 replies.put(reply.getId(), reply);
1368 synchronized (newReplies) {
1369 knownReplies.add(reply.getId());
1371 sone.addReply(reply);
1377 * Deletes the given reply.
1380 * The reply to delete
1382 public void deleteReply(Reply reply) {
1383 Sone sone = reply.getSone();
1384 if (!isLocalSone(sone)) {
1385 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1388 synchronized (replies) {
1389 replies.remove(reply.getId());
1391 sone.removeReply(reply);
1396 * Marks the given reply as known, if it is currently a new reply (according
1397 * to {@link #isNewReply(String)}).
1400 * The reply to mark as known
1402 public void markReplyKnown(Reply reply) {
1403 synchronized (newReplies) {
1404 if (newReplies.remove(reply.getId())) {
1405 knownReplies.add(reply.getId());
1406 coreListenerManager.fireMarkReplyKnown(reply);
1407 saveConfiguration();
1415 public void start() {
1416 loadConfiguration();
1417 updateChecker.addUpdateListener(this);
1418 updateChecker.start();
1424 public void stop() {
1425 synchronized (localSones) {
1426 for (SoneInserter soneInserter : soneInserters.values()) {
1427 soneInserter.stop();
1430 updateChecker.stop();
1431 updateChecker.removeUpdateListener(this);
1432 soneDownloader.stop();
1433 saveConfiguration();
1438 * Saves the current options.
1440 public void saveConfiguration() {
1441 synchronized (configuration) {
1442 if (storingConfiguration) {
1443 logger.log(Level.FINE, "Already storing configuration…");
1446 storingConfiguration = true;
1449 /* store the options first. */
1451 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1452 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1453 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1454 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1455 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1457 /* save known Sones. */
1458 int soneCounter = 0;
1459 synchronized (newSones) {
1460 for (String knownSoneId : knownSones) {
1461 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1463 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1466 /* save known posts. */
1467 int postCounter = 0;
1468 synchronized (newPosts) {
1469 for (String knownPostId : knownPosts) {
1470 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1472 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1475 /* save known replies. */
1476 int replyCounter = 0;
1477 synchronized (newReplies) {
1478 for (String knownReplyId : knownReplies) {
1479 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1481 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1485 configuration.save();
1487 } catch (ConfigurationException ce1) {
1488 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1490 synchronized (configuration) {
1491 storingConfiguration = false;
1501 * Loads the configuration.
1503 @SuppressWarnings("unchecked")
1504 private void loadConfiguration() {
1505 /* create options. */
1506 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1509 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1510 SoneInserter.setInsertionDelay(newValue);
1514 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1515 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1516 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1518 /* read options from configuration. */
1519 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1520 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1521 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1522 options.getBooleanOption("ClearOnNextRestart").set(null);
1523 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1524 if (clearConfiguration) {
1525 /* stop loading the configuration. */
1529 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1530 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1532 /* load known Sones. */
1533 int soneCounter = 0;
1535 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1536 if (knownSoneId == null) {
1539 synchronized (newSones) {
1540 knownSones.add(knownSoneId);
1544 /* load known posts. */
1545 int postCounter = 0;
1547 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1548 if (knownPostId == null) {
1551 synchronized (newPosts) {
1552 knownPosts.add(knownPostId);
1556 /* load known replies. */
1557 int replyCounter = 0;
1559 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1560 if (knownReplyId == null) {
1563 synchronized (newReplies) {
1564 knownReplies.add(knownReplyId);
1571 * Generate a Sone URI from the given URI and latest edition.
1574 * The URI to derive the Sone URI from
1575 * @return The derived URI
1577 private FreenetURI getSoneUri(String uriString) {
1579 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1581 } catch (MalformedURLException mue1) {
1582 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1588 // INTERFACE IdentityListener
1595 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1596 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1597 if (ownIdentity.hasContext("Sone")) {
1598 addLocalSone(ownIdentity);
1606 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1607 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1614 public void identityAdded(Identity identity) {
1615 logger.log(Level.FINEST, "Adding Identity: " + identity);
1616 addRemoteSone(identity);
1623 public void identityUpdated(final Identity identity) {
1624 new Thread(new Runnable() {
1627 @SuppressWarnings("synthetic-access")
1629 Sone sone = getRemoteSone(identity.getId());
1630 soneDownloader.fetchSone(sone);
1639 public void identityRemoved(Identity identity) {
1644 // INTERFACE UpdateListener
1651 public void updateFound(Version version, long releaseTime) {
1652 coreListenerManager.fireUpdateFound(version, releaseTime);