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