Store request URI in yet unknown Sones when parsing.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
index 8563187..b838216 100644 (file)
 package net.pterodactylus.sone.core;
 
 import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
+import java.util.UUID;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
+import net.pterodactylus.sone.core.SoneException.Type;
+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.util.config.Configuration;
+import net.pterodactylus.util.config.ConfigurationException;
 import net.pterodactylus.util.logging.Logging;
 import net.pterodactylus.util.service.AbstractService;
-import net.pterodactylus.util.text.StringEscaper;
-import net.pterodactylus.util.text.TextException;
+import freenet.client.FetchResult;
 import freenet.keys.FreenetURI;
 
 /**
@@ -49,9 +59,26 @@ public class Core extends AbstractService {
        /** Interface to freenet. */
        private FreenetInterface freenetInterface;
 
+       /** The Sone downloader. */
+       private SoneDownloader soneDownloader;
+
        /** The local Sones. */
        private final Set<Sone> localSones = new HashSet<Sone>();
 
+       /** Sone inserters. */
+       private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
+
+       /* various caches follow here. */
+
+       /** Cache for all known Sones. */
+       private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
+
+       /** Cache for all known posts. */
+       private final Map<String, Post> postCache = new HashMap<String, Post>();
+
+       /** Cache for all known replies. */
+       private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
+
        /**
         * Creates a new core.
         */
