X-Git-Url: http://git.nikiroo.be/?a=blobdiff_plain;f=src%2Fbe%2Fnikiroo%2Fjvcard%2Fremote%2FSync.java;h=771798c353b651f3dd3d1a9243d118cfa7418a24;hb=02b341aa6dcd14dc311f6ea218e199f20e242f36;hp=dbf03242fb3e82083a6ef601ee50b3edb66ad975;hpb=a046fa49cdcaea2ce4eb9104387c66f915205f2d;p=jvcard.git diff --git a/src/be/nikiroo/jvcard/remote/Sync.java b/src/be/nikiroo/jvcard/remote/Sync.java index dbf0324..771798c 100644 --- a/src/be/nikiroo/jvcard/remote/Sync.java +++ b/src/be/nikiroo/jvcard/remote/Sync.java @@ -12,16 +12,20 @@ import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.security.InvalidParameterException; +import java.util.HashMap; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import be.nikiroo.jvcard.Card; +import be.nikiroo.jvcard.Contact; +import be.nikiroo.jvcard.Data; import be.nikiroo.jvcard.parsers.Format; -import be.nikiroo.jvcard.parsers.Parser; -import be.nikiroo.jvcard.remote.Command.Verb; +import be.nikiroo.jvcard.parsers.Vcard21Parser; import be.nikiroo.jvcard.resources.Bundles; -import be.nikiroo.jvcard.tui.StringUtils; +import be.nikiroo.jvcard.resources.StringUtils; /** * This class will synchronise {@link Card}s between a local instance an a @@ -32,7 +36,7 @@ import be.nikiroo.jvcard.tui.StringUtils; */ public class Sync { /** The time in ms after which we declare that 2 timestamps are different */ - static private final int GRACE_TIME = 2000; + static private final int GRACE_TIME = 2001; /** Directory where to store local cache of remote {@link Card}s. */ static private File cacheDir; @@ -110,7 +114,7 @@ public class Sync { } /** - * Check if the synchronisation is available for this resource. + * Check if the remote server already know about this resource. * * @return TRUE if it is possible to contact the remote server and that this * server has the resource available @@ -120,7 +124,7 @@ public class Sync { SimpleSocket s = new SimpleSocket(new Socket(host, port), "check avail client"); s.open(true); - s.sendCommand(Verb.LIST); + s.sendCommand(Command.LIST_CARD); List timestampedFiles = s.receiveBlock(); s.close(); @@ -137,16 +141,41 @@ public class Sync { return false; } - // return: synced or not - public boolean sync(Card card, boolean force) throws UnknownHostException, - IOException { + /** + * Synchronise the current resource if needed, then return the locally + * cached version of said resource. + * + *

+ * A synchronisation is deemed necessary if one of the following is true: + *

+ *

