update nikiroo-utils, remote lib errors need some work
[fanfix.git] / src / be / nikiroo / fanfix / library / RemoteLibraryServer.java
index d62b41b0283e5b2fe49abe2a47059e98ce8e6bca..0893746239292297aeb1091aa51780351288b749 100644 (file)
@@ -6,6 +6,8 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
+import javax.net.ssl.SSLException;
+
 import be.nikiroo.fanfix.Instance;
 import be.nikiroo.fanfix.data.Chapter;
 import be.nikiroo.fanfix.data.MetaData;
@@ -14,7 +16,6 @@ import be.nikiroo.fanfix.data.Story;
 import be.nikiroo.utils.Progress;
 import be.nikiroo.utils.Progress.ProgressListener;
 import be.nikiroo.utils.StringUtils;
-import be.nikiroo.utils.Version;
 import be.nikiroo.utils.serial.server.ConnectActionServerObject;
 import be.nikiroo.utils.serial.server.ServerObject;
 
@@ -24,27 +25,17 @@ import be.nikiroo.utils.serial.server.ServerObject;
  * The available commands are given as arrays of objects (first item is the
  * command, the rest are the arguments).
  * <p>
- * All commands, including PING, will first return a random value to you that
- * you must hash with your key and return before processing the rest; if the
- * value is OK, it will return "true", if not, it will return NULL and stop the
- * connection.
- * <p>
- * BTW: this system <b>is by no means secure</b>. It is just slightly
- * obfuscated, and operate on clear text (because Google decided not to support
- * anonymous SSL exchanges on Android, and the main use case for this server is
- * Android).
  * <ul>
  * <li>PING: will return PONG if the key is accepted</li>
  * <li>GET_METADATA *: will return the metadata of all the stories in the
  * library (array)</li> *
- * <li>GET_METADATA [luid]: will return the metadata of the story of LUID
- * luid</li>
+ * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
  * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
  * not)</li>
  * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
  * command) with the given LUID, then return the LUID</li>
- * <li>IMPORT [url]: save the story found at the given URL, then return the
- * LUID</li>
+ * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
+ * </li>
  * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
  * <li>GET_COVER [luid]: return the cover of the story</li>
  * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