@@ -84,13 +111,282 @@ public class Core extends AbstractService {
         */
        public Core freenetInterface(FreenetInterface freenetInterface) {
                this.freenetInterface = freenetInterface;
+               soneDownloader = new SoneDownloader(this, freenetInterface);
+               soneDownloader.start();
                return this;
        }
 
+       /**
+        * Returns the local Sones.
+        *
+        * @return The local Sones
+        */
+       public Set<Sone> getSones() {
+               return Collections.unmodifiableSet(localSones);
+       }
+
+       /**
+        * Returns the Sone with the given ID, or an empty Sone that has been
+        * initialized with the given ID.
+        *
+        * @param soneId
+        *            The ID of the Sone
+        * @return The Sone
+        */
+       public Sone getSone(String soneId) {
+               if (!soneCache.containsKey(soneId)) {
+                       Sone sone = new Sone(soneId);
+                       soneCache.put(soneId, sone);
+               }
+               return soneCache.get(soneId);
+       }
+
+       /**
+        * Returns all known sones.
+        *
+        * @return All known sones
+        */
+       public Collection<Sone> getKnownSones() {
+               return soneCache.values();
+       }
+
+       /**
+        * Creates a new post.
+        *
+        * @param sone
+        *            The sone that creates the post
+        * @param text
+        *            The text of the post
+        * @return The created post
+        */
+       public Post createPost(Sone sone, String text) {
+               return createPost(sone, System.currentTimeMillis(), text);
+       }
+
+       /**
+        * Creates a new post.
+        *
+        * @param sone
+        *            The Sone that creates the post
+        * @param time
+        *            The time of the post
+        * @param text
+        *            The text of the post
+        * @return The created post
+        */
+       public Post createPost(Sone sone, long time, String text) {
+               Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
+               sone.addPost(post);
+               return post;
+       }
+
+       /**
+        * Creates a reply.
+        *
+        * @param sone
+        *            The Sone that posts the reply
+        * @param post
+        *            The post the reply refers to
+        * @param text
+        *            The text of the reply
+        * @return The created reply
+        */
+       public Reply createReply(Sone sone, Post post, String text) {
+               return createReply(sone, post, System.currentTimeMillis(), text);
+       }
+
+       /**
+        * Creates a reply.
+        *
+        * @param sone
+        *            The Sone that posts the reply
+        * @param post
+        *            The post the reply refers to
+        * @param time
+        *            The time of the post
+        * @param text
+        *            The text of the reply
+        * @return The created reply
+        */
+       public Reply createReply(Sone sone, Post post, long time, String text) {
+               Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
+               sone.addReply(reply);
+               return reply;
+       }
+
        //
        // ACTIONS
        //
 
+       /**
+        * Adds a Sone to watch for updates. The Sone needs to be completely
+        * initialized.
+        *
+        * @param sone
+        *            The Sone to watch for updates
+        */
+       public void addSone(Sone sone) {
+               soneCache.put(sone.getId(), sone);
+               soneDownloader.addSone(sone);
+       }
+
+       /**
+        * Adds the given Sone.
+        *
+        * @param sone
+        *            The Sone to add
+        */
+       public void addLocalSone(Sone sone) {
+               if (localSones.add(sone)) {
+                       SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
+                       soneInserter.start();
+                       soneInserters.put(sone, soneInserter);
+               }
+       }
+
+       /**
+        * Creates a new Sone at a random location.
+        *
+        * @param name
+        *            The name of the Sone
+        * @return The created Sone
+        * @throws SoneException
+        *             if a Sone error occurs
+        */
+       public Sone createSone(String name) throws SoneException {
+               return createSone(name, null, null);
+       }
+
+       /**
+        * Creates a new Sone at the given location. If one of {@code requestUri} or
+        * {@code insertUrI} is {@code null}, the Sone is created at a random
+        * location.
+        *
+        * @param name
+        *            The name of the Sone
+        * @param requestUri
+        *            The request URI of the Sone, or {@link NullPointerException}
+        *            to create a Sone at a random location
+        * @param insertUri
+        *            The insert URI of the Sone, or {@code null} to create a Sone
+        *            at a random location
+        * @return The created Sone
+        * @throws SoneException
+        *             if a Sone error occurs
+        */
+       public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
+               if ((name == null) || (name.trim().length() == 0)) {
+                       throw new SoneException(Type.INVALID_SONE_NAME);
+               }
+               String finalRequestUri;
+               String finalInsertUri;
+               if ((requestUri == null) || (insertUri == null)) {
+                       String[] keyPair = freenetInterface.generateKeyPair();
+                       finalRequestUri = keyPair[0];
+                       finalInsertUri = keyPair[1];
+               } else {
+                       finalRequestUri = requestUri;
+                       finalInsertUri = insertUri;
+               }
+               Sone sone;
+               try {
+                       logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
+                       sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
+                       sone.setProfile(new Profile());
+                       /* set modification counter to 1 so it is inserted immediately. */
+                       sone.setModificationCounter(1);
+                       addLocalSone(sone);
+               } catch (MalformedURLException mue1) {
+                       throw new SoneException(Type.INVALID_URI);
+               }
+               return sone;
+       }
+
+       /**
+        * Loads the Sone from the given request URI.
+        *
+        * @param requestUri
+        *            The request URI to load the Sone from
+        */
+       public void loadSone(String requestUri) {
+               try {
+                       FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
+                       FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
+                       soneDownloader.parseSone(null, fetchResult, realRequestUri);
+               } catch (MalformedURLException mue1) {
+                       logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
+               }
+       }
+
+       /**
+        * Deletes the given Sone from this plugin instance.
+        *
+        * @param sone
+        *            The sone to delete
+        */
+       public void deleteSone(Sone sone) {
+               SoneInserter soneInserter = soneInserters.remove(sone);
+               soneInserter.stop();
+               localSones.remove(sone);
+       }
+
+       /**
+        * Returns the post with the given ID. If no post exists yet with the given
+        * ID, a new post is returned.
+        *
+        * @param postId
+        *            The ID of the post
+        * @return The post
+        */
+       public Post getPost(String postId) {
+               if (!postCache.containsKey(postId)) {
+                       postCache.put(postId, new Post(postId));
+               }
+               return postCache.get(postId);
+       }
+
+       /**
+        * Returns the reply with the given ID. If no reply exists yet with the
+        * given ID, a new reply is returned.
+        *
+        * @param replyId
+        *            The ID of the reply
+        * @return The reply
+        */
+       public Reply getReply(String replyId) {
+               if (!replyCache.containsKey(replyId)) {
+                       replyCache.put(replyId, new Reply(replyId));
+               }
+               return replyCache.get(replyId);
+       }
+
+       /**
+        * Gets all replies to the given post, sorted by date, oldest first.
+        *
+        * @param post
+        *            The post the replies refer to
+        * @return The sorted list of replies for the post
+        */
+       public List<Reply> getReplies(Post post) {
+               List<Reply> replies = new ArrayList<Reply>();
+               for (Reply reply : replyCache.values()) {
+                       if (reply.getPost().equals(post)) {
+                               replies.add(reply);
+                       }
+               }
+               Collections.sort(replies, new Comparator<Reply>() {
+
+                       /**
+                        * {@inheritDoc}
+                        */
+                       @Override
+                       public int compare(Reply leftReply, Reply rightReply) {
+                               return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
+                       }
+               });
+               return replies;
+       }
+
        //
        // SERVICE METHODS
        //
@@ -103,6 +399,19 @@ public class Core extends AbstractService {
                loadConfiguration();
        }
 
+       /**
+        * {@inheritDoc}
+        */
+       @Override
+       protected void serviceStop() {
+               soneDownloader.stop();
+               /* stop all Sone inserters. */
+               for (SoneInserter soneInserter : soneInserters.values()) {
+                       soneInserter.stop();
+               }
+               saveConfiguration();
+       }
+
        //
        // PRIVATE METHODS
        //
