update from master
[fanfix.git] / library / RemoteLibraryServer.java
CommitLineData
e42573a0 1package be.nikiroo.fanfix.library;
b0e88ebd 2
b0e88ebd 3import java.io.IOException;
edf79e5e 4import java.net.URL;
74a40dfb 5import java.util.ArrayList;
9b863b20 6import java.util.Date;
9b558341 7import java.util.HashMap;
68e2c6d2 8import java.util.List;
9b558341 9import java.util.Map;
b0e88ebd 10
7e51d91c
NR
11import javax.net.ssl.SSLException;
12
e42573a0 13import be.nikiroo.fanfix.Instance;
fb25273c 14import be.nikiroo.fanfix.bundles.Config;
74a40dfb 15import be.nikiroo.fanfix.data.Chapter;
b0e88ebd 16import be.nikiroo.fanfix.data.MetaData;
74a40dfb 17import be.nikiroo.fanfix.data.Paragraph;
085a2f9a 18import be.nikiroo.fanfix.data.Story;
b9ce9cad
NR
19import be.nikiroo.utils.Progress;
20import be.nikiroo.utils.Progress.ProgressListener;
416c54f8 21import be.nikiroo.utils.StringUtils;
fb25273c 22import be.nikiroo.utils.Version;
62c63b07
NR
23import be.nikiroo.utils.serial.server.ConnectActionServerObject;
24import be.nikiroo.utils.serial.server.ServerObject;
b0e88ebd 25
a85e8077 26/**
ea734ab4 27 * Create a new remote server that will listen for orders on the given port.
a85e8077 28 * <p>
ea734ab4
N
29 * The available commands are given as arrays of objects (first item is the
30 * command, the rest are the arguments).
2a25f781 31 * <p>
fb25273c
NR
32 * All the commands are always prefixed by the subkey (which can be EMPTY if
33 * none).
34 * <p>
a85e8077 35 * <ul>
fb25273c
NR
36 * <li>PING: will return the mode if the key is accepted (mode can be: "r/o" or
37 * "r/w")</li>
ea734ab4
N
38 * <li>GET_METADATA *: will return the metadata of all the stories in the
39 * library (array)</li> *
c91f1830
NR
40 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID
41 * luid</li>
ea734ab4
N
42 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
43 * not)</li>
44 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
0fa0fe95 45 * command) with the given LUID, then return the LUID</li>
37abe20c
NR
46 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
47 * </li>
ea734ab4
N
48 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
49 * <li>GET_COVER [luid]: return the cover of the story</li>
50 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
51 * source/author</li>
52 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
53 * the given source/author to the cover of the story denoted by luid</li>
54 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
55 * luid</li>
56 * <li>EXIT: stop the server</li>
a85e8077
NR
57 * </ul>
58 *
59 * @author niki
60 */
62c63b07 61public class RemoteLibraryServer extends ServerObject {
9b558341
NR
62 private Map<Long, String> commands = new HashMap<Long, String>();
63 private Map<Long, Long> times = new HashMap<Long, Long>();
fb25273c 64 private Map<Long, Boolean> wls = new HashMap<Long, Boolean>();
c91f1830 65 private Map<Long, Boolean> bls = new HashMap<Long, Boolean>();
fb25273c 66 private Map<Long, Boolean> rws = new HashMap<Long, Boolean>();
9b558341 67
a85e8077
NR
68 /**
69 * Create a new remote server (will not be active until
70 * {@link RemoteLibraryServer#start()} is called).
fb25273c
NR
71 * <p>
72 * Note: the key we use here is the encryption key (it must not contain a
73 * subkey).
a85e8077 74 *
a85e8077
NR
75 * @throws IOException
76 * in case of I/O error
77 */
f433d153
NR
78 public RemoteLibraryServer() throws IOException {
79 super("Fanfix remote library",
80 Instance.getInstance().getConfig()
81 .getInteger(Config.SERVER_PORT),
82 Instance.getInstance().getConfig()
83 .getString(Config.SERVER_KEY));
c91f1830 84
d66deb8d 85 setTraceHandler(Instance.getInstance().getTraceHandler());
b0e88ebd
NR
86 }
87
88 @Override
fb25273c
NR
89 protected Object onRequest(ConnectActionServerObject action,
90 Version clientVersion, Object data, long id) throws Exception {
ea734ab4
N
91 long start = new Date().getTime();
92
fb25273c
NR
93 // defaults are positive (as previous versions without the feature)
94 boolean rw = true;
95 boolean wl = true;
c91f1830 96 boolean bl = true;
fb25273c
NR
97
98 String subkey = "";
085a2f9a
NR
99 String command = "";
100 Object[] args = new Object[0];
101 if (data instanceof Object[]) {
2070ced5 102 Object[] dataArray = (Object[]) data;
27eba894 103 if (dataArray.length > 0) {
fb25273c
NR
104 subkey = "" + dataArray[0];
105 }
106 if (dataArray.length > 1) {
107 command = "" + dataArray[1];
108
109 args = new Object[dataArray.length - 2];
110 for (int i = 2; i < dataArray.length; i++) {
111 args[i - 2] = dataArray[i];
112 }
113 }
114 }
115
c91f1830
NR
116 List<String> whitelist = Instance.getInstance().getConfig()
117 .getList(Config.SERVER_WHITELIST);
fb25273c
NR
118 if (whitelist == null) {
119 whitelist = new ArrayList<String>();
120 }
c91f1830
NR
121 List<String> blacklist = Instance.getInstance().getConfig()
122 .getList(Config.SERVER_BLACKLIST);
123 if (blacklist == null) {
124 blacklist = new ArrayList<String>();
125 }
fb25273c
NR
126
127 if (whitelist.isEmpty()) {
128 wl = false;
129 }
edf79e5e 130
c91f1830
NR
131 rw = Instance.getInstance().getConfig().getBoolean(Config.SERVER_RW,
132 rw);
fb25273c 133 if (!subkey.isEmpty()) {
c91f1830
NR
134 List<String> allowed = Instance.getInstance().getConfig()
135 .getList(Config.SERVER_ALLOWED_SUBKEYS);
fb25273c
NR
136 if (allowed.contains(subkey)) {
137 if ((subkey + "|").contains("|rw|")) {
138 rw = true;
139 }
140 if ((subkey + "|").contains("|wl|")) {
141 wl = false; // |wl| = bypass whitelist
651072f3 142 whitelist = new ArrayList<String>();
2070ced5 143 }
c91f1830
NR
144 if ((subkey + "|").contains("|bl|")) {
145 bl = false; // |bl| = bypass blacklist
146 blacklist = new ArrayList<String>();
147 }
b0e88ebd
NR
148 }
149 }
150
c91f1830 151 String mode = display(wl, bl, rw);
fb25273c
NR
152
153 String trace = mode + "[ " + command + "] ";
085a2f9a 154 for (Object arg : args) {
b9ce9cad 155 trace += arg + " ";
085a2f9a 156 }
c1bb921e
NR
157 long now = System.currentTimeMillis();
158 System.out.println(StringUtils.fromTime(now) + ": " + trace);
b0e88ebd 159
c1b31971 160 Object rep = null;
c1b31971 161 try {
c91f1830 162 rep = doRequest(action, command, args, rw, whitelist, blacklist);
5db598bc 163 } catch (IOException e) {
533dc2b8 164 rep = new RemoteLibraryException(e, true);
c1b31971 165 }
9f51d8ab 166
9b558341 167 commands.put(id, command);
fb25273c 168 wls.put(id, wl);
c91f1830 169 bls.put(id, bl);
fb25273c 170 rws.put(id, rw);
9b558341 171 times.put(id, (new Date().getTime() - start));
9f51d8ab
NR
172
173 return rep;
174 }
175
c91f1830 176 private String display(boolean whitelist, boolean blacklist, boolean rw) {
fb25273c
NR
177 String mode = "";
178 if (!rw) {
179 mode += "RO: ";
180 }
181 if (whitelist) {
182 mode += "WL: ";
183 }
c91f1830
NR
184 if (blacklist) {
185 mode += "BL: ";
186 }
fb25273c
NR
187
188 return mode;
189 }
190
9b558341
NR
191 @Override
192 protected void onRequestDone(long id, long bytesReceived, long bytesSent) {
fb25273c 193 boolean whitelist = wls.get(id);
c91f1830 194 boolean blacklist = bls.get(id);
fb25273c
NR
195 boolean rw = rws.get(id);
196 wls.remove(id);
c91f1830 197 bls.remove(id);
fb25273c
NR
198 rws.remove(id);
199
9b558341
NR
200 String rec = StringUtils.formatNumber(bytesReceived) + "b";
201 String sent = StringUtils.formatNumber(bytesSent) + "b";
c1bb921e 202 long now = System.currentTimeMillis();
c91f1830 203 System.out.println(StringUtils.fromTime(now) + ": "
c1bb921e 204 + String.format("%s[>%s]: (%s sent, %s rec) in %d ms",
c91f1830
NR
205 display(whitelist, blacklist, rw), commands.get(id),
206 sent, rec, times.get(id)));
fb25273c 207
9b558341
NR
208 commands.remove(id);
209 times.remove(id);
210 }
211
9f51d8ab 212 private Object doRequest(ConnectActionServerObject action, String command,
c91f1830
NR
213 Object[] args, boolean rw, List<String> whitelist,
214 List<String> blacklist) throws NoSuchFieldException,
215 NoSuchMethodException, ClassNotFoundException, IOException {
3bbc86a5 216 if ("PING".equals(command)) {
fb25273c 217 return rw ? "r/w" : "r/o";
3bbc86a5 218 } else if ("GET_METADATA".equals(command)) {
651072f3
NR
219 List<MetaData> metas = new ArrayList<MetaData>();
220
7efece85 221 if ("*".equals(args[0])) {
9b863b20 222 Progress pg = createPgForwarder(action);
9f51d8ab 223
c91f1830
NR
224 for (MetaData meta : Instance.getInstance().getLibrary()
225 .getMetas(pg)) {
a5d1f0e6 226 metas.add(removeCover(meta));
9f51d8ab
NR
227 }
228
9b863b20 229 forcePgDoneSent(pg);
651072f3 230 } else {
c91f1830
NR
231 MetaData meta = Instance.getInstance().getLibrary()
232 .getInfo((String) args[0]);
210465c3
NR
233 MetaData light;
234 if (meta.getCover() == null) {
235 light = meta;
236 } else {
237 light = meta.clone();
238 light.setCover(null);
239 }
240
241 metas.add(light);
651072f3
NR
242 }
243
c91f1830
NR
244 for (int i = 0; i < metas.size(); i++) {
245 if (!isAllowed(metas.get(i), whitelist, blacklist)) {
246 metas.remove(i);
247 i--;
651072f3 248 }
a85e8077 249 }
e272f05f 250
651072f3 251 return metas.toArray(new MetaData[0]);
c91f1830 252
a85e8077 253 } else if ("GET_STORY".equals(command)) {
c91f1830
NR
254 MetaData meta = Instance.getInstance().getLibrary()
255 .getInfo((String) args[0]);
256 if (meta == null || !isAllowed(meta, whitelist, blacklist)) {
651072f3
NR
257 return null;
258 }
259
b9ce9cad
NR
260 meta = meta.clone();
261 meta.setCover(null);
262
263 action.send(meta);
264 action.rec();
265
c91f1830
NR
266 Story story = Instance.getInstance().getLibrary()
267 .getStory((String) args[0], null);
b9ce9cad
NR
268 for (Object obj : breakStory(story)) {
269 action.send(obj);
270 action.rec();
271 }
085a2f9a 272 } else if ("SAVE_STORY".equals(command)) {
651072f3 273 if (!rw) {
c91f1830
NR
274 throw new RemoteLibraryException(
275 "Read-Only remote library: " + args[0], false);
651072f3
NR
276 }
277
b9ce9cad
NR
278 List<Object> list = new ArrayList<Object>();
279
280 action.send(null);
281 Object obj = action.rec();
282 while (obj != null) {
283 list.add(obj);
284 action.send(null);
285 obj = action.rec();
286 }
287
288 Story story = rebuildStory(list);
c91f1830
NR
289 Instance.getInstance().getLibrary().save(story, (String) args[0],
290 null);
0fa0fe95 291 return story.getMeta().getLuid();
edf79e5e 292 } else if ("IMPORT".equals(command)) {
651072f3 293 if (!rw) {
c91f1830
NR
294 throw new RemoteLibraryException(
295 "Read-Only remote library: " + args[0], false);
651072f3
NR
296 }
297
9b863b20 298 Progress pg = createPgForwarder(action);
c91f1830
NR
299 MetaData meta = Instance.getInstance().getLibrary()
300 .imprt(new URL((String) args[0]), pg);
9b863b20 301 forcePgDoneSent(pg);
b6b65795 302 return meta.getLuid();
085a2f9a 303 } else if ("DELETE_STORY".equals(command)) {
651072f3 304 if (!rw) {
c91f1830
NR
305 throw new RemoteLibraryException(
306 "Read-Only remote library: " + args[0], false);
651072f3
NR
307 }
308
d66deb8d 309 Instance.getInstance().getLibrary().delete((String) args[0]);
e604986c 310 } else if ("GET_COVER".equals(command)) {
c91f1830
NR
311 return Instance.getInstance().getLibrary()
312 .getCover((String) args[0]);
3989dfc5
NR
313 } else if ("GET_CUSTOM_COVER".equals(command)) {
314 if ("SOURCE".equals(args[0])) {
c91f1830
NR
315 return Instance.getInstance().getLibrary()
316 .getCustomSourceCover((String) args[1]);
3989dfc5 317 } else if ("AUTHOR".equals(args[0])) {
c91f1830
NR
318 return Instance.getInstance().getLibrary()
319 .getCustomAuthorCover((String) args[1]);
3989dfc5
NR
320 } else {
321 return null;
322 }
323 } else if ("SET_COVER".equals(command)) {
651072f3 324 if (!rw) {
c91f1830
NR
325 throw new RemoteLibraryException(
326 "Read-Only remote library: " + args[0] + ", " + args[1],
327 false);
651072f3
NR
328 }
329
3989dfc5 330 if ("SOURCE".equals(args[0])) {
c91f1830
NR
331 Instance.getInstance().getLibrary()
332 .setSourceCover((String) args[1], (String) args[2]);
3989dfc5 333 } else if ("AUTHOR".equals(args[0])) {
c91f1830
NR
334 Instance.getInstance().getLibrary()
335 .setAuthorCover((String) args[1], (String) args[2]);
3989dfc5 336 }
c8d48938 337 } else if ("CHANGE_STA".equals(command)) {
651072f3 338 if (!rw) {
c91f1830
NR
339 throw new RemoteLibraryException(
340 "Read-Only remote library: " + args[0] + ", " + args[1],
341 false);
651072f3
NR
342 }
343
9b863b20 344 Progress pg = createPgForwarder(action);
c91f1830
NR
345 Instance.getInstance().getLibrary().changeSTA((String) args[0],
346 (String) args[1], (String) args[2], (String) args[3], pg);
9b863b20 347 forcePgDoneSent(pg);
5e848e6a 348 } else if ("EXIT".equals(command)) {
651072f3 349 if (!rw) {
533dc2b8
NR
350 throw new RemoteLibraryException(
351 "Read-Only remote library: EXIT", false);
651072f3
NR
352 }
353
c08c6ca1 354 stop(10000, false);
b0e88ebd
NR
355 }
356
357 return null;
358 }
74a40dfb 359
b9ce9cad
NR
360 @Override
361 protected void onError(Exception e) {
7e51d91c 362 if (e instanceof SSLException) {
c1bb921e
NR
363 long now = System.currentTimeMillis();
364 System.out.println(StringUtils.fromTime(now) + ": "
365 + "[Client connection refused (bad key)]");
7e51d91c
NR
366 } else {
367 getTraceHandler().error(e);
368 }
b9ce9cad 369 }
74a40dfb 370
b9ce9cad
NR
371 /**
372 * Break a story in multiple {@link Object}s for easier serialisation.
373 *
374 * @param story
375 * the {@link Story} to break
376 *
377 * @return the list of {@link Object}s
378 */
379 static List<Object> breakStory(Story story) {
380 List<Object> list = new ArrayList<Object>();
74a40dfb
NR
381
382 story = story.clone();
b9ce9cad 383 list.add(story);
74a40dfb 384
b9ce9cad
NR
385 if (story.getMeta().isImageDocument()) {
386 for (Chapter chap : story) {
387 list.add(chap);
388 list.addAll(chap.getParagraphs());
389 chap.setParagraphs(new ArrayList<Paragraph>());
74a40dfb 390 }
b9ce9cad 391 story.setChapters(new ArrayList<Chapter>());
74a40dfb 392 }
74a40dfb 393
b9ce9cad
NR
394 return list;
395 }
74a40dfb 396
b9ce9cad
NR
397 /**
398 * Rebuild a story from a list of broke up {@link Story} parts.
399 *
400 * @param list
401 * the list of {@link Story} parts
402 *
403 * @return the reconstructed {@link Story}
404 */
405 static Story rebuildStory(List<Object> list) {
74a40dfb 406 Story story = null;
b9ce9cad 407 Chapter chap = null;
74a40dfb 408
b9ce9cad
NR
409 for (Object obj : list) {
410 if (obj instanceof Story) {
411 story = (Story) obj;
412 } else if (obj instanceof Chapter) {
413 chap = (Chapter) obj;
414 story.getChapters().add(chap);
415 } else if (obj instanceof Paragraph) {
416 chap.getParagraphs().add((Paragraph) obj);
74a40dfb
NR
417 }
418 }
419
420 return story;
421 }
422
b9ce9cad
NR
423 /**
424 * Update the {@link Progress} with the adequate {@link Object} received
425 * from the network via {@link RemoteLibraryServer}.
426 *
427 * @param pg
428 * the {@link Progress} to update
429 * @param rep
430 * the object received from the network
431 *
432 * @return TRUE if it was a progress event, FALSE if not
433 */
434 static boolean updateProgress(Progress pg, Object rep) {
1f5a9d0c
NR
435 boolean updateProgress = false;
436 if (rep instanceof Integer[] && ((Integer[]) rep).length == 3)
437 updateProgress = true;
438 if (rep instanceof Object[] && ((Object[]) rep).length >= 5
439 && "UPDATE".equals(((Object[]) rep)[0]))
440 updateProgress = true;
441
442 if (updateProgress) {
a5d1f0e6 443 Object[] a = (Object[]) rep;
b9ce9cad 444
1f5a9d0c
NR
445 int offset = 0;
446 if (a[0] instanceof String) {
447 offset = 1;
448 }
449
450 int min = (Integer) a[0 + offset];
451 int max = (Integer) a[1 + offset];
452 int progress = (Integer) a[2 + offset];
c91f1830 453
1f5a9d0c
NR
454 Object meta = null;
455 if (a.length > (3 + offset)) {
456 meta = a[3 + offset];
457 }
c91f1830 458
95c926ea
NR
459 String name = null;
460 if (a.length > (4 + offset)) {
461 name = a[4 + offset] == null ? "" : a[4 + offset].toString();
462 }
1f5a9d0c
NR
463
464 if (min >= 0 && min <= max) {
95c926ea 465 pg.setName(name);
1f5a9d0c
NR
466 pg.setMinMax(min, max);
467 pg.setProgress(progress);
468 if (meta != null) {
469 pg.put("meta", meta);
b9ce9cad 470 }
1f5a9d0c
NR
471
472 return true;
b9ce9cad 473 }
74a40dfb 474 }
b9ce9cad
NR
475
476 return false;
74a40dfb
NR
477 }
478
b9ce9cad
NR
479 /**
480 * Create a {@link Progress} that will forward its progress over the
481 * network.
482 *
483 * @param action
484 * the {@link ConnectActionServerObject} to use to forward it
485 *
486 * @return the {@link Progress}
487 */
49f3dec5 488 private Progress createPgForwarder(final ConnectActionServerObject action) {
9b863b20
NR
489 final Boolean[] isDoneForwarded = new Boolean[] { false };
490 final Progress pg = new Progress() {
491 @Override
492 public boolean isDone() {
493 return isDoneForwarded[0];
494 }
495 };
496
b9ce9cad 497 final Integer[] p = new Integer[] { -1, -1, -1 };
a5d1f0e6 498 final Object[] pMeta = new MetaData[1];
95c926ea 499 final String[] pName = new String[1];
9b863b20 500 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
501 pg.addProgressListener(new ProgressListener() {
502 @Override
503 public void progress(Progress progress, String name) {
a5d1f0e6
NR
504 Object meta = pg.get("meta");
505 if (meta instanceof MetaData) {
c91f1830 506 meta = removeCover((MetaData) meta);
a5d1f0e6 507 }
c91f1830 508
b9ce9cad
NR
509 int min = pg.getMin();
510 int max = pg.getMax();
c91f1830
NR
511 int rel = min + (int) Math
512 .round(pg.getRelativeProgress() * (max - min));
513
a5d1f0e6 514 boolean samePg = p[0] == min && p[1] == max && p[2] == rel;
c91f1830 515
9b863b20
NR
516 // Do not re-send the same value twice over the wire,
517 // unless more than 2 seconds have elapsed (to maintain the
518 // connection)
c91f1830 519 if (!samePg || !same(pMeta[0], meta) || !same(pName[0], name) //
9b863b20 520 || (new Date().getTime() - lastTime[0] > 2000)) {
b9ce9cad
NR
521 p[0] = min;
522 p[1] = max;
a5d1f0e6
NR
523 p[2] = rel;
524 pMeta[0] = meta;
95c926ea 525 pName[0] = name;
b9ce9cad
NR
526
527 try {
95c926ea
NR
528 action.send(new Object[] { "UPDATE", min, max, rel,
529 meta, name });
b9ce9cad
NR
530 action.rec();
531 } catch (Exception e) {
49f3dec5 532 getTraceHandler().error(e);
b9ce9cad 533 }
9b863b20 534
9b863b20 535 lastTime[0] = new Date().getTime();
b9ce9cad 536 }
652fd9b0
NR
537
538 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
539 }
540 });
541
542 return pg;
74a40dfb 543 }
c91f1830 544
a5d1f0e6
NR
545 private boolean same(Object obj1, Object obj2) {
546 if (obj1 == null || obj2 == null)
547 return obj1 == null && obj2 == null;
548
549 return obj1.equals(obj2);
550 }
9b863b20
NR
551
552 // with 30 seconds timeout
49f3dec5 553 private void forcePgDoneSent(Progress pg) {
9b863b20
NR
554 long start = new Date().getTime();
555 pg.done();
556 while (!pg.isDone() && new Date().getTime() - start < 30000) {
557 try {
558 Thread.sleep(100);
559 } catch (InterruptedException e) {
49f3dec5 560 getTraceHandler().error(e);
9b863b20
NR
561 }
562 }
563 }
c91f1830 564
a5d1f0e6 565 private MetaData removeCover(MetaData meta) {
eccb0cbc
NR
566 MetaData light = null;
567 if (meta != null) {
568 if (meta.getCover() == null) {
569 light = meta;
570 } else {
571 light = meta.clone();
572 light.setCover(null);
573 }
a5d1f0e6 574 }
c91f1830 575
a5d1f0e6
NR
576 return light;
577 }
c91f1830
NR
578
579 private boolean isAllowed(MetaData meta, List<String> whitelist,
580 List<String> blacklist) {
581 if (!whitelist.isEmpty() && !whitelist.contains(meta.getSource())) {
582 return false;
583 }
584
585 if (blacklist.contains(meta.getSource())) {
586 return false;
587 }
588
589 return true;
590 }
b0e88ebd 591}