Commit | Line | Data |
---|---|---|
a046fa49 NR |
1 | package be.nikiroo.jvcard.remote; |
2 | ||
3 | import java.io.BufferedReader; | |
4 | import java.io.BufferedWriter; | |
5 | import java.io.File; | |
6 | import java.io.FileInputStream; | |
7 | import java.io.FileNotFoundException; | |
8 | import java.io.FileOutputStream; | |
9 | import java.io.IOException; | |
10 | import java.io.InputStreamReader; | |
11 | import java.io.OutputStreamWriter; | |
12 | import java.net.Socket; | |
13 | import java.net.UnknownHostException; | |
14 | import java.security.InvalidParameterException; | |
0b6140e4 | 15 | import java.util.LinkedList; |
a046fa49 NR |
16 | import java.util.List; |
17 | import java.util.MissingResourceException; | |
18 | import java.util.ResourceBundle; | |
19 | ||
20 | import be.nikiroo.jvcard.Card; | |
0b6140e4 NR |
21 | import be.nikiroo.jvcard.Contact; |
22 | import be.nikiroo.jvcard.Data; | |
a046fa49 | 23 | import be.nikiroo.jvcard.parsers.Format; |
0b6140e4 | 24 | import be.nikiroo.jvcard.parsers.Vcard21Parser; |
a046fa49 NR |
25 | import be.nikiroo.jvcard.remote.Command.Verb; |
26 | import be.nikiroo.jvcard.resources.Bundles; | |
27 | import be.nikiroo.jvcard.tui.StringUtils; | |
28 | ||
29 | /** | |
30 | * This class will synchronise {@link Card}s between a local instance an a | |
31 | * remote jVCard server. | |
32 | * | |
33 | * @author niki | |
34 | * | |
35 | */ | |
36 | public class Sync { | |
37 | /** The time in ms after which we declare that 2 timestamps are different */ | |
38 | static private final int GRACE_TIME = 2000; | |
39 | ||
40 | /** Directory where to store local cache of remote {@link Card}s. */ | |
41 | static private File cacheDir; | |
42 | ||
43 | /** | |
44 | * Directory where to store cache of remote {@link Card}s without | |
45 | * modifications since the last synchronisation. | |
46 | */ | |
47 | static private File cacheDirOrig; | |
48 | /** Directory where to store timestamps for files in cacheDirOrig */ | |
49 | static private File cacheDirOrigTS; | |
50 | ||
51 | static private boolean autoSync; | |
52 | private String host; | |
53 | private int port; | |
54 | ||
55 | /** Resource name on the remote server. */ | |
56 | private String name; | |
57 | ||
58 | /** | |
59 | * Create a new {@link Sync} object, ready to operate for the given resource | |
60 | * on the given server. | |
61 | * | |
62 | * <p> | |
63 | * Note that the format used is the standard "host:port_number/file", with | |
64 | * an optional <tt>jvcard://</tt> prefix. | |
65 | * </p> | |
66 | * | |
67 | * <p> | |
68 | * E.g.: <tt>jvcard://localhost:4444/family.vcf</tt> | |
69 | * </p> | |
70 | * | |
71 | * @param url | |
72 | * the server and port to contact, optionally prefixed with | |
73 | * <tt>jvcard://</tt> | |
74 | * | |
75 | * @throws InvalidParameterException | |
76 | * if the remote configuration file <tt>remote.properties</tt> | |
77 | * cannot be accessed or if the cache directory cannot be used | |
78 | */ | |
79 | public Sync(String url) { | |
80 | if (cacheDir == null) { | |
81 | config(); | |
82 | } | |
83 | ||
84 | try { | |
85 | url = url.replace("jvcard://", ""); | |
86 | int indexSl = url.indexOf('/'); | |
87 | this.name = url.substring(indexSl + 1); | |
88 | url = url.substring(0, indexSl); | |
89 | this.host = url.split("\\:")[0]; | |
90 | this.port = Integer.parseInt(url.split("\\:")[1]); | |
91 | } catch (Exception e) { | |
92 | throw new InvalidParameterException( | |
93 | "the given parameter was not a valid HOST:PORT value: " | |
94 | + url); | |
95 | } | |
96 | } | |
97 | ||
98 | /** | |
99 | * Create a new {@link Sync} object, ready to operate on the given server. | |
100 | * | |
101 | * | |
102 | * @param host | |
103 | * the server to contact | |
104 | * @param port | |
105 | * the port to use | |
106 | * @param name | |
107 | * the resource name to synchronise to | |
108 | */ | |
109 | public Sync(String host, int port, String name) { | |
110 | this.host = host; | |
111 | this.port = port; | |
112 | this.name = name; | |
113 | } | |
114 | ||
115 | /** | |
116 | * Check if the synchronisation is available for this resource. | |
117 | * | |
118 | * @return TRUE if it is possible to contact the remote server and that this | |
119 | * server has the resource available | |
120 | */ | |
121 | public boolean isAvailable() { | |
122 | try { | |
123 | SimpleSocket s = new SimpleSocket(new Socket(host, port), | |
124 | "check avail client"); | |
125 | s.open(true); | |
126 | s.sendCommand(Verb.LIST); | |
127 | List<String> timestampedFiles = s.receiveBlock(); | |
128 | s.close(); | |
129 | ||
130 | for (String timestampedFile : timestampedFiles) { | |
131 | String file = timestampedFile.substring(StringUtils.fromTime(0) | |
132 | .length() + 1); | |
133 | if (file.equals(name)) { | |
134 | return true; | |
135 | } | |
136 | } | |
137 | } catch (Exception e) { | |
138 | } | |
139 | ||
140 | return false; | |
141 | } | |
142 | ||
143 | // return: synced or not | |
144 | public boolean sync(Card card, boolean force) throws UnknownHostException, | |
145 | IOException { | |
146 | ||
147 | long tsOriginal = getLastModified(); | |
148 | ||
149 | // do NOT update unless we are in autoSync or forced mode or we don't | |
150 | // have the file on cache | |
151 | if (!autoSync && !force && tsOriginal != -1) { | |
152 | return false; | |
153 | } | |
154 | ||
155 | SimpleSocket s = new SimpleSocket(new Socket(host, port), "sync client"); | |
156 | ||
157 | // get the server time stamp | |
158 | long tsServer = -1; | |
159 | try { | |
160 | s.open(true); | |
161 | s.sendCommand(Verb.LIST); | |
162 | List<String> timestampedFiles = s.receiveBlock(); | |
163 | ||
164 | for (String timestampedFile : timestampedFiles) { | |
165 | String file = timestampedFile.substring(StringUtils.fromTime(0) | |
166 | .length() + 1); | |
167 | if (file.equals(name)) { | |
168 | tsServer = StringUtils.toTime(timestampedFile.substring(0, | |
169 | StringUtils.fromTime(0).length())); | |
170 | break; | |
171 | } | |
172 | } | |
173 | } catch (IOException e) { | |
174 | s.close(); | |
175 | throw e; | |
176 | } catch (Exception e) { | |
177 | e.printStackTrace(); | |
178 | s.close(); | |
179 | return false; | |
180 | } | |
181 | ||
182 | // Error cases: | |
183 | // - file not preset neither in cache nor on server | |
184 | // - remote < previous | |
185 | if ((tsServer == -1 && tsOriginal == -1) | |
186 | || (tsServer != -1 && tsOriginal != -1 && ((tsOriginal - tsServer) > GRACE_TIME))) { | |
187 | throw new IOException( | |
188 | "The timestamps between server and client are invalid"); | |
189 | } | |
190 | ||
191 | // Check changes | |
192 | boolean serverChanges = (tsServer - tsOriginal) > GRACE_TIME; | |
193 | boolean localChanges = false; | |
0b6140e4 NR |
194 | Card local = null; |
195 | Card original = null; | |
a046fa49 | 196 | if (tsOriginal != -1) { |
0b6140e4 NR |
197 | local = new Card(getCache(cacheDir), Format.VCard21); |
198 | original = new Card(getCache(cacheDirOrig), Format.VCard21); | |
cf77cb35 | 199 | localChanges = !local.isEquals(original, true); |
a046fa49 NR |
200 | } |
201 | ||
202 | Verb action = null; | |
203 | ||
204 | // Sync to server if: | |
205 | if (localChanges) { | |
0b6140e4 | 206 | action = Verb.PUT_CARD; |
a046fa49 NR |
207 | } |
208 | ||
0b6140e4 | 209 | // Sync from/to server if |
a046fa49 | 210 | if (serverChanges && localChanges) { |
0b6140e4 NR |
211 | action = Verb.PUT_CARD; |
212 | } | |
213 | ||
214 | // Sync from server if: | |
215 | if (serverChanges) { | |
216 | // TODO: only sends changed cstate if serverChanges | |
217 | action = Verb.GET_CARD; | |
a046fa49 NR |
218 | } |
219 | ||
220 | // PUT the whole file if: | |
221 | if (tsServer == -1) { | |
0b6140e4 | 222 | action = Verb.POST_CARD; |
a046fa49 NR |
223 | } |
224 | ||
225 | // GET the whole file if: | |
0b6140e4 NR |
226 | if (tsOriginal == -1) { |
227 | action = Verb.GET_CARD; | |
a046fa49 NR |
228 | } |
229 | ||
230 | System.err.println("remote: " + (tsServer / 1000) % 1000 + " (" | |
231 | + tsServer + ")"); | |
232 | System.err.println("previous: " + (tsOriginal / 1000) % 1000 + " (" | |
233 | + tsOriginal + ")"); | |
234 | System.err.println("local changes: " + localChanges); | |
235 | System.err.println("server changes: " + serverChanges); | |
236 | System.err.println("choosen action: " + action); | |
237 | ||
238 | if (action != null) { | |
239 | switch (action) { | |
0b6140e4 NR |
240 | case GET_CARD: |
241 | s.sendCommand(Verb.GET_CARD, name); | |
a046fa49 NR |
242 | List<String> data = s.receiveBlock(); |
243 | setLastModified(data.remove(0)); | |
0b6140e4 | 244 | Card server = new Card(Vcard21Parser.parseContact(data)); |
a046fa49 | 245 | card.replaceListContent(server); |
cf77cb35 | 246 | |
a046fa49 NR |
247 | if (card.isDirty()) |
248 | card.save(); | |
249 | card.saveAs(getCache(cacheDirOrig), Format.VCard21); | |
250 | break; | |
0b6140e4 NR |
251 | case POST_CARD: |
252 | s.sendCommand(Verb.POST_CARD, name); | |
253 | s.sendBlock(Vcard21Parser.toStrings(card)); | |
cf77cb35 NR |
254 | card.saveAs(getCache(cacheDirOrig), Format.VCard21); |
255 | setLastModified(s.receiveLine()); | |
a046fa49 | 256 | break; |
0b6140e4 NR |
257 | case PUT_CARD: |
258 | List<Contact> added = new LinkedList<Contact>(); | |
259 | List<Contact> removed = new LinkedList<Contact>(); | |
260 | List<Contact> from = new LinkedList<Contact>(); | |
261 | List<Contact> to = new LinkedList<Contact>(); | |
262 | original.compare(local, added, removed, from, to); | |
263 | s.sendCommand(Verb.PUT_CARD, name); | |
264 | for (Contact c : removed) { | |
265 | s.sendCommand(Verb.DELETE_CONTACT, c.getId()); | |
266 | } | |
267 | for (Contact c : added) { | |
268 | s.sendCommand(Verb.POST_CONTACT, c.getId()); | |
269 | s.sendBlock(Vcard21Parser.toStrings(c, -1)); | |
270 | } | |
271 | if (from.size() > 0) { | |
272 | for (int index = 0; index < from.size(); index++) { | |
273 | Contact f = from.get(index); | |
274 | Contact t = to.get(index); | |
275 | ||
276 | List<Data> subadded = new LinkedList<Data>(); | |
277 | List<Data> subremoved = new LinkedList<Data>(); | |
278 | f.compare(t, subadded, subremoved, subremoved, subadded); | |
279 | s.sendCommand(Verb.PUT_CONTACT, name); | |
280 | for (Data d : subremoved) { | |
281 | s.sendCommand(Verb.DELETE_DATA, d.getContentState()); | |
282 | } | |
283 | for (Data d : subadded) { | |
284 | s.sendCommand(Verb.POST_DATA, d.getContentState()); | |
285 | s.sendBlock(Vcard21Parser.toStrings(d)); | |
286 | } | |
287 | } | |
288 | } | |
289 | s.sendCommand(Verb.PUT_CARD); | |
290 | break; | |
a046fa49 NR |
291 | default: |
292 | // TODO | |
293 | throw new IOException(action | |
294 | + " operation not supported yet :("); | |
295 | } | |
296 | } | |
297 | ||
298 | s.close(); | |
299 | ||
300 | return true; | |
301 | } | |
302 | ||
303 | /** | |
304 | * Return the requested cache for the current resource. | |
305 | * | |
306 | * @param dir | |
307 | * the cache to use | |
308 | * | |
309 | * @return the cached {@link File} | |
310 | */ | |
311 | private File getCache(File dir) { | |
312 | return new File(dir.getPath() + File.separator + name); | |
313 | } | |
314 | ||
315 | /** | |
316 | * Return the cached {@link File} corresponding to the current resource. | |
317 | * | |
318 | * @return the cached {@link File} | |
319 | */ | |
320 | public File getCache() { | |
321 | return new File(cacheDir.getPath() + File.separator + name); | |
322 | } | |
323 | ||
324 | /** | |
325 | * Get the last modified date of the current resource's original cached | |
326 | * file, that is, the time the server reported as the "last modified time" | |
327 | * when this resource was transfered. | |
328 | * | |
329 | * @return the last modified time from the server back when this resource | |
330 | * was transfered | |
331 | */ | |
332 | public long getLastModified() { | |
333 | try { | |
334 | BufferedReader in = new BufferedReader(new InputStreamReader( | |
335 | new FileInputStream(cacheDirOrigTS.getPath() | |
336 | + File.separator + name))); | |
337 | String line = in.readLine(); | |
338 | in.close(); | |
339 | ||
340 | return StringUtils.toTime(line); | |
341 | } catch (FileNotFoundException e) { | |
342 | return -1; | |
cf77cb35 | 343 | } catch (Exception e) { |
a046fa49 NR |
344 | return -1; |
345 | } | |
346 | } | |
347 | ||
348 | /** | |
349 | * Set the last modified date of the current resource's original cached | |
350 | * file, that is, the time the server reported as the "last modified time" | |
351 | * when this resource was transfered. | |
352 | * | |
353 | * @param time | |
354 | * the last modified time from the server back when this resource | |
355 | * was transfered | |
356 | */ | |
357 | public void setLastModified(String time) { | |
358 | try { | |
359 | BufferedWriter out = new BufferedWriter(new OutputStreamWriter( | |
360 | new FileOutputStream(cacheDirOrigTS.getPath() | |
361 | + File.separator + name))); | |
362 | out.append(time); | |
363 | out.newLine(); | |
364 | out.close(); | |
365 | } catch (FileNotFoundException e) { | |
366 | e.printStackTrace(); | |
367 | } catch (IOException e) { | |
368 | e.printStackTrace(); | |
369 | } | |
370 | } | |
371 | ||
372 | /** | |
373 | * Configure the synchronisation mechanism (cache, auto update...). | |
374 | * | |
375 | * @throws InvalidParameterException | |
376 | * if the remote configuration file <tt>remote.properties</tt> | |
377 | * cannot be accessed or if the cache directory cannot be used | |
378 | */ | |
379 | static private void config() { | |
380 | String dir = null; | |
381 | ResourceBundle bundle = Bundles.getBundle("remote"); | |
382 | ||
383 | try { | |
384 | dir = bundle.getString("CLIENT_CACHE_DIR").trim(); | |
385 | ||
386 | cacheDir = new File(dir + File.separator + "current"); | |
387 | cacheDir.mkdir(); | |
388 | cacheDirOrig = new File(dir + File.separator + "original"); | |
389 | cacheDirOrig.mkdir(); | |
390 | cacheDirOrigTS = new File(dir + File.separator + "timestamps"); | |
391 | cacheDirOrigTS.mkdir(); | |
392 | ||
393 | if (!cacheDir.exists() || !cacheDirOrig.exists()) { | |
394 | throw new IOException("Cannot open or create cache store at: " | |
395 | + dir); | |
396 | } | |
397 | ||
398 | String autoStr = bundle.getString("CLIENT_AUTO_SYNC"); | |
399 | if (autoStr != null && autoStr.trim().equalsIgnoreCase("true")) { | |
400 | autoSync = true; | |
401 | } | |
402 | ||
403 | } catch (MissingResourceException e) { | |
404 | throw new InvalidParameterException( | |
405 | "Cannot access remote.properties configuration file"); | |
406 | } catch (Exception e) { | |
407 | throw new InvalidParameterException( | |
408 | "Cannot open or create cache store at: " + dir); | |
409 | } | |
410 | } | |
411 | } |