@@ -59,8 +50,6 @@ import be.nikiroo.utils.serial.server.ServerObject;
  * @author niki
  */
 public class RemoteLibraryServer extends ServerObject {
-       private final String key;
-
        /**
         * Create a new remote server (will not be active until
         * {@link RemoteLibraryServer#start()} is called).
@@ -74,22 +63,20 @@ public class RemoteLibraryServer extends ServerObject {
         *             in case of I/O error
         */
        public RemoteLibraryServer(String key, int port) throws IOException {
-               super("Fanfix remote library", port, false);
-               this.key = key;
-
+               super("Fanfix remote library", port, key);
                setTraceHandler(Instance.getTraceHandler());
        }
 
        @Override
-       protected Object onRequest(ConnectActionServerObject action,
-                       Version clientVersion, Object data) throws Exception {
+       protected Object onRequest(ConnectActionServerObject action, Object data)
+                       throws Exception {
                long start = new Date().getTime();
 
                String command = "";
                Object[] args = new Object[0];
                if (data instanceof Object[]) {
                        Object[] dataArray = (Object[]) data;
-                       if (dataArray.length >= 2) {
+                       if (dataArray.length > 0) {
                                command = "" + dataArray[0];
 
                                args = new Object[dataArray.length - 1];
@@ -103,29 +90,14 @@ public class RemoteLibraryServer extends ServerObject {
                for (Object arg : args) {
                        trace += arg + " ";
                }
-               getTraceHandler().trace(trace);
-
-               // Authentication:
-               String random = StringUtils.getMd5Hash(Double.toString(Math.random()));
-               action.send(random);
-               String answer = "";
-               try {
-                       answer += action.rec();
-               } catch (NullPointerException e) {
-                       return null;
-               }
-
-               if (answer.equals(RemoteLibrary.hashKey(key, random))) {
-                       action.send(true);
-               } else {
-                       getTraceHandler().trace("Key rejected.");
-                       return null;
-               }
+               System.out.println(trace);
 
                Object rep = doRequest(action, command, args);
 
-               getTraceHandler().trace(String.format("[>%s]: %d ms", command,
-                               (new Date().getTime() - start)));
+               String rec = StringUtils.formatNumber(action.getBytesReceived()) + "b";
+               String sent = StringUtils.formatNumber(action.getBytesSent()) + "b";
+               System.out.println(String.format("[>%s]: (%s sent, %s rec) in %d ms",
+                               command, sent, rec, (new Date().getTime() - start)));
 
                return rep;
        }
@@ -157,8 +129,8 @@ public class RemoteLibraryServer extends ServerObject {
                                return metas.toArray(new MetaData[] {});
                        }
 
-                       return new MetaData[] {
-                                       Instance.getLibrary().getInfo((String) args[0]) };
+                       return new MetaData[] { Instance.getLibrary().getInfo(
+                                       (String) args[0]) };
                } else if ("GET_STORY".equals(command)) {
                        MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
                        meta = meta.clone();
@@ -167,8 +139,8 @@ public class RemoteLibraryServer extends ServerObject {
                        action.send(meta);
                        action.rec();
 
-                       Story story = Instance.getLibrary().getStory((String) args[0],
-                                       null);
+                       Story story = Instance.getLibrary()
+                                       .getStory((String) args[0], null);
                        for (Object obj : breakStory(story)) {
                                action.send(obj);
                                action.rec();
@@ -189,8 +161,8 @@ public class RemoteLibraryServer extends ServerObject {
                        return story.getMeta().getLuid();
                } else if ("IMPORT".equals(command)) {
                        Progress pg = createPgForwarder(action);
-                       Story story = Instance.getLibrary().imprt(new URL((String) args[0]),
-                                       pg);
+                       Story story = Instance.getLibrary().imprt(
+                                       new URL((String) args[0]), pg);
                        forcePgDoneSent(pg);
                        return story.getMeta().getLuid();
                } else if ("DELETE_STORY".equals(command)) {
@@ -199,11 +171,11 @@ public class RemoteLibraryServer extends ServerObject {
                        return Instance.getLibrary().getCover((String) args[0]);
                } else if ("GET_CUSTOM_COVER".equals(command)) {
                        if ("SOURCE".equals(args[0])) {
-                               return Instance.getLibrary()
-                                               .getCustomSourceCover((String) args[1]);
+                               return Instance.getLibrary().getCustomSourceCover(
+                                               (String) args[1]);
                        } else if ("AUTHOR".equals(args[0])) {
-                               return Instance.getLibrary()
-                                               .getCustomAuthorCover((String) args[1]);
+                               return Instance.getLibrary().getCustomAuthorCover(
+                                               (String) args[1]);
                        } else {
                                return null;
                        }
@@ -229,7 +201,11 @@ public class RemoteLibraryServer extends ServerObject {
 
        @Override
        protected void onError(Exception e) {
-               getTraceHandler().error(e);
+               if (e instanceof SSLException) {
+                       System.out.println("[Client connection refused (bad key)]");
+               } else {
+                       getTraceHandler().error(e);
+               }
        }
 
        /**
@@ -324,8 +300,7 @@ public class RemoteLibraryServer extends ServerObject {
         * 
         * @return the {@link Progress}
         */
-       private static Progress createPgForwarder(
-                       final ConnectActionServerObject action) {
+       private Progress createPgForwarder(final ConnectActionServerObject action) {
                final Boolean[] isDoneForwarded = new Boolean[] { false };
                final Progress pg = new Progress() {
                        @Override
@@ -341,8 +316,9 @@ public class RemoteLibraryServer extends ServerObject {
                        public void progress(Progress progress, String name) {
                                int min = pg.getMin();
                                int max = pg.getMax();
-                               int relativeProgress = min + (int) Math
-                                               .round(pg.getRelativeProgress() * (max - min));
+                               int relativeProgress = min
+                                               + (int) Math.round(pg.getRelativeProgress()
+                                                               * (max - min));
 
                                // Do not re-send the same value twice over the wire,
                                // unless more than 2 seconds have elapsed (to maintain the
@@ -354,11 +330,10 @@ public class RemoteLibraryServer extends ServerObject {
                                        p[2] = relativeProgress;
 
                                        try {
-                                               action.send(
-                                                               new Integer[] { min, max, relativeProgress });
+                                               action.send(new Integer[] { min, max, relativeProgress });
                                                action.rec();
                                        } catch (Exception e) {
-                                               Instance.getTraceHandler().error(e);
+                                               getTraceHandler().error(e);
                                        }
 
                                        lastTime[0] = new Date().getTime();
@@ -372,14 +347,14 @@ public class RemoteLibraryServer extends ServerObject {
        }
 
        // with 30 seconds timeout
-       private static void forcePgDoneSent(Progress pg) {
+       private void forcePgDoneSent(Progress pg) {
                long start = new Date().getTime();
                pg.done();
                while (!pg.isDone() && new Date().getTime() - start < 30000) {
                        try {
                                Thread.sleep(100);
                        } catch (InterruptedException e) {
-                               Instance.getTraceHandler().error(e);
+                               getTraceHandler().error(e);
                        }
                }
        }