@@ -113,31 +422,140 @@ public class Core extends AbstractService {
        private void loadConfiguration() {
                logger.entering(Core.class.getName(), "loadConfiguration()");
 
-               /* get names of all local Sones. */
-               String allSoneNamesString = configuration.getStringValue("Sone/Names").getValue(null);
-               if (allSoneNamesString == null) {
-                       allSoneNamesString = "";
-               }
-               List<String> allSoneNames;
-               try {
-                       allSoneNames = StringEscaper.parseLine(allSoneNamesString);
-               } catch (TextException te1) {
-                       logger.log(Level.WARNING, "Could not parse Sone names: “" + allSoneNamesString + "”", te1);
-                       allSoneNames = Collections.emptyList();
-               }
-
                /* parse local Sones. */
-               for (String soneName : allSoneNames) {
-                       String insertUri = configuration.getStringValue("Sone/Name." + soneName + "/InsertURI").getValue(null);
-                       String requestUri = configuration.getStringValue("Sone/Name." + soneName + "/RequestURI").getValue(null);
+               logger.log(Level.INFO, "Loading Sones…");
+               int soneId = 0;
+               do {
+                       String sonePrefix = "Sone/Sone." + soneId++;
+                       String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
+                       if (id == null) {
+                               break;
+                       }
+                       String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
+                       String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
+                       String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
+                       long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
+                       String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
+                       String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
+                       String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
                        try {
-                               localSones.add(new Sone(new FreenetURI(requestUri), new FreenetURI(insertUri)));
+                               Profile profile = new Profile();
+                               profile.setFirstName(firstName);
+                               profile.setMiddleName(middleName);
+                               profile.setLastName(lastName);
+                               Sone sone = getSone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
+                               sone.setProfile(profile);
+                               int postId = 0;
+                               do {
+                                       String postPrefix = sonePrefix + "/Post." + postId++;
+                                       id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
+                                       if (id == null) {
+                                               break;
+                                       }
+                                       long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
+                                       String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
+                                       Post post = getPost(id).setSone(sone).setTime(time).setText(text);
+                                       sone.addPost(post);
+                               } while (true);
+                               int replyCounter = 0;
+                               do {
+                                       String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
+                                       String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
+                                       if (replyId == null) {
+                                               break;
+                                       }
+                                       Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
+                                       long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
+                                       String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
+                                       Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
+                                       sone.addReply(reply);
+                               } while (true);
+
+                               /* load friends. */
+                               int friendCounter = 0;
+                               while (true) {
+                                       String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
+                                       String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
+                                       if (friendId == null) {
+                                               break;
+                                       }
+                                       Sone friendSone = getSone(friendId);
+                                       String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
+                                       String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
+                                       friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
+                                       soneDownloader.addSone(friendSone);
+                                       sone.addFriend(friendSone);
+                               }
+
+                               sone.setModificationCounter(modificationCounter);
+                               addLocalSone(sone);
                        } catch (MalformedURLException mue1) {
                                logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
                        }
-               }
+               } while (true);
+               logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
 
                logger.exiting(Core.class.getName(), "loadConfiguration()");
        }
 
+       /**
+        * Saves the configuraiton.
+        */
+       private void saveConfiguration() {
+               Set<Sone> sones = getSones();
+               logger.log(Level.INFO, "Storing %d Sones…", sones.size());
+               try {
+                       /* store all Sones. */
+                       int soneId = 0;
+                       for (Sone sone : localSones) {
+                               String sonePrefix = "Sone/Sone." + soneId++;
+                               configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
+                               configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
+                               configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
+                               configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
+                               configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
+                               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());
+                               int postId = 0;
+                               for (Post post : sone.getPosts()) {
+                                       String postPrefix = sonePrefix + "/Post." + postId++;
+                                       configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
+                                       configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
+                                       configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
+                               }
+                               /* write null ID as terminator. */
+                               configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
+
+                               int replyId = 0;
+                               for (Reply reply : sone.getReplies()) {
+                                       String replyPrefix = sonePrefix + "/Reply." + replyId++;
+                                       configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
+                                       configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
+                                       configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
+                                       configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
+                               }
+                               /* write null ID as terminator. */
+                               configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
+
+                               int friendId = 0;
+                               for (Sone friend : sone.getFriends()) {
+                                       String friendPrefix = sonePrefix + "/Friend." + friendId++;
+                                       configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
+                                       configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
+                                       configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
+                               }
+                               /* write null ID as terminator. */
+                               configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
+
+                       }
+                       /* write null ID as terminator. */
+                       configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
+
+               } catch (ConfigurationException ce1) {
+                       logger.log(Level.WARNING, "Could not store configuration!", ce1);
+               }
+       }
+
 }