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>();
149 * Creates a new core.
151 * @param configuration
152 * The configuration of the core
153 * @param freenetInterface
154 * The freenet interface
155 * @param identityManager
156 * The identity manager
158 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
159 this.configuration = configuration;
160 this.freenetInterface = freenetInterface;
161 this.identityManager = identityManager;
162 this.soneDownloader = new SoneDownloader(this, freenetInterface);
166 // LISTENER MANAGEMENT
170 * Adds a new core listener.
172 * @param coreListener
173 * The listener to add
175 public void addCoreListener(CoreListener coreListener) {
176 coreListenerManager.addListener(coreListener);
180 * Removes a core listener.
182 * @param coreListener
183 * The listener to remove
185 public void removeCoreListener(CoreListener coreListener) {
186 coreListenerManager.removeListener(coreListener);
194 * Sets the configuration to use. This will automatically save the current
195 * configuration to the given configuration.
197 * @param configuration
198 * The new configuration to use
200 public void setConfiguration(Configuration configuration) {
201 this.configuration = configuration;
206 * Returns the options used by the core.
208 * @return The options of the core
210 public Options getOptions() {
215 * Returns whether the “Sone rescue mode” is currently activated.
217 * @return {@code true} if the “Sone rescue mode” is currently activated,
218 * {@code false} if it is not
220 public boolean isSoneRescueMode() {
221 return options.getBooleanOption("SoneRescueMode").get();
225 * Returns the identity manager used by the core.
227 * @return The identity manager
229 public IdentityManager getIdentityManager() {
230 return identityManager;
234 * Returns the status of the given Sone.
237 * The Sone to get the status for
238 * @return The status of the Sone
240 public SoneStatus getSoneStatus(Sone sone) {
241 synchronized (soneStatuses) {
242 return soneStatuses.get(sone);
247 * Sets the status of the given Sone.
250 * The Sone to set the status of
254 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
255 synchronized (soneStatuses) {
256 soneStatuses.put(sone, soneStatus);
261 * Returns whether the given Sone is currently locked.
265 * @return {@code true} if the Sone is locked, {@code false} if it is not
267 public boolean isLocked(Sone sone) {
268 synchronized (lockedSones) {
269 return lockedSones.contains(sone);
274 * Returns all Sones, remote and local.
278 public Set<Sone> getSones() {
279 Set<Sone> allSones = new HashSet<Sone>();
280 allSones.addAll(getLocalSones());
281 allSones.addAll(getRemoteSones());
286 * Returns the Sone with the given ID, regardless whether it’s local or
290 * The ID of the Sone to get
291 * @return The Sone with the given ID, or {@code null} if there is no such
294 public Sone getSone(String id) {
295 return getSone(id, true);
299 * Returns the Sone with the given ID, regardless whether it’s local or
303 * The ID of the Sone to get
305 * {@code true} to create a new Sone if none exists,
306 * {@code false} to return {@code null} if a Sone with the given
308 * @return The Sone with the given ID, or {@code null} if there is no such
311 public Sone getSone(String id, boolean create) {
312 if (isLocalSone(id)) {
313 return getLocalSone(id);
315 return getRemoteSone(id, create);
319 * Checks whether the core knows a Sone with the given ID.
323 * @return {@code true} if there is a Sone with the given ID, {@code false}
326 public boolean hasSone(String id) {
327 return isLocalSone(id) || isRemoteSone(id);
331 * Returns whether the given Sone is a local Sone.
334 * The Sone to check for its locality
335 * @return {@code true} if the given Sone is local, {@code false} otherwise
337 public boolean isLocalSone(Sone sone) {
338 synchronized (localSones) {
339 return localSones.containsKey(sone.getId());
344 * Returns whether the given ID is the ID of a local Sone.
347 * The Sone ID to check for its locality
348 * @return {@code true} if the given ID is a local Sone, {@code false}
351 public boolean isLocalSone(String id) {
352 synchronized (localSones) {
353 return localSones.containsKey(id);
358 * Returns all local Sones.
360 * @return All local Sones
362 public Set<Sone> getLocalSones() {
363 synchronized (localSones) {
364 return new HashSet<Sone>(localSones.values());
369 * Returns the local Sone with the given ID.
372 * The ID of the Sone to get
373 * @return The Sone with the given ID
375 public Sone getLocalSone(String id) {
376 return getLocalSone(id, true);
380 * Returns the local Sone with the given ID, optionally creating a new Sone.
385 * {@code true} to create a new Sone if none exists,
386 * {@code false} to return null if none exists
387 * @return The Sone with the given ID, or {@code null}
389 public Sone getLocalSone(String id, boolean create) {
390 synchronized (localSones) {
391 Sone sone = localSones.get(id);
392 if ((sone == null) && create) {
394 localSones.put(id, sone);
401 * Returns all remote Sones.
403 * @return All remote Sones
405 public Set<Sone> getRemoteSones() {
406 synchronized (remoteSones) {
407 return new HashSet<Sone>(remoteSones.values());
412 * Returns the remote Sone with the given ID.
415 * The ID of the remote Sone to get
416 * @return The Sone with the given ID
418 public Sone getRemoteSone(String id) {
419 return getRemoteSone(id, true);
423 * Returns the remote Sone with the given ID.
426 * The ID of the remote Sone to get
428 * {@code true} to always create a Sone, {@code false} to return
429 * {@code null} if no Sone with the given ID exists
430 * @return The Sone with the given ID
432 public Sone getRemoteSone(String id, boolean create) {
433 synchronized (remoteSones) {
434 Sone sone = remoteSones.get(id);
435 if ((sone == null) && create) {
437 remoteSones.put(id, sone);
444 * Returns whether the given Sone is a remote Sone.
448 * @return {@code true} if the given Sone is a remote Sone, {@code false}
451 public boolean isRemoteSone(Sone sone) {
452 synchronized (remoteSones) {
453 return remoteSones.containsKey(sone.getId());
458 * Returns whether the Sone with the given ID is a remote Sone.
461 * The ID of the Sone to check
462 * @return {@code true} if the Sone with the given ID is a remote Sone,
463 * {@code false} otherwise
465 public boolean isRemoteSone(String id) {
466 synchronized (remoteSones) {
467 return remoteSones.containsKey(id);
472 * Returns whether the given Sone is a new Sone. After this check, the Sone
473 * is marked as known, i.e. a second call with the same parameters will
474 * always yield {@code false}.
477 * The sone to check for
478 * @return {@code true} if the given Sone is new, false otherwise
480 public boolean isNewSone(Sone sone) {
481 synchronized (newSones) {
482 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
483 knownSones.add(sone.getId());
485 coreListenerManager.fireMarkSoneKnown(sone);
492 * Returns whether the given Sone has been modified.
495 * The Sone to check for modifications
496 * @return {@code true} if a modification has been detected in the Sone,
497 * {@code false} otherwise
499 public boolean isModifiedSone(Sone sone) {
500 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
504 * Returns the post with the given ID.
507 * The ID of the post to get
508 * @return The post, or {@code null} if there is no such post
510 public Post getPost(String postId) {
511 return getPost(postId, true);
515 * Returns the post with the given ID, optionally creating a new post.
518 * The ID of the post to get
520 * {@code true} it create a new post if no post with the given ID
521 * exists, {@code false} to return {@code null}
522 * @return The post, or {@code null} if there is no such post
524 public Post getPost(String postId, boolean create) {
525 synchronized (posts) {
526 Post post = posts.get(postId);
527 if ((post == null) && create) {
528 post = new Post(postId);
529 posts.put(postId, post);
536 * Returns whether the given post ID is new. After this method returns it is
537 * marked a known post ID.
541 * @return {@code true} if the post is considered to be new, {@code false}
544 public boolean isNewPost(String postId) {
545 return isNewPost(postId, true);
549 * Returns whether the given post ID is new. If {@code markAsKnown} is
550 * {@code true} then after this method returns the post ID is marked a known
556 * {@code true} to mark the post ID as known, {@code false} to
557 * not to mark it as known
558 * @return {@code true} if the post is considered to be new, {@code false}
561 public boolean isNewPost(String postId, boolean markAsKnown) {
562 synchronized (newPosts) {
563 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
565 Post post = getPost(postId, false);
575 * Returns the reply with the given ID. If there is no reply with the given
576 * ID yet, a new one is created.
579 * The ID of the reply to get
582 public Reply getReply(String replyId) {
583 return getReply(replyId, true);
587 * Returns the reply with the given ID. If there is no reply with the given
588 * ID yet, a new one is created, unless {@code create} is false in which
589 * case {@code null} is returned.
592 * The ID of the reply to get
594 * {@code true} to always return a {@link Reply}, {@code false}
595 * to return {@code null} if no reply can be found
596 * @return The reply, or {@code null} if there is no such reply
598 public Reply getReply(String replyId, boolean create) {
599 synchronized (replies) {
600 Reply reply = replies.get(replyId);
601 if (create && (reply == null)) {
602 reply = new Reply(replyId);
603 replies.put(replyId, reply);
610 * Returns all replies for the given post, order ascending by time.
613 * The post to get all replies for
614 * @return All replies for the given post
616 public List<Reply> getReplies(Post post) {
617 Set<Sone> sones = getSones();
618 List<Reply> replies = new ArrayList<Reply>();
619 for (Sone sone : sones) {
620 for (Reply reply : sone.getReplies()) {
621 if (reply.getPost().equals(post)) {
626 Collections.sort(replies, Reply.TIME_COMPARATOR);
631 * Returns whether the reply with the given ID is new.
634 * The ID of the reply to check
635 * @return {@code true} if the reply is considered to be new, {@code false}
638 public boolean isNewReply(String replyId) {
639 return isNewReply(replyId, true);
643 * Returns whether the reply with the given ID is new.
646 * The ID of the reply to check
648 * {@code true} to mark the reply as known, {@code false} to not
649 * to mark it as known
650 * @return {@code true} if the reply is considered to be new, {@code false}
653 public boolean isNewReply(String replyId, boolean markAsKnown) {
654 synchronized (newReplies) {
655 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
657 Reply reply = getReply(replyId, false);
659 markReplyKnown(reply);
667 * Returns all Sones that have liked the given post.
670 * The post to get the liking Sones for
671 * @return The Sones that like the given post
673 public Set<Sone> getLikes(Post post) {
674 Set<Sone> sones = new HashSet<Sone>();
675 for (Sone sone : getSones()) {
676 if (sone.getLikedPostIds().contains(post.getId())) {
684 * Returns all Sones that have liked the given reply.
687 * The reply to get the liking Sones for
688 * @return The Sones that like the given reply
690 public Set<Sone> getLikes(Reply reply) {
691 Set<Sone> sones = new HashSet<Sone>();
692 for (Sone sone : getSones()) {
693 if (sone.getLikedReplyIds().contains(reply.getId())) {
705 * Locks the given Sone. A locked Sone will not be inserted by
706 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
712 public void lockSone(Sone sone) {
713 synchronized (lockedSones) {
714 lockedSones.add(sone);
719 * Unlocks the given Sone.
721 * @see #lockSone(Sone)
725 public void unlockSone(Sone sone) {
726 synchronized (lockedSones) {
727 lockedSones.remove(sone);
732 * Adds a local Sone from the given ID which has to be the ID of an own
736 * The ID of an own identity to add a Sone for
737 * @return The added (or already existing) Sone
739 public Sone addLocalSone(String id) {
740 synchronized (localSones) {
741 if (localSones.containsKey(id)) {
742 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
743 return localSones.get(id);
745 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
746 if (ownIdentity == null) {
747 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
750 return addLocalSone(ownIdentity);
755 * Adds a local Sone from the given own identity.
758 * The own identity to create a Sone from
759 * @return The added (or already existing) Sone
761 public Sone addLocalSone(OwnIdentity ownIdentity) {
762 if (ownIdentity == null) {
763 logger.log(Level.WARNING, "Given OwnIdentity is null!");
766 synchronized (localSones) {
769 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
770 } catch (MalformedURLException mue1) {
771 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
774 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
775 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
776 /* TODO - load posts ’n stuff */
777 localSones.put(ownIdentity.getId(), sone);
778 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
779 soneInserters.put(sone, soneInserter);
780 setSoneStatus(sone, SoneStatus.idle);
782 if (!isSoneRescueMode()) {
783 soneInserter.start();
785 new Thread(new Runnable() {
788 @SuppressWarnings("synthetic-access")
790 if (!isSoneRescueMode()) {
791 soneDownloader.fetchSone(sone);
794 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
795 coreListenerManager.fireRescuingSone(sone);
797 long edition = sone.getLatestEdition();
798 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
799 logger.log(Level.FINE, "Downloading edition " + edition + "…");
800 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
803 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
805 coreListenerManager.fireRescuedSone(sone);
806 soneInserter.start();
809 }, "Sone Downloader").start();
815 * Creates a new Sone for the given own identity.
818 * The own identity to create a Sone for
819 * @return The created Sone
821 public Sone createSone(OwnIdentity ownIdentity) {
823 ownIdentity.addContext("Sone");
824 } catch (WebOfTrustException wote1) {
825 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
828 Sone sone = addLocalSone(ownIdentity);
833 * Adds the Sone of the given identity.
836 * The identity whose Sone to add
837 * @return The added or already existing Sone
839 public Sone addRemoteSone(Identity identity) {
840 if (identity == null) {
841 logger.log(Level.WARNING, "Given Identity is null!");
844 synchronized (remoteSones) {
845 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
846 boolean newSone = sone.getRequestUri() == null;
847 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
848 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
850 synchronized (newSones) {
851 newSone = !knownSones.contains(sone.getId());
853 newSones.add(sone.getId());
857 coreListenerManager.fireNewSoneFound(sone);
860 remoteSones.put(identity.getId(), sone);
861 soneDownloader.addSone(sone);
862 setSoneStatus(sone, SoneStatus.unknown);
863 new Thread(new Runnable() {
866 @SuppressWarnings("synthetic-access")
868 soneDownloader.fetchSone(sone);
871 }, "Sone Downloader").start();
877 * Updates the stores Sone with the given Sone.
882 public void updateSone(Sone sone) {
883 if (hasSone(sone.getId())) {
884 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
885 Sone storedSone = getSone(sone.getId());
886 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
887 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
890 synchronized (posts) {
891 if (!soneRescueMode) {
892 for (Post post : storedSone.getPosts()) {
893 posts.remove(post.getId());
894 if (!sone.getPosts().contains(post)) {
895 coreListenerManager.firePostRemoved(post);
899 synchronized (newPosts) {
900 for (Post post : sone.getPosts()) {
901 post.setSone(getSone(post.getSone().getId()));
902 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
903 newPosts.add(post.getId());
904 coreListenerManager.fireNewPostFound(post);
906 posts.put(post.getId(), post);
910 synchronized (replies) {
911 if (!soneRescueMode) {
912 for (Reply reply : storedSone.getReplies()) {
913 replies.remove(reply.getId());
914 if (!sone.getReplies().contains(reply)) {
915 coreListenerManager.fireReplyRemoved(reply);
919 synchronized (newReplies) {
920 for (Reply reply : sone.getReplies()) {
921 reply.setSone(getSone(reply.getSone().getId()));
922 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
923 newReplies.add(reply.getId());
924 coreListenerManager.fireNewReplyFound(reply);
926 replies.put(reply.getId(), reply);
930 synchronized (storedSone) {
931 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
932 storedSone.setTime(sone.getTime());
934 storedSone.setClient(sone.getClient());
935 storedSone.setProfile(sone.getProfile());
936 if (soneRescueMode) {
937 for (Post post : sone.getPosts()) {
938 storedSone.addPost(post);
940 for (Reply reply : sone.getReplies()) {
941 storedSone.addReply(reply);
943 for (String likedPostId : sone.getLikedPostIds()) {
944 storedSone.addLikedPostId(likedPostId);
946 for (String likedReplyId : sone.getLikedReplyIds()) {
947 storedSone.addLikedReplyId(likedReplyId);
950 storedSone.setPosts(sone.getPosts());
951 storedSone.setReplies(sone.getReplies());
952 storedSone.setLikePostIds(sone.getLikedPostIds());
953 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
955 storedSone.setLatestEdition(sone.getLatestEdition());
961 * Deletes the given Sone. This will remove the Sone from the
962 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
963 * and remove the context from its identity.
968 public void deleteSone(Sone sone) {
969 if (!(sone.getIdentity() instanceof OwnIdentity)) {
970 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
973 synchronized (localSones) {
974 if (!localSones.containsKey(sone.getId())) {
975 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
978 localSones.remove(sone.getId());
979 soneInserters.remove(sone).stop();
982 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
983 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
984 } catch (WebOfTrustException wote1) {
985 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
988 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
989 } catch (ConfigurationException ce1) {
990 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
995 * Loads and updates the given Sone from the configuration. If any error is
996 * encountered, loading is aborted and the given Sone is not changed.
999 * The Sone to load and update
1001 public void loadSone(Sone sone) {
1002 if (!isLocalSone(sone)) {
1003 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1008 String sonePrefix = "Sone/" + sone.getId();
1009 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1010 if (soneTime == null) {
1011 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1014 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1017 Profile profile = new Profile();
1018 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1019 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1020 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1021 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1022 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1023 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1026 Set<Post> posts = new HashSet<Post>();
1028 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1029 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1030 if (postId == null) {
1033 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1034 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1035 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1036 if ((postTime == 0) || (postText == null)) {
1037 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1040 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1041 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1042 post.setRecipient(getSone(postRecipientId));
1048 Set<Reply> replies = new HashSet<Reply>();
1050 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1051 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1052 if (replyId == null) {
1055 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1056 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1057 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1058 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1059 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1062 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1065 /* load post likes. */
1066 Set<String> likedPostIds = new HashSet<String>();
1068 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1069 if (likedPostId == null) {
1072 likedPostIds.add(likedPostId);
1075 /* load reply likes. */
1076 Set<String> likedReplyIds = new HashSet<String>();
1078 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1079 if (likedReplyId == null) {
1082 likedReplyIds.add(likedReplyId);
1086 Set<String> friends = new HashSet<String>();
1088 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1089 if (friendId == null) {
1092 friends.add(friendId);
1095 /* if we’re still here, Sone was loaded successfully. */
1096 synchronized (sone) {
1097 sone.setTime(soneTime);
1098 sone.setProfile(profile);
1099 sone.setPosts(posts);
1100 sone.setReplies(replies);
1101 sone.setLikePostIds(likedPostIds);
1102 sone.setLikeReplyIds(likedReplyIds);
1103 sone.setFriends(friends);
1104 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1106 synchronized (newSones) {
1107 for (String friend : friends) {
1108 knownSones.add(friend);
1111 synchronized (newPosts) {
1112 for (Post post : posts) {
1113 knownPosts.add(post.getId());
1116 synchronized (newReplies) {
1117 for (Reply reply : replies) {
1118 knownReplies.add(reply.getId());
1124 * Saves the given Sone. This will persist all local settings for the given
1125 * Sone, such as the friends list and similar, private options.
1130 public void saveSone(Sone sone) {
1131 if (!isLocalSone(sone)) {
1132 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1135 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1136 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1140 logger.log(Level.INFO, "Saving Sone: %s", sone);
1142 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1144 /* save Sone into configuration. */
1145 String sonePrefix = "Sone/" + sone.getId();
1146 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1147 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1150 Profile profile = sone.getProfile();
1151 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1152 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1153 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1154 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1155 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1156 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1159 int postCounter = 0;
1160 for (Post post : sone.getPosts()) {
1161 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1162 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1163 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1164 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1165 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1167 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1170 int replyCounter = 0;
1171 for (Reply reply : sone.getReplies()) {
1172 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1173 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1174 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1175 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1176 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1178 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1180 /* save post likes. */
1181 int postLikeCounter = 0;
1182 for (String postId : sone.getLikedPostIds()) {
1183 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1185 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1187 /* save reply likes. */
1188 int replyLikeCounter = 0;
1189 for (String replyId : sone.getLikedReplyIds()) {
1190 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1192 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1195 int friendCounter = 0;
1196 for (String friendId : sone.getFriends()) {
1197 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1199 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1201 logger.log(Level.INFO, "Sone %s saved.", sone);
1202 } catch (ConfigurationException ce1) {
1203 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1204 } catch (WebOfTrustException wote1) {
1205 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1210 * Creates a new post.
1213 * The Sone that creates the post
1215 * The text of the post
1216 * @return The created post
1218 public Post createPost(Sone sone, String text) {
1219 return createPost(sone, System.currentTimeMillis(), text);
1223 * Creates a new post.
1226 * The Sone that creates the post
1228 * The time of the post
1230 * The text of the post
1231 * @return The created post
1233 public Post createPost(Sone sone, long time, String text) {
1234 return createPost(sone, null, time, text);
1238 * Creates a new post.
1241 * The Sone that creates the post
1243 * The recipient Sone, or {@code null} if this post does not have
1246 * The text of the post
1247 * @return The created post
1249 public Post createPost(Sone sone, Sone recipient, String text) {
1250 return createPost(sone, recipient, System.currentTimeMillis(), 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 time of the post
1264 * The text of the post
1265 * @return The created post
1267 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1268 if (!isLocalSone(sone)) {
1269 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1272 Post post = new Post(sone, time, text);
1273 if (recipient != null) {
1274 post.setRecipient(recipient);
1276 synchronized (posts) {
1277 posts.put(post.getId(), post);
1279 synchronized (newPosts) {
1280 knownPosts.add(post.getId());
1288 * Deletes the given post.
1291 * The post to delete
1293 public void deletePost(Post post) {
1294 if (!isLocalSone(post.getSone())) {
1295 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1298 post.getSone().removePost(post);
1299 synchronized (posts) {
1300 posts.remove(post.getId());
1302 saveSone(post.getSone());
1306 * Marks the given post as known, if it is currently a new post (according
1307 * to {@link #isNewPost(String)}).
1310 * The post to mark as known
1312 public void markPostKnown(Post post) {
1313 synchronized (newPosts) {
1314 if (newPosts.remove(post.getId())) {
1315 knownPosts.add(post.getId());
1316 coreListenerManager.fireMarkPostKnown(post);
1322 * Creates a new reply.
1325 * The Sone that creates the reply
1327 * The post that this reply refers to
1329 * The text of the reply
1330 * @return The created reply
1332 public Reply createReply(Sone sone, Post post, String text) {
1333 return createReply(sone, post, System.currentTimeMillis(), text);
1337 * Creates a new reply.
1340 * The Sone that creates the reply
1342 * The post that this reply refers to
1344 * The time of the reply
1346 * The text of the reply
1347 * @return The created reply
1349 public Reply createReply(Sone sone, Post post, long time, String text) {
1350 if (!isLocalSone(sone)) {
1351 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1354 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1355 synchronized (replies) {
1356 replies.put(reply.getId(), reply);
1358 synchronized (newReplies) {
1359 knownReplies.add(reply.getId());
1361 sone.addReply(reply);
1367 * Deletes the given reply.
1370 * The reply to delete
1372 public void deleteReply(Reply reply) {
1373 Sone sone = reply.getSone();
1374 if (!isLocalSone(sone)) {
1375 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1378 synchronized (replies) {
1379 replies.remove(reply.getId());
1381 sone.removeReply(reply);
1386 * Marks the given reply as known, if it is currently a new reply (according
1387 * to {@link #isNewReply(String)}).
1390 * The reply to mark as known
1392 public void markReplyKnown(Reply reply) {
1393 synchronized (newReplies) {
1394 if (newReplies.remove(reply.getId())) {
1395 knownReplies.add(reply.getId());
1396 coreListenerManager.fireMarkReplyKnown(reply);
1404 public void start() {
1405 loadConfiguration();
1411 public void stop() {
1412 synchronized (localSones) {
1413 for (SoneInserter soneInserter : soneInserters.values()) {
1414 soneInserter.stop();
1417 saveConfiguration();
1422 * Saves the current options.
1424 public void saveConfiguration() {
1425 /* store the options first. */
1427 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1428 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1429 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1430 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1432 /* save known Sones. */
1433 int soneCounter = 0;
1434 synchronized (newSones) {
1435 for (String knownSoneId : knownSones) {
1436 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1438 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1441 /* save known posts. */
1442 int postCounter = 0;
1443 synchronized (newPosts) {
1444 for (String knownPostId : knownPosts) {
1445 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1447 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1450 /* save known replies. */
1451 int replyCounter = 0;
1452 synchronized (newReplies) {
1453 for (String knownReplyId : knownReplies) {
1454 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1456 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1460 configuration.save();
1462 } catch (ConfigurationException ce1) {
1463 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1472 * Loads the configuration.
1474 @SuppressWarnings("unchecked")
1475 private void loadConfiguration() {
1476 /* create options. */
1477 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1480 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1481 SoneInserter.setInsertionDelay(newValue);
1485 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1486 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1487 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1489 /* read options from configuration. */
1490 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1491 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1492 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1493 options.getBooleanOption("ClearOnNextRestart").set(null);
1494 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1495 if (clearConfiguration) {
1496 /* stop loading the configuration. */
1500 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1501 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1503 /* load known Sones. */
1504 int soneCounter = 0;
1506 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1507 if (knownSoneId == null) {
1510 synchronized (newSones) {
1511 knownSones.add(knownSoneId);
1515 /* load known posts. */
1516 int postCounter = 0;
1518 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1519 if (knownPostId == null) {
1522 synchronized (newPosts) {
1523 knownPosts.add(knownPostId);
1527 /* load known replies. */
1528 int replyCounter = 0;
1530 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1531 if (knownReplyId == null) {
1534 synchronized (newReplies) {
1535 knownReplies.add(knownReplyId);
1542 * Generate a Sone URI from the given URI and latest edition.
1545 * The URI to derive the Sone URI from
1546 * @return The derived URI
1548 private FreenetURI getSoneUri(String uriString) {
1550 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1552 } catch (MalformedURLException mue1) {
1553 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1559 // INTERFACE IdentityListener
1566 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1567 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1568 if (ownIdentity.hasContext("Sone")) {
1569 addLocalSone(ownIdentity);
1577 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1578 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1585 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1586 logger.log(Level.FINEST, "Adding Identity: " + identity);
1587 addRemoteSone(identity);
1594 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1595 new Thread(new Runnable() {
1598 @SuppressWarnings("synthetic-access")
1600 Sone sone = getRemoteSone(identity.getId());
1601 soneDownloader.fetchSone(sone);
1610 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {