Store friend Sones as strings, not as Sone objects.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
index 284c6fb..450e996 100644 (file)
@@ -32,6 +32,7 @@ import net.pterodactylus.sone.core.Options.DefaultOption;
 import net.pterodactylus.sone.core.Options.Option;
 import net.pterodactylus.sone.core.Options.OptionWatcher;
 import net.pterodactylus.sone.data.Post;
+import net.pterodactylus.sone.data.Profile;
 import net.pterodactylus.sone.data.Reply;
 import net.pterodactylus.sone.data.Sone;
 import net.pterodactylus.sone.freenet.wot.Identity;
@@ -105,6 +106,13 @@ public class Core implements IdentityListener {
        /* synchronize access on this on itself. */
        private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
 
+       /** All new Sones. */
+       private Set<String> newSones = new HashSet<String>();
+
+       /** All known Sones. */
+       /* synchronize access on {@link #newSones}. */
+       private Set<String> knownSones = new HashSet<String>();
+
        /** All posts. */
        private Map<String, Post> posts = new HashMap<String, Post>();
 
@@ -199,12 +207,39 @@ public class Core implements IdentityListener {
         *         Sone
         */
        public Sone getSone(String id) {
-               Sone sone = getRemoteSone(id);
-               if (sone != null) {
-                       return sone;
+               return getSone(id, true);
+       }
+
+       /**
+        * Returns the Sone with the given ID, regardless whether it’s local or
+        * remote.
+        *
+        * @param id
+        *            The ID of the Sone to get
+        * @param create
+        *            {@code true} to create a new Sone if none exists,
+        *            {@code false} to return {@code null} if a Sone with the given
+        *            ID does not exist
+        * @return The Sone with the given ID, or {@code null} if there is no such
+        *         Sone
+        */
+       public Sone getSone(String id, boolean create) {
+               if (isLocalSone(id)) {
+                       return getLocalSone(id);
                }
-               sone = getLocalSone(id);
-               return sone;
+               return getRemoteSone(id, create);
+       }
+
+       /**
+        * Checks whether the core knows a Sone with the given ID.
+        *
+        * @param id
+        *            The ID of the Sone
+        * @return {@code true} if there is a Sone with the given ID, {@code false}
+        *         otherwise
+        */
+       public boolean hasSone(String id) {
+               return isLocalSone(id) || isRemoteSone(id);
        }
 
        /**
@@ -221,6 +256,20 @@ public class Core implements IdentityListener {
        }
 
        /**
+        * Returns whether the given ID is the ID of a local Sone.
+        *
+        * @param id
+        *            The Sone ID to check for its locality
+        * @return {@code true} if the given ID is a local Sone, {@code false}
+        *         otherwise
+        */
+       public boolean isLocalSone(String id) {
+               synchronized (localSones) {
+                       return localSones.containsKey(id);
+               }
+       }
+
+       /**
         * Returns all local Sones.
         *
         * @return All local Sones
@@ -236,11 +285,16 @@ public class Core implements IdentityListener {
         *
         * @param id
         *            The ID of the Sone to get
-        * @return The Sone, or {@code null} if there is no Sone with the given ID
+        * @return The Sone with the given ID
         */
        public Sone getLocalSone(String id) {
                synchronized (localSones) {
-                       return localSones.get(id);
+                       Sone sone = localSones.get(id);
+                       if (sone == null) {
+                               sone = new Sone(id);
+                               localSones.put(id, sone);
+                       }
+                       return sone;
                }
        }
 
@@ -260,11 +314,30 @@ public class Core implements IdentityListener {
         *
         * @param id
         *            The ID of the remote Sone to get
-        * @return The Sone, or {@code null} if there is no such Sone
+        * @return The Sone with the given ID
         */
        public Sone getRemoteSone(String id) {
+               return getRemoteSone(id, true);
+       }
+
+       /**
+        * Returns the remote Sone with the given ID.
+        *
+        * @param id
+        *            The ID of the remote Sone to get
+        * @param create
+        *            {@code true} to always create a Sone, {@code false} to return
+        *            {@code null} if no Sone with the given ID exists
+        * @return The Sone with the given ID
+        */
+       public Sone getRemoteSone(String id, boolean create) {
                synchronized (remoteSones) {
-                       return remoteSones.get(id);
+                       Sone sone = remoteSones.get(id);
+                       if ((sone == null) && create) {
+                               sone = new Sone(id);
+                               remoteSones.put(id, sone);
+                       }
+                       return sone;
                }
        }
 
@@ -283,6 +356,37 @@ public class Core implements IdentityListener {
        }
 
        /**
+        * Returns whether the Sone with the given ID is a remote Sone.
+        *
+        * @param id
+        *            The ID of the Sone to check
+        * @return {@code true} if the Sone with the given ID is a remote Sone,
+        *         {@code false} otherwise
+        */
+       public boolean isRemoteSone(String id) {
+               synchronized (remoteSones) {
+                       return remoteSones.containsKey(id);
+               }
+       }
+
+       /**
+        * Returns whether the given Sone is a new Sone. After this check, the Sone
+        * is marked as known, i.e. a second call with the same parameters will
+        * always yield {@code false}.
+        *
+        * @param sone
+        *            The sone to check for
+        * @return {@code true} if the given Sone is new, false otherwise
+        */
+       public boolean isNewSone(Sone sone) {
+               synchronized (newSones) {
+                       boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
+                       knownSones.add(sone.getId());
+                       return isNew;
+               }
+       }
+
+       /**
         * Returns the post with the given ID.
         *
         * @param postId
@@ -291,7 +395,12 @@ public class Core implements IdentityListener {
         */
        public Post getPost(String postId) {
                synchronized (posts) {
-                       return posts.get(postId);
+                       Post post = posts.get(postId);
+                       if (post == null) {
+                               post = new Post(postId);
+                               posts.put(postId, post);
+                       }
+                       return post;
                }
        }
 
@@ -304,7 +413,12 @@ public class Core implements IdentityListener {
         */
        public Reply getReply(String replyId) {
                synchronized (replies) {
-                       return replies.get(replyId);
+                       Reply reply = replies.get(replyId);
+                       if (reply == null) {
+                               reply = new Reply(replyId);
+                               replies.put(replyId, reply);
+                       }
+                       return reply;
                }
        }
 
@@ -356,7 +470,7 @@ public class Core implements IdentityListener {
        public Set<Sone> getLikes(Reply reply) {
                Set<Sone> sones = new HashSet<Sone>();
                for (Sone sone : getSones()) {
-                       if (sone.getLikedPostIds().contains(reply.getId())) {
+                       if (sone.getLikedReplyIds().contains(reply.getId())) {
                                sones.add(sone);
                        }
                }
@@ -403,18 +517,30 @@ public class Core implements IdentityListener {
                        return null;
                }
                synchronized (localSones) {
-                       if (localSones.containsKey(ownIdentity.getId())) {
-                               logger.log(Level.FINE, "Tried to add known local Sone: %s", ownIdentity);
-                               return localSones.get(ownIdentity.getId());
+                       final Sone sone;
+                       try {
+                               sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
+                               sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
+                       } catch (MalformedURLException mue1) {
+                               logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
+                               return null;
                        }
-                       String latestEdition = ownIdentity.getProperty("Sone.LatestEdition");
-                       Sone sone = new Sone(ownIdentity).setInsertUri(getSoneUri(ownIdentity.getInsertUri(), latestEdition)).setRequestUri(getSoneUri(ownIdentity.getRequestUri(), latestEdition));
                        /* TODO - load posts ’n stuff */
                        localSones.put(ownIdentity.getId(), sone);
                        SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
                        soneInserters.put(sone, soneInserter);
                        soneInserter.start();
                        setSoneStatus(sone, SoneStatus.idle);
+                       loadSone(sone);
+                       new Thread(new Runnable() {
+
+                               @Override
+                               @SuppressWarnings("synthetic-access")
+                               public void run() {
+                                       soneDownloader.fetchSone(sone);
+                               }
+
+                       }, "Sone Downloader").start();
                        return sone;
                }
        }
@@ -449,15 +575,27 @@ public class Core implements IdentityListener {
                        return null;
                }
                synchronized (remoteSones) {
-                       if (remoteSones.containsKey(identity.getId())) {
-                               logger.log(Level.FINE, "Identity already exists: %s", identity);
-                               return remoteSones.get(identity.getId());
+                       final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
+                       boolean newSone = sone.getRequestUri() == null;
+                       sone.setRequestUri(getSoneUri(identity.getRequestUri()));
+                       sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
+                       if (newSone) {
+                               synchronized (newSones) {
+                                       newSones.add(sone.getId());
+                               }
                        }
-                       Sone sone = new Sone(identity);
-                       sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition")));
                        remoteSones.put(identity.getId(), sone);
                        soneDownloader.addSone(sone);
-                       setSoneStatus(sone, SoneStatus.idle);
+                       setSoneStatus(sone, SoneStatus.unknown);
+                       new Thread(new Runnable() {
+
+                               @Override
+                               @SuppressWarnings("synthetic-access")
+                               public void run() {
+                                       soneDownloader.fetchSone(sone);
+                               }
+
+                       }, "Sone Downloader").start();
                        return sone;
                }
        }
@@ -498,9 +636,9 @@ public class Core implements IdentityListener {
                                storedSone.setReplies(sone.getReplies());
                                storedSone.setLikePostIds(sone.getLikedPostIds());
                                storedSone.setLikeReplyIds(sone.getLikedReplyIds());
-                               storedSone.updateUris(sone.getRequestUri().getEdition());
+                               storedSone.setLatestEdition(sone.getRequestUri().getEdition());
+                               storedSone.setModificationCounter(0);
                        }
-                       saveSone(storedSone);
                }
        }
 
@@ -523,9 +661,129 @@ public class Core implements IdentityListener {
                                return;
                        }
                        localSones.remove(sone.getId());
-                       soneInserters.remove(sone.getId()).stop();
+                       soneInserters.remove(sone).stop();
                }
                identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
+               identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
+               try {
+                       configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
+               } catch (ConfigurationException ce1) {
+                       logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
+               }
+       }
+
+       /**
+        * Loads and updates the given Sone from the configuration. If any error is
+        * encountered, loading is aborted and the given Sone is not changed.
+        *
+        * @param sone
+        *            The Sone to load and update
+        */
+       public void loadSone(Sone sone) {
+               if (!isLocalSone(sone)) {
+                       logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
+                       return;
+               }
+
+               /* load Sone. */
+               String sonePrefix = "Sone/" + sone.getId();
+               Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
+               if (soneTime == null) {
+                       logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
+                       return;
+               }
+               long soneModificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
+
+               /* load profile. */
+               Profile profile = new Profile();
+               profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
+               profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
+               profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
+               profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
+               profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
+               profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
+
+               /* load posts. */
+               Set<Post> posts = new HashSet<Post>();
+               while (true) {
+                       String postPrefix = sonePrefix + "/Posts/" + posts.size();
+                       String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
+                       if (postId == null) {
+                               break;
+                       }
+                       long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
+                       String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
+                       if ((postTime == 0) || (postText == null)) {
+                               logger.log(Level.WARNING, "Invalid post found, aborting load!");
+                               return;
+                       }
+                       posts.add(getPost(postId).setSone(sone).setTime(postTime).setText(postText));
+               }
+
+               /* load replies. */
+               Set<Reply> replies = new HashSet<Reply>();
+               while (true) {
+                       String replyPrefix = sonePrefix + "/Replies/" + replies.size();
+                       String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
+                       if (replyId == null) {
+                               break;
+                       }
+                       String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
+                       long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
+                       String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
+                       if ((postId == null) || (replyTime == 0) || (replyText == null)) {
+                               logger.log(Level.WARNING, "Invalid reply found, aborting load!");
+                               return;
+                       }
+                       replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
+               }
+
+               /* load post likes. */
+               Set<String> likedPostIds = new HashSet<String>();
+               while (true) {
+                       String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
+                       if (likedPostId == null) {
+                               break;
+                       }
+                       likedPostIds.add(likedPostId);
+               }
+
+               /* load reply likes. */
+               Set<String> likedReplyIds = new HashSet<String>();
+               while (true) {
+                       String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
+                       if (likedReplyId == null) {
+                               break;
+                       }
+                       likedReplyIds.add(likedReplyId);
+               }
+
+               /* load friends. */
+               Set<String> friends = new HashSet<String>();
+               while (true) {
+                       String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
+                       if (friendId == null) {
+                               break;
+                       }
+                       friends.add(friendId);
+               }
+
+               /* if we’re still here, Sone was loaded successfully. */
+               synchronized (sone) {
+                       sone.setTime(soneTime);
+                       sone.setProfile(profile);
+                       sone.setPosts(posts);
+                       sone.setReplies(replies);
+                       sone.setLikePostIds(likedPostIds);
+                       sone.setLikeReplyIds(likedReplyIds);
+                       sone.setFriends(friends);
+                       sone.setModificationCounter(soneModificationCounter);
+               }
+               synchronized (newSones) {
+                       for (String friend : friends) {
+                               knownSones.add(friend);
+                       }
+               }
        }
 
        /**
@@ -538,8 +796,76 @@ public class Core implements IdentityListener {
        public void saveSone(Sone sone) {
                if (!isLocalSone(sone)) {
                        logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
+                       return;
+               }
+               if (!(sone.getIdentity() instanceof OwnIdentity)) {
+                       logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
+                       return;
+               }
+
+               logger.log(Level.INFO, "Saving Sone: %s", sone);
+               identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
+               try {
+                       /* save Sone into configuration. */
+                       String sonePrefix = "Sone/" + sone.getId();
+                       configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
+                       configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
+
+                       /* save profile. */
+                       Profile profile = sone.getProfile();
+                       configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
+                       configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
+                       configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
+                       configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
+                       configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
+                       configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
+
+                       /* save posts. */
+                       int postCounter = 0;
+                       for (Post post : sone.getPosts()) {
+                               String postPrefix = sonePrefix + "/Posts/" + postCounter++;
+                               configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
+                               configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
+                               configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
+                       }
+                       configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
+
+                       /* save replies. */
+                       int replyCounter = 0;
+                       for (Reply reply : sone.getReplies()) {
+                               String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
+                               configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
+                               configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
+                               configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
+                               configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
+                       }
+                       configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
+
+                       /* save post likes. */
+                       int postLikeCounter = 0;
+                       for (String postId : sone.getLikedPostIds()) {
+                               configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
+                       }
+                       configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
+
+                       /* save reply likes. */
+                       int replyLikeCounter = 0;
+                       for (String replyId : sone.getLikedReplyIds()) {
+                               configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
+                       }
+                       configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
+
+                       /* save friends. */
+                       int friendCounter = 0;
+                       for (String friend : sone.getFriends()) {
+                               configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(friend);
+                       }
+                       configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
+
+                       logger.log(Level.INFO, "Sone %s saved.", sone);
+               } catch (ConfigurationException ce1) {
+                       logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
                }
-               /* TODO - implement saving. */
        }
 
        /**
@@ -706,6 +1032,17 @@ public class Core implements IdentityListener {
 
                options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
 
+               /* load known Sones. */
+               int soneCounter = 0;
+               while (true) {
+                       String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
+                       if (knownSoneId == null) {
+                               break;
+                       }
+                       synchronized (newSones) {
+                               knownSones.add(knownSoneId);
+                       }
+               }
        }
 
        /**
@@ -717,6 +1054,16 @@ public class Core implements IdentityListener {
                        configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
                        configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
                        configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
+
+                       /* save known Sones. */
+                       int soneCounter = 0;
+                       synchronized (newSones) {
+                               for (String knownSoneId : knownSones) {
+                                       configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
+                               }
+                               configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
+                       }
+
                } catch (ConfigurationException ce1) {
                        logger.log(Level.SEVERE, "Could not store configuration!", ce1);
                }
@@ -727,13 +1074,11 @@ public class Core implements IdentityListener {
         *
         * @param uriString
         *            The URI to derive the Sone URI from
-        * @param latestEditionString
-        *            The latest edition as a {@link String}, or {@code null}
         * @return The derived URI
         */
-       private FreenetURI getSoneUri(String uriString, String latestEditionString) {
+       private FreenetURI getSoneUri(String uriString) {
                try {
-                       FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0));
+                       FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
                        return uri;
                } catch (MalformedURLException mue1) {
                        logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
@@ -761,7 +1106,7 @@ public class Core implements IdentityListener {
         */
        @Override
        public void ownIdentityRemoved(OwnIdentity ownIdentity) {
-               /* TODO */
+               logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
        }
 
        /**
@@ -777,8 +1122,16 @@ public class Core implements IdentityListener {
         * {@inheritDoc}
         */
        @Override
-       public void identityUpdated(Identity identity) {
-               /* TODO */
+       public void identityUpdated(final Identity identity) {
+               new Thread(new Runnable() {
+
+                       @Override
+                       @SuppressWarnings("synthetic-access")
+                       public void run() {
+                               Sone sone = getRemoteSone(identity.getId());
+                               soneDownloader.fetchSone(sone);
+                       }
+               }).start();
        }
 
        /**