remote: exceptions
[fanfix.git] / src / be / nikiroo / fanfix / library / RemoteLibraryServer.java
1 package be.nikiroo.fanfix.library;
2
3 import java.io.IOException;
4 import java.net.URL;
5 import java.nio.file.AccessDeniedException;
6 import java.util.ArrayList;
7 import java.util.Date;
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.Map;
11
12 import javax.net.ssl.SSLException;
13
14 import be.nikiroo.fanfix.Instance;
15 import be.nikiroo.fanfix.bundles.Config;
16 import be.nikiroo.fanfix.data.Chapter;
17 import be.nikiroo.fanfix.data.MetaData;
18 import be.nikiroo.fanfix.data.Paragraph;
19 import be.nikiroo.fanfix.data.Story;
20 import be.nikiroo.utils.Progress;
21 import be.nikiroo.utils.Progress.ProgressListener;
22 import be.nikiroo.utils.StringUtils;
23 import be.nikiroo.utils.Version;
24 import be.nikiroo.utils.serial.server.ConnectActionServerObject;
25 import be.nikiroo.utils.serial.server.ServerObject;
26
27 /**
28 * Create a new remote server that will listen for orders on the given port.
29 * <p>
30 * The available commands are given as arrays of objects (first item is the
31 * command, the rest are the arguments).
32 * <p>
33 * All the commands are always prefixed by the subkey (which can be EMPTY if
34 * none).
35 * <p>
36 * <ul>
37 * <li>PING: will return the mode if the key is accepted (mode can be: "r/o" or
38 * "r/w")</li>
39 * <li>GET_METADATA *: will return the metadata of all the stories in the
40 * library (array)</li> *
41 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
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
45 * command) with the given LUID, then return the LUID</li>
46 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
47 * </li>
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>
57 * </ul>
58 *
59 * @author niki
60 */
61 public class RemoteLibraryServer extends ServerObject {
62 private Map<Long, String> commands = new HashMap<Long, String>();
63 private Map<Long, Long> times = new HashMap<Long, Long>();
64 private Map<Long, Boolean> wls = new HashMap<Long, Boolean>();
65 private Map<Long, Boolean> rws = new HashMap<Long, Boolean>();
66
67 /**
68 * Create a new remote server (will not be active until
69 * {@link RemoteLibraryServer#start()} is called).
70 * <p>
71 * Note: the key we use here is the encryption key (it must not contain a
72 * subkey).
73 *
74 * @param key
75 * the key that will restrict access to this server
76 * @param port
77 * the port to listen on
78 *
79 * @throws IOException
80 * in case of I/O error
81 */
82 public RemoteLibraryServer(String key, int port) throws IOException {
83 super("Fanfix remote library", port, key);
84 setTraceHandler(Instance.getTraceHandler());
85 }
86
87 @Override
88 protected Object onRequest(ConnectActionServerObject action,
89 Version clientVersion, Object data, long id) throws Exception {
90 long start = new Date().getTime();
91
92 // defaults are positive (as previous versions without the feature)
93 boolean rw = true;
94 boolean wl = true;
95
96 String subkey = "";
97 String command = "";
98 Object[] args = new Object[0];
99 if (data instanceof Object[]) {
100 Object[] dataArray = (Object[]) data;
101 if (dataArray.length > 0) {
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 }
123
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
134 whitelist = new ArrayList<String>();
135 }
136 }
137 }
138
139 String mode = display(wl, rw);
140
141 String trace = mode + "[ " + command + "] ";
142 for (Object arg : args) {
143 trace += arg + " ";
144 }
145 System.out.println(trace);
146
147 Object rep = null;
148 try {
149 rep = doRequest(action, command, args, rw, whitelist);
150 } catch (IOException e) {
151 rep = new RemoteLibraryException(e);
152 }
153
154 commands.put(id, command);
155 wls.put(id, wl);
156 rws.put(id, rw);
157 times.put(id, (new Date().getTime() - start));
158
159 return rep;
160 }
161
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
174 @Override
175 protected void onRequestDone(long id, long bytesReceived, long bytesSent) {
176 boolean whitelist = wls.get(id);
177 boolean rw = rws.get(id);
178 wls.remove(id);
179 rws.remove(id);
180
181 String rec = StringUtils.formatNumber(bytesReceived) + "b";
182 String sent = StringUtils.formatNumber(bytesSent) + "b";
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
187 commands.remove(id);
188 times.remove(id);
189 }
190
191 private Object doRequest(ConnectActionServerObject action, String command,
192 Object[] args, boolean rw, List<String> whitelist)
193 throws NoSuchFieldException, NoSuchMethodException,
194 ClassNotFoundException, IOException {
195 if ("PING".equals(command)) {
196 return rw ? "r/w" : "r/o";
197 } else if ("GET_METADATA".equals(command)) {
198 List<MetaData> metas = new ArrayList<MetaData>();
199
200 if ("*".equals(args[0])) {
201 Progress pg = createPgForwarder(action);
202
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
215 forcePgDoneSent(pg);
216 } else {
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);
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 }
236 }
237
238 return metas.toArray(new MetaData[0]);
239 } else if ("GET_STORY".equals(command)) {
240 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
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
251 meta = meta.clone();
252 meta.setCover(null);
253
254 action.send(meta);
255 action.rec();
256
257 Story story = Instance.getLibrary()
258 .getStory((String) args[0], null);
259 for (Object obj : breakStory(story)) {
260 action.send(obj);
261 action.rec();
262 }
263 } else if ("SAVE_STORY".equals(command)) {
264 if (!rw) {
265 throw new AccessDeniedException("" + args[0], null,
266 "Read-Only remote library");
267 }
268
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);
280 Instance.getLibrary().save(story, (String) args[0], null);
281 return story.getMeta().getLuid();
282 } else if ("IMPORT".equals(command)) {
283 if (!rw) {
284 throw new AccessDeniedException("" + args[0], null,
285 "Read-Only remote library");
286 }
287
288 Progress pg = createPgForwarder(action);
289 Story story = Instance.getLibrary().imprt(
290 new URL((String) args[0]), pg);
291 forcePgDoneSent(pg);
292 return story.getMeta().getLuid();
293 } else if ("DELETE_STORY".equals(command)) {
294 if (!rw) {
295 throw new AccessDeniedException("" + args[0], null,
296 "Read-Only remote library");
297 }
298
299 Instance.getLibrary().delete((String) args[0]);
300 } else if ("GET_COVER".equals(command)) {
301 return Instance.getLibrary().getCover((String) args[0]);
302 } else if ("GET_CUSTOM_COVER".equals(command)) {
303 if ("SOURCE".equals(args[0])) {
304 return Instance.getLibrary().getCustomSourceCover(
305 (String) args[1]);
306 } else if ("AUTHOR".equals(args[0])) {
307 return Instance.getLibrary().getCustomAuthorCover(
308 (String) args[1]);
309 } else {
310 return null;
311 }
312 } else if ("SET_COVER".equals(command)) {
313 if (!rw) {
314 throw new AccessDeniedException("" + args[0], "" + args[1],
315 "Read-Only remote library");
316 }
317
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 }
325 } else if ("CHANGE_STA".equals(command)) {
326 if (!rw) {
327 throw new AccessDeniedException("" + args[0], "" + args[1],
328 "Read-Only remote library");
329 }
330
331 Progress pg = createPgForwarder(action);
332 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
333 (String) args[2], (String) args[3], pg);
334 forcePgDoneSent(pg);
335 } else if ("EXIT".equals(command)) {
336 if (!rw) {
337 throw new AccessDeniedException("EXIT", "",
338 "Read-Only remote library, cannot close it");
339 }
340
341 stop(0, false);
342 }
343
344 return null;
345 }
346
347 @Override
348 protected void onError(Exception e) {
349 if (e instanceof SSLException) {
350 System.out.println("[Client connection refused (bad key)]");
351 } else {
352 getTraceHandler().error(e);
353 }
354 }
355
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>();
366
367 story = story.clone();
368 list.add(story);
369
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>());
375 }
376 story.setChapters(new ArrayList<Chapter>());
377 }
378
379 return list;
380 }
381
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) {
391 Story story = null;
392 Chapter chap = null;
393
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);
402 }
403 }
404
405 return story;
406 }
407
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 }
434 }
435
436 return false;
437 }
438
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 */
448 private Progress createPgForwarder(final ConnectActionServerObject action) {
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
457 final Integer[] p = new Integer[] { -1, -1, -1 };
458 final Long[] lastTime = new Long[] { new Date().getTime() };
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();
464 int relativeProgress = min
465 + (int) Math.round(pg.getRelativeProgress()
466 * (max - min));
467
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)) {
473 p[0] = min;
474 p[1] = max;
475 p[2] = relativeProgress;
476
477 try {
478 action.send(new Integer[] { min, max, relativeProgress });
479 action.rec();
480 } catch (Exception e) {
481 getTraceHandler().error(e);
482 }
483
484 lastTime[0] = new Date().getTime();
485 }
486
487 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
488 }
489 });
490
491 return pg;
492 }
493
494 // with 30 seconds timeout
495 private void forcePgDoneSent(Progress pg) {
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) {
502 getTraceHandler().error(e);
503 }
504 }
505 }
506 }