+ * + * @param force + * force the synchronisation to occur + * + * @return the synchronised (or not) {@link Card} + * + * @throws UnknownHostException + * in case of server name resolution failure + * @throws IOException + * in case of IO error + */ + public Card sync(boolean force) throws UnknownHostException, IOException { long tsOriginal = getLastModified(); + Card local = new Card(getCache(cacheDir), Format.VCard21); + local.setRemote(true); + // do NOT update unless we are in autoSync or forced mode or we don't // have the file on cache if (!autoSync && !force && tsOriginal != -1) { - return false; + return local; } SimpleSocket s = new SimpleSocket(new Socket(host, port), "sync client"); @@ -155,7 +184,7 @@ public class Sync { long tsServer = -1; try { s.open(true); - s.sendCommand(Verb.LIST); + s.sendCommand(Command.LIST_CARD); List timestampedFiles = s.receiveBlock(); for (String timestampedFile : timestampedFiles) { @@ -167,91 +196,289 @@ public class Sync { break; } } + + // Error cases: + // - file not present neither in cache nor on server + // - remote < previous + if ((tsServer == -1 && tsOriginal == -1) + || (tsServer != -1 && tsOriginal != -1 && ((tsOriginal - tsServer) > GRACE_TIME))) { + throw new IOException( + "The timestamps between server and client are invalid"); + } + + // Check changes + boolean serverChanges = (tsServer - tsOriginal) > GRACE_TIME; + boolean localChanges = false; + Card original = null; + if (tsOriginal != -1) { + original = new Card(getCache(cacheDirOrig), Format.VCard21); + localChanges = !local.isEquals(original, true); + } + + Command action = null; + + // Sync to server if: + if (localChanges) { + action = Command.PUT_CARD; + } + + // Sync from server if: + if (serverChanges) { + action = Command.HASH_CONTACT; + } + + // Sync from/to server if + if (serverChanges && localChanges) { + action = Command.HELP; + } + + // POST the whole file if: + if (tsServer == -1) { + action = Command.POST_CARD; + } + + // GET the whole file if: + if (tsOriginal == -1) { + action = Command.GET_CARD; + } + + System.err.println("remote: " + (tsServer / 1000) % 1000 + " (" + + tsServer + ")"); + System.err.println("previous: " + (tsOriginal / 1000) % 1000 + " (" + + tsOriginal + ")"); + System.err.println("local changes: " + localChanges); + System.err.println("server changes: " + serverChanges); + System.err.println("choosen action: " + action); + + if (action != null) { + s.sendCommand(Command.SELECT, name); + if (tsServer != StringUtils.toTime(s.receiveLine())) { + System.err.println("DEBUG: it changed. retry."); + s.sendCommand(Command.SELECT); + s.close(); + return sync(force); + } + + switch (action) { + case GET_CARD: { + s.sendCommand(Command.GET_CARD); + List data = s.receiveBlock(); + setLastModified(data.remove(0)); + Card server = new Card(Vcard21Parser.parseContact(data)); + local.replaceListContent(server); + + if (local.isDirty()) + local.save(); + local.saveAs(getCache(cacheDirOrig), Format.VCard21); + break; + } + case POST_CARD: { + s.sendCommand(Command.POST_CARD); + s.sendBlock(Vcard21Parser.toStrings(local)); + local.saveAs(getCache(cacheDirOrig), Format.VCard21); + setLastModified(s.receiveLine()); + break; + } + case PUT_CARD: { + String serverLastModifTime = updateToServer(s, original, + local); + + local.saveAs(getCache(cacheDirOrig), Format.VCard21); + + setLastModified(serverLastModifTime); + break; + } + case HASH_CONTACT: { + String serverLastModifTime = updateFromServer(s, local); + + local.save(); + local.saveAs(getCache(cacheDirOrig), Format.VCard21); + + setLastModified(serverLastModifTime); + break; + } + case HELP: { + if (true) + throw new IOException("two-way sync not supported yet"); + + // note: we are holding the server here, so it could throw + // us away if we take too long + + File mergeF = File.createTempFile("contact-merge", ".vcf"); + File serverF = File + .createTempFile("contact-server", ".vcf"); + original.saveAs(serverF, Format.VCard21); + + Card server = new Card(serverF, Format.VCard21); + updateFromServer(s, server); + + // TODO: auto merge into mergeF (from original, local, + // server) + local.saveAs(mergeF, Format.VCard21); + Card merge = new Card(mergeF, Format.VCard21); + + // TODO: ask client if ok or to change it herself + + String serverLastModifTime = updateToServer(s, original, + merge); + + merge.saveAs(getCache(cacheDir), Format.VCard21); + merge.saveAs(getCache(cacheDirOrig), Format.VCard21); + + setLastModified(serverLastModifTime); + + local = merge; + + break; + } + } + + s.sendCommand(Command.SELECT); + } } catch (IOException e) { - s.close(); throw e; } catch (Exception e) { e.printStackTrace(); + return local; + } finally { s.close(); - return false; } - // Error cases: - // - file not preset neither in cache nor on server - // - remote < previous - if ((tsServer == -1 && tsOriginal == -1) - || (tsServer != -1 && tsOriginal != -1 && ((tsOriginal - tsServer) > GRACE_TIME))) { - throw new IOException( - "The timestamps between server and client are invalid"); + return local; + } + + /** + * Will update the currently selected {@link Card} on the remote server to + * be in the same state as local, assuming the server is currently + * in original state. + * + * @param s + * the {@link SimpleSocket} to work on, which MUST be in + * SELECT mode + * @param original + * the original {@link Card} as it was before the client made + * changes to it + * @param local + * the {@link Card} to which state we want the server in + * + * @return the last modified time from the remote server (which is basically + * "now") + * + * @throws IOException + * in case of IO error + */ + private String updateToServer(SimpleSocket s, Card original, Card local) + throws IOException { + List added = new LinkedList(); + List removed = new LinkedList(); + List from = new LinkedList(); + List to = new LinkedList(); + original.compare(local, added, removed, from, to); + + s.sendCommand(Command.PUT_CARD); + + for (Contact c : removed) { + s.sendCommand(Command.DELETE_CONTACT, c.getId()); + } + for (Contact c : added) { + s.sendCommand(Command.POST_CONTACT, c.getId()); + s.sendBlock(Vcard21Parser.toStrings(c, -1)); + } + if (from.size() > 0) { + for (int index = 0; index < from.size(); index++) { + Contact f = from.get(index); + Contact t = to.get(index); + + List subadded = new LinkedList(); + List subremoved = new LinkedList(); + f.compare(t, subadded, subremoved, subremoved, subadded); + s.sendCommand(Command.PUT_CONTACT, name); + for (Data d : subremoved) { + s.sendCommand(Command.DELETE_DATA, d.getContentState()); + } + for (Data d : subadded) { + s.sendCommand(Command.POST_DATA, d.getContentState()); + s.sendBlock(Vcard21Parser.toStrings(d)); + } + } } - // Check changes - boolean serverChanges = (tsServer - tsOriginal) > GRACE_TIME; - boolean localChanges = false; - if (tsOriginal != -1) { - Card local = new Card(getCache(cacheDir), Format.VCard21); - Card original = new Card(getCache(cacheDirOrig), Format.VCard21); - localChanges = !local.isEquals(original); + s.sendCommand(Command.PUT_CARD); + + return s.receiveLine(); + } + + /** + * Will update the given {@link Card} object (not {@link File}) to the + * currently selected {@link Card} on the remote server. + * + * @param s + * the {@link SimpleSocket} to work on, which MUST be in + * SELECT mode + * @param local + * the {@link Card} to update + * + * @return the last modified time from the remote server + * + * @throws IOException + * in case of IO error + */ + private String updateFromServer(SimpleSocket s, Card local) + throws IOException { + s.sendCommand(Command.PUT_CARD); + + s.sendCommand(Command.LIST_CONTACT); + Map remote = new HashMap(); + for (String line : s.receiveBlock()) { + int indexSp = line.indexOf(" "); + String hash = line.substring(0, indexSp); + String uid = line.substring(indexSp + 1); + + remote.put(uid, hash); } - Verb action = null; + List deleted = new LinkedList(); + List changed = new LinkedList(); + List added = new LinkedList(); - // Sync to server if: - if (localChanges) { - // TODO: sync instead (with PUT) - action = Verb.POST; + for (Contact c : local) { + String hash = remote.get(c.getId()); + if (hash == null) { + deleted.add(c); + } else if (!hash.equals(c.getContentState())) { + changed.add(c); + } } - // Sync from server if - if (serverChanges && localChanges) { - // TODO - throw new IOException("Sync operation not supported yet :("); + for (String uid : remote.keySet()) { + if (local.getById(uid) == null) + added.add(uid); } - // PUT the whole file if: - if (tsServer == -1) { - action = Verb.POST; + // process: + + for (Contact c : deleted) { + c.delete(); } - // GET the whole file if: - if (tsOriginal == -1 || serverChanges) { - action = Verb.GET; + for (String uid : added) { + s.sendCommand(Command.GET_CONTACT, uid); + for (Contact cc : Vcard21Parser.parseContact(s.receiveBlock())) { + local.add(cc); + } } - System.err.println("remote: " + (tsServer / 1000) % 1000 + " (" - + tsServer + ")"); - System.err.println("previous: " + (tsOriginal / 1000) % 1000 + " (" - + tsOriginal + ")"); - System.err.println("local changes: " + localChanges); - System.err.println("server changes: " + serverChanges); - System.err.println("choosen action: " + action); - - if (action != null) { - switch (action) { - case GET: - s.sendCommand(Verb.GET, name); - List data = s.receiveBlock(); - setLastModified(data.remove(0)); - Card server = new Card(Parser.parse(data, Format.VCard21)); - card.replaceListContent(server); - if (card.isDirty()) - card.save(); - card.saveAs(getCache(cacheDirOrig), Format.VCard21); - break; - case POST: - s.sendCommand(Verb.POST, name); - s.sendLine(card.toString(Format.VCard21)); - break; - default: - // TODO - throw new IOException(action - + " operation not supported yet :("); + for (Contact c : changed) { + c.delete(); + s.sendCommand(Command.GET_CONTACT, c.getId()); + for (Contact cc : Vcard21Parser.parseContact(s.receiveBlock())) { + local.add(cc); } } - s.close(); + s.sendCommand(Command.PUT_CARD); - return true; + return s.receiveLine(); } /** @@ -294,7 +521,7 @@ public class Sync { return StringUtils.toTime(line); } catch (FileNotFoundException e) { return -1; - } catch (IOException e) { + } catch (Exception e) { return -1; } }