remote: exceptions
[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;
651072f3 5import java.nio.file.AccessDeniedException;
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 }
49f3dec5 145 System.out.println(trace);
b0e88ebd 146
c1b31971 147 Object rep = null;
c1b31971
NR
148 try {
149 rep = doRequest(action, command, args, rw, whitelist);
5db598bc
NR
150 } catch (IOException e) {
151 rep = new RemoteLibraryException(e);
c1b31971 152 }
9f51d8ab 153
9b558341 154 commands.put(id, command);
fb25273c
NR
155 wls.put(id, wl);
156 rws.put(id, rw);
9b558341 157 times.put(id, (new Date().getTime() - start));
9f51d8ab
NR
158
159 return rep;
160 }
161
fb25273c
NR
162 private String display(boolean whitelist, boolean rw) {
163 String mode = "";
164 if (!rw) {
165 mode += "RO: ";
166 }
167 if (whitelist) {
168 mode += "WL: ";
169 }
170
171 return mode;
172 }
173
9b558341
NR
174 @Override
175 protected void onRequestDone(long id, long bytesReceived, long bytesSent) {
fb25273c
NR
176 boolean whitelist = wls.get(id);
177 boolean rw = rws.get(id);
178 wls.remove(id);
179 rws.remove(id);
180
9b558341
NR
181 String rec = StringUtils.formatNumber(bytesReceived) + "b";
182 String sent = StringUtils.formatNumber(bytesSent) + "b";
fb25273c
NR
183 System.out.println(String.format("%s[>%s]: (%s sent, %s rec) in %d ms",
184 display(whitelist, rw), commands.get(id), sent, rec,
185 times.get(id)));
186
9b558341
NR
187 commands.remove(id);
188 times.remove(id);
189 }
190
9f51d8ab 191 private Object doRequest(ConnectActionServerObject action, String command,
fb25273c
NR
192 Object[] args, boolean rw, List<String> whitelist)
193 throws NoSuchFieldException, NoSuchMethodException,
9f51d8ab 194 ClassNotFoundException, IOException {
3bbc86a5 195 if ("PING".equals(command)) {
fb25273c 196 return rw ? "r/w" : "r/o";
3bbc86a5 197 } else if ("GET_METADATA".equals(command)) {
651072f3
NR
198 List<MetaData> metas = new ArrayList<MetaData>();
199
7efece85 200 if ("*".equals(args[0])) {
9b863b20 201 Progress pg = createPgForwarder(action);
9f51d8ab 202
9f51d8ab
NR
203 for (MetaData meta : Instance.getLibrary().getMetas(pg)) {
204 MetaData light;
205 if (meta.getCover() == null) {
206 light = meta;
207 } else {
208 light = meta.clone();
209 light.setCover(null);
210 }
211
212 metas.add(light);
213 }
214
9b863b20 215 forcePgDoneSent(pg);
651072f3 216 } else {
210465c3
NR
217 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
218 MetaData light;
219 if (meta.getCover() == null) {
220 light = meta;
221 } else {
222 light = meta.clone();
223 light.setCover(null);
224 }
225
226 metas.add(light);
651072f3
NR
227 }
228
229 if (!whitelist.isEmpty()) {
230 for (int i = 0; i < metas.size(); i++) {
231 if (!whitelist.contains(metas.get(i).getSource())) {
232 metas.remove(i);
233 i--;
234 }
235 }
a85e8077 236 }
e272f05f 237
651072f3 238 return metas.toArray(new MetaData[0]);
a85e8077 239 } else if ("GET_STORY".equals(command)) {
7efece85 240 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
651072f3
NR
241 if (meta == null) {
242 return null;
243 }
244
245 if (!whitelist.isEmpty()) {
246 if (!whitelist.contains(meta.getSource())) {
247 return null;
248 }
249 }
250
b9ce9cad
NR
251 meta = meta.clone();
252 meta.setCover(null);
253
254 action.send(meta);
255 action.rec();
256
37abe20c
NR
257 Story story = Instance.getLibrary()
258 .getStory((String) args[0], null);
b9ce9cad
NR
259 for (Object obj : breakStory(story)) {
260 action.send(obj);
261 action.rec();
262 }
085a2f9a 263 } else if ("SAVE_STORY".equals(command)) {
651072f3
NR
264 if (!rw) {
265 throw new AccessDeniedException("" + args[0], null,
266 "Read-Only remote library");
267 }
268
b9ce9cad
NR
269 List<Object> list = new ArrayList<Object>();
270
271 action.send(null);
272 Object obj = action.rec();
273 while (obj != null) {
274 list.add(obj);
275 action.send(null);
276 obj = action.rec();
277 }
278
279 Story story = rebuildStory(list);
7efece85 280 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 281 return story.getMeta().getLuid();
edf79e5e 282 } else if ("IMPORT".equals(command)) {
651072f3
NR
283 if (!rw) {
284 throw new AccessDeniedException("" + args[0], null,
285 "Read-Only remote library");
286 }
287
9b863b20 288 Progress pg = createPgForwarder(action);
37abe20c
NR
289 Story story = Instance.getLibrary().imprt(
290 new URL((String) args[0]), pg);
9b863b20 291 forcePgDoneSent(pg);
edf79e5e 292 return story.getMeta().getLuid();
085a2f9a 293 } else if ("DELETE_STORY".equals(command)) {
651072f3
NR
294 if (!rw) {
295 throw new AccessDeniedException("" + args[0], null,
296 "Read-Only remote library");
297 }
298
7efece85 299 Instance.getLibrary().delete((String) args[0]);
e604986c 300 } else if ("GET_COVER".equals(command)) {
7efece85 301 return Instance.getLibrary().getCover((String) args[0]);
3989dfc5
NR
302 } else if ("GET_CUSTOM_COVER".equals(command)) {
303 if ("SOURCE".equals(args[0])) {
37abe20c
NR
304 return Instance.getLibrary().getCustomSourceCover(
305 (String) args[1]);
3989dfc5 306 } else if ("AUTHOR".equals(args[0])) {
37abe20c
NR
307 return Instance.getLibrary().getCustomAuthorCover(
308 (String) args[1]);
3989dfc5
NR
309 } else {
310 return null;
311 }
312 } else if ("SET_COVER".equals(command)) {
651072f3
NR
313 if (!rw) {
314 throw new AccessDeniedException("" + args[0], "" + args[1],
315 "Read-Only remote library");
316 }
317
3989dfc5
NR
318 if ("SOURCE".equals(args[0])) {
319 Instance.getLibrary().setSourceCover((String) args[1],
320 (String) args[2]);
321 } else if ("AUTHOR".equals(args[0])) {
322 Instance.getLibrary().setAuthorCover((String) args[1],
323 (String) args[2]);
324 }
c8d48938 325 } else if ("CHANGE_STA".equals(command)) {
651072f3
NR
326 if (!rw) {
327 throw new AccessDeniedException("" + args[0], "" + args[1],
328 "Read-Only remote library");
329 }
330
9b863b20 331 Progress pg = createPgForwarder(action);
c8d48938
NR
332 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
333 (String) args[2], (String) args[3], pg);
9b863b20 334 forcePgDoneSent(pg);
5e848e6a 335 } else if ("EXIT".equals(command)) {
651072f3
NR
336 if (!rw) {
337 throw new AccessDeniedException("EXIT", "",
338 "Read-Only remote library, cannot close it");
339 }
340
5e848e6a 341 stop(0, false);
b0e88ebd
NR
342 }
343
344 return null;
345 }
74a40dfb 346
b9ce9cad
NR
347 @Override
348 protected void onError(Exception e) {
7e51d91c
NR
349 if (e instanceof SSLException) {
350 System.out.println("[Client connection refused (bad key)]");
351 } else {
352 getTraceHandler().error(e);
353 }
b9ce9cad 354 }
74a40dfb 355
b9ce9cad
NR
356 /**
357 * Break a story in multiple {@link Object}s for easier serialisation.
358 *
359 * @param story
360 * the {@link Story} to break
361 *
362 * @return the list of {@link Object}s
363 */
364 static List<Object> breakStory(Story story) {
365 List<Object> list = new ArrayList<Object>();
74a40dfb
NR
366
367 story = story.clone();
b9ce9cad 368 list.add(story);
74a40dfb 369
b9ce9cad
NR
370 if (story.getMeta().isImageDocument()) {
371 for (Chapter chap : story) {
372 list.add(chap);
373 list.addAll(chap.getParagraphs());
374 chap.setParagraphs(new ArrayList<Paragraph>());
74a40dfb 375 }
b9ce9cad 376 story.setChapters(new ArrayList<Chapter>());
74a40dfb 377 }
74a40dfb 378
b9ce9cad
NR
379 return list;
380 }
74a40dfb 381
b9ce9cad
NR
382 /**
383 * Rebuild a story from a list of broke up {@link Story} parts.
384 *
385 * @param list
386 * the list of {@link Story} parts
387 *
388 * @return the reconstructed {@link Story}
389 */
390 static Story rebuildStory(List<Object> list) {
74a40dfb 391 Story story = null;
b9ce9cad 392 Chapter chap = null;
74a40dfb 393
b9ce9cad
NR
394 for (Object obj : list) {
395 if (obj instanceof Story) {
396 story = (Story) obj;
397 } else if (obj instanceof Chapter) {
398 chap = (Chapter) obj;
399 story.getChapters().add(chap);
400 } else if (obj instanceof Paragraph) {
401 chap.getParagraphs().add((Paragraph) obj);
74a40dfb
NR
402 }
403 }
404
405 return story;
406 }
407
b9ce9cad
NR
408 /**
409 * Update the {@link Progress} with the adequate {@link Object} received
410 * from the network via {@link RemoteLibraryServer}.
411 *
412 * @param pg
413 * the {@link Progress} to update
414 * @param rep
415 * the object received from the network
416 *
417 * @return TRUE if it was a progress event, FALSE if not
418 */
419 static boolean updateProgress(Progress pg, Object rep) {
420 if (rep instanceof Integer[]) {
421 Integer[] a = (Integer[]) rep;
422 if (a.length == 3) {
423 int min = a[0];
424 int max = a[1];
425 int progress = a[2];
426
427 if (min >= 0 && min <= max) {
428 pg.setMinMax(min, max);
429 pg.setProgress(progress);
430
431 return true;
432 }
433 }
74a40dfb 434 }
b9ce9cad
NR
435
436 return false;
74a40dfb
NR
437 }
438
b9ce9cad
NR
439 /**
440 * Create a {@link Progress} that will forward its progress over the
441 * network.
442 *
443 * @param action
444 * the {@link ConnectActionServerObject} to use to forward it
445 *
446 * @return the {@link Progress}
447 */
49f3dec5 448 private Progress createPgForwarder(final ConnectActionServerObject action) {
9b863b20
NR
449 final Boolean[] isDoneForwarded = new Boolean[] { false };
450 final Progress pg = new Progress() {
451 @Override
452 public boolean isDone() {
453 return isDoneForwarded[0];
454 }
455 };
456
b9ce9cad 457 final Integer[] p = new Integer[] { -1, -1, -1 };
9b863b20 458 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
459 pg.addProgressListener(new ProgressListener() {
460 @Override
461 public void progress(Progress progress, String name) {
462 int min = pg.getMin();
463 int max = pg.getMax();
37abe20c
NR
464 int relativeProgress = min
465 + (int) Math.round(pg.getRelativeProgress()
466 * (max - min));
b9ce9cad 467
9b863b20
NR
468 // Do not re-send the same value twice over the wire,
469 // unless more than 2 seconds have elapsed (to maintain the
470 // connection)
471 if ((p[0] != min || p[1] != max || p[2] != relativeProgress)
472 || (new Date().getTime() - lastTime[0] > 2000)) {
b9ce9cad
NR
473 p[0] = min;
474 p[1] = max;
475 p[2] = relativeProgress;
476
477 try {
37abe20c 478 action.send(new Integer[] { min, max, relativeProgress });
b9ce9cad
NR
479 action.rec();
480 } catch (Exception e) {
49f3dec5 481 getTraceHandler().error(e);
b9ce9cad 482 }
9b863b20 483
9b863b20 484 lastTime[0] = new Date().getTime();
b9ce9cad 485 }
652fd9b0
NR
486
487 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
488 }
489 });
490
491 return pg;
74a40dfb 492 }
9b863b20
NR
493
494 // with 30 seconds timeout
49f3dec5 495 private void forcePgDoneSent(Progress pg) {
9b863b20
NR
496 long start = new Date().getTime();
497 pg.done();
498 while (!pg.isDone() && new Date().getTime() - start < 30000) {
499 try {
500 Thread.sleep(100);
501 } catch (InterruptedException e) {
49f3dec5 502 getTraceHandler().error(e);
9b863b20
NR
503 }
504 }
505 }
b0e88ebd 506}