1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.IOException
;
5 import java
.util
.ArrayList
;
7 import java
.util
.HashMap
;
11 import javax
.net
.ssl
.SSLException
;
13 import be
.nikiroo
.fanfix
.Instance
;
14 import be
.nikiroo
.fanfix
.bundles
.Config
;
15 import be
.nikiroo
.fanfix
.data
.Chapter
;
16 import be
.nikiroo
.fanfix
.data
.MetaData
;
17 import be
.nikiroo
.fanfix
.data
.Paragraph
;
18 import be
.nikiroo
.fanfix
.data
.Story
;
19 import be
.nikiroo
.utils
.Progress
;
20 import be
.nikiroo
.utils
.Progress
.ProgressListener
;
21 import be
.nikiroo
.utils
.StringUtils
;
22 import be
.nikiroo
.utils
.Version
;
23 import be
.nikiroo
.utils
.serial
.server
.ConnectActionServerObject
;
24 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
27 * Create a new remote server that will listen for orders on the given port.
29 * The available commands are given as arrays of objects (first item is the
30 * command, the rest are the arguments).
32 * All the commands are always prefixed by the subkey (which can be EMPTY if
36 * <li>PING: will return the mode if the key is accepted (mode can be: "r/o" or
38 * <li>GET_METADATA *: will return the metadata of all the stories in the
39 * library (array)</li> *
40 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
41 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
43 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
44 * command) with the given LUID, then return the LUID</li>
45 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
47 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
48 * <li>GET_COVER [luid]: return the cover of the story</li>
49 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
51 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
52 * the given source/author to the cover of the story denoted by luid</li>
53 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
55 * <li>EXIT: stop the server</li>
60 public class RemoteLibraryServer
extends ServerObject
{
61 private Map
<Long
, String
> commands
= new HashMap
<Long
, String
>();
62 private Map
<Long
, Long
> times
= new HashMap
<Long
, Long
>();
63 private Map
<Long
, Boolean
> wls
= new HashMap
<Long
, Boolean
>();
64 private Map
<Long
, Boolean
> rws
= new HashMap
<Long
, Boolean
>();
67 * Create a new remote server (will not be active until
68 * {@link RemoteLibraryServer#start()} is called).
70 * Note: the key we use here is the encryption key (it must not contain a
74 * in case of I/O error
76 public RemoteLibraryServer() throws IOException
{
77 super("Fanfix remote library",
78 Instance
.getInstance().getConfig()
79 .getInteger(Config
.SERVER_PORT
),
80 Instance
.getInstance().getConfig()
81 .getString(Config
.SERVER_KEY
));
83 setTraceHandler(Instance
.getInstance().getTraceHandler());
87 protected Object
onRequest(ConnectActionServerObject action
,
88 Version clientVersion
, Object data
, long id
) throws Exception
{
89 long start
= new Date().getTime();
91 // defaults are positive (as previous versions without the feature)
97 Object
[] args
= new Object
[0];
98 if (data
instanceof Object
[]) {
99 Object
[] dataArray
= (Object
[]) data
;
100 if (dataArray
.length
> 0) {
101 subkey
= "" + dataArray
[0];
103 if (dataArray
.length
> 1) {
104 command
= "" + dataArray
[1];
106 args
= new Object
[dataArray
.length
- 2];
107 for (int i
= 2; i
< dataArray
.length
; i
++) {
108 args
[i
- 2] = dataArray
[i
];
113 List
<String
> whitelist
= Instance
.getInstance().getConfig().getList(Config
.SERVER_WHITELIST
);
114 if (whitelist
== null) {
115 whitelist
= new ArrayList
<String
>();
118 if (whitelist
.isEmpty()) {
122 rw
= Instance
.getInstance().getConfig().getBoolean(Config
.SERVER_RW
, rw
);
123 if (!subkey
.isEmpty()) {
124 List
<String
> allowed
= Instance
.getInstance().getConfig().getList(Config
.SERVER_ALLOWED_SUBKEYS
);
125 if (allowed
.contains(subkey
)) {
126 if ((subkey
+ "|").contains("|rw|")) {
129 if ((subkey
+ "|").contains("|wl|")) {
130 wl
= false; // |wl| = bypass whitelist
131 whitelist
= new ArrayList
<String
>();
136 String mode
= display(wl
, rw
);
138 String trace
= mode
+ "[ " + command
+ "] ";
139 for (Object arg
: args
) {
142 long now
= System
.currentTimeMillis();
143 System
.out
.println(StringUtils
.fromTime(now
) + ": " + trace
);
147 rep
= doRequest(action
, command
, args
, rw
, whitelist
);
148 } catch (IOException e
) {
149 rep
= new RemoteLibraryException(e
, true);
152 commands
.put(id
, command
);
155 times
.put(id
, (new Date().getTime() - start
));
160 private String
display(boolean whitelist
, boolean rw
) {
173 protected void onRequestDone(long id
, long bytesReceived
, long bytesSent
) {
174 boolean whitelist
= wls
.get(id
);
175 boolean rw
= rws
.get(id
);
179 String rec
= StringUtils
.formatNumber(bytesReceived
) + "b";
180 String sent
= StringUtils
.formatNumber(bytesSent
) + "b";
181 long now
= System
.currentTimeMillis();
182 System
.out
.println(StringUtils
.fromTime(now
)
184 + String
.format("%s[>%s]: (%s sent, %s rec) in %d ms",
185 display(whitelist
, rw
), commands
.get(id
), sent
, rec
,
192 private Object
doRequest(ConnectActionServerObject action
, String command
,
193 Object
[] args
, boolean rw
, List
<String
> whitelist
)
194 throws NoSuchFieldException
, NoSuchMethodException
,
195 ClassNotFoundException
, IOException
{
196 if ("PING".equals(command
)) {
197 return rw ?
"r/w" : "r/o";
198 } else if ("GET_METADATA".equals(command
)) {
199 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
201 if ("*".equals(args
[0])) {
202 Progress pg
= createPgForwarder(action
);
204 for (MetaData meta
: Instance
.getInstance().getLibrary().getMetas(pg
)) {
205 metas
.add(removeCover(meta
));
210 MetaData meta
= Instance
.getInstance().getLibrary().getInfo((String
) args
[0]);
212 if (meta
.getCover() == null) {
215 light
= meta
.clone();
216 light
.setCover(null);
222 if (!whitelist
.isEmpty()) {
223 for (int i
= 0; i
< metas
.size(); i
++) {
224 if (!whitelist
.contains(metas
.get(i
).getSource())) {
231 return metas
.toArray(new MetaData
[0]);
232 } else if ("GET_STORY".equals(command
)) {
233 MetaData meta
= Instance
.getInstance().getLibrary().getInfo((String
) args
[0]);
238 if (!whitelist
.isEmpty()) {
239 if (!whitelist
.contains(meta
.getSource())) {
250 Story story
= Instance
.getInstance().getLibrary().getStory((String
) args
[0], null);
251 for (Object obj
: breakStory(story
)) {
255 } else if ("SAVE_STORY".equals(command
)) {
257 throw new RemoteLibraryException("Read-Only remote library: "
261 List
<Object
> list
= new ArrayList
<Object
>();
264 Object obj
= action
.rec();
265 while (obj
!= null) {
271 Story story
= rebuildStory(list
);
272 Instance
.getInstance().getLibrary().save(story
, (String
) args
[0], null);
273 return story
.getMeta().getLuid();
274 } else if ("IMPORT".equals(command
)) {
276 throw new RemoteLibraryException("Read-Only remote library: "
280 Progress pg
= createPgForwarder(action
);
281 MetaData meta
= Instance
.getInstance().getLibrary().imprt(new URL((String
) args
[0]), pg
);
283 return meta
.getLuid();
284 } else if ("DELETE_STORY".equals(command
)) {
286 throw new RemoteLibraryException("Read-Only remote library: "
290 Instance
.getInstance().getLibrary().delete((String
) args
[0]);
291 } else if ("GET_COVER".equals(command
)) {
292 return Instance
.getInstance().getLibrary().getCover((String
) args
[0]);
293 } else if ("GET_CUSTOM_COVER".equals(command
)) {
294 if ("SOURCE".equals(args
[0])) {
295 return Instance
.getInstance().getLibrary().getCustomSourceCover((String
) args
[1]);
296 } else if ("AUTHOR".equals(args
[0])) {
297 return Instance
.getInstance().getLibrary().getCustomAuthorCover((String
) args
[1]);
301 } else if ("SET_COVER".equals(command
)) {
303 throw new RemoteLibraryException("Read-Only remote library: "
304 + args
[0] + ", " + args
[1], false);
307 if ("SOURCE".equals(args
[0])) {
308 Instance
.getInstance().getLibrary().setSourceCover((String
) args
[1], (String
) args
[2]);
309 } else if ("AUTHOR".equals(args
[0])) {
310 Instance
.getInstance().getLibrary().setAuthorCover((String
) args
[1], (String
) args
[2]);
312 } else if ("CHANGE_STA".equals(command
)) {
314 throw new RemoteLibraryException("Read-Only remote library: " + args
[0] + ", " + args
[1], false);
317 Progress pg
= createPgForwarder(action
);
318 Instance
.getInstance().getLibrary().changeSTA((String
) args
[0], (String
) args
[1], (String
) args
[2],
319 (String
) args
[3], pg
);
321 } else if ("EXIT".equals(command
)) {
323 throw new RemoteLibraryException(
324 "Read-Only remote library: EXIT", false);
334 protected void onError(Exception e
) {
335 if (e
instanceof SSLException
) {
336 long now
= System
.currentTimeMillis();
337 System
.out
.println(StringUtils
.fromTime(now
) + ": "
338 + "[Client connection refused (bad key)]");
340 getTraceHandler().error(e
);
345 * Break a story in multiple {@link Object}s for easier serialisation.
348 * the {@link Story} to break
350 * @return the list of {@link Object}s
352 static List
<Object
> breakStory(Story story
) {
353 List
<Object
> list
= new ArrayList
<Object
>();
355 story
= story
.clone();
358 if (story
.getMeta().isImageDocument()) {
359 for (Chapter chap
: story
) {
361 list
.addAll(chap
.getParagraphs());
362 chap
.setParagraphs(new ArrayList
<Paragraph
>());
364 story
.setChapters(new ArrayList
<Chapter
>());
371 * Rebuild a story from a list of broke up {@link Story} parts.
374 * the list of {@link Story} parts
376 * @return the reconstructed {@link Story}
378 static Story
rebuildStory(List
<Object
> list
) {
382 for (Object obj
: list
) {
383 if (obj
instanceof Story
) {
385 } else if (obj
instanceof Chapter
) {
386 chap
= (Chapter
) obj
;
387 story
.getChapters().add(chap
);
388 } else if (obj
instanceof Paragraph
) {
389 chap
.getParagraphs().add((Paragraph
) obj
);
397 * Update the {@link Progress} with the adequate {@link Object} received
398 * from the network via {@link RemoteLibraryServer}.
401 * the {@link Progress} to update
403 * the object received from the network
405 * @return TRUE if it was a progress event, FALSE if not
407 static boolean updateProgress(Progress pg
, Object rep
) {
408 boolean updateProgress
= false;
409 if (rep
instanceof Integer
[] && ((Integer
[]) rep
).length
== 3)
410 updateProgress
= true;
411 if (rep
instanceof Object
[] && ((Object
[]) rep
).length
>= 5
412 && "UPDATE".equals(((Object
[]) rep
)[0]))
413 updateProgress
= true;
415 if (updateProgress
) {
416 Object
[] a
= (Object
[]) rep
;
419 if (a
[0] instanceof String
) {
423 int min
= (Integer
) a
[0 + offset
];
424 int max
= (Integer
) a
[1 + offset
];
425 int progress
= (Integer
) a
[2 + offset
];
428 if (a
.length
> (3 + offset
)) {
429 meta
= a
[3 + offset
];
433 if (a
.length
> (4 + offset
)) {
434 name
= a
[4 + offset
] == null ?
"" : a
[4 + offset
].toString();
438 if (min
>= 0 && min
<= max
) {
440 pg
.setMinMax(min
, max
);
441 pg
.setProgress(progress
);
443 pg
.put("meta", meta
);
454 * Create a {@link Progress} that will forward its progress over the
458 * the {@link ConnectActionServerObject} to use to forward it
460 * @return the {@link Progress}
462 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
463 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
464 final Progress pg
= new Progress() {
466 public boolean isDone() {
467 return isDoneForwarded
[0];
471 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
472 final Object
[] pMeta
= new MetaData
[1];
473 final String
[] pName
= new String
[1];
474 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
475 pg
.addProgressListener(new ProgressListener() {
477 public void progress(Progress progress
, String name
) {
478 Object meta
= pg
.get("meta");
479 if (meta
instanceof MetaData
) {
480 meta
= removeCover((MetaData
)meta
);
483 int min
= pg
.getMin();
484 int max
= pg
.getMax();
486 + (int) Math
.round(pg
.getRelativeProgress()
489 boolean samePg
= p
[0] == min
&& p
[1] == max
&& p
[2] == rel
;
491 // Do not re-send the same value twice over the wire,
492 // unless more than 2 seconds have elapsed (to maintain the
494 if (!samePg
|| !same(pMeta
[0], meta
)
495 || !same(pName
[0], name
) //
496 || (new Date().getTime() - lastTime
[0] > 2000)) {
504 action
.send(new Object
[] { "UPDATE", min
, max
, rel
,
507 } catch (Exception e
) {
508 getTraceHandler().error(e
);
511 lastTime
[0] = new Date().getTime();
514 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
521 private boolean same(Object obj1
, Object obj2
) {
522 if (obj1
== null || obj2
== null)
523 return obj1
== null && obj2
== null;
525 return obj1
.equals(obj2
);
528 // with 30 seconds timeout
529 private void forcePgDoneSent(Progress pg
) {
530 long start
= new Date().getTime();
532 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
535 } catch (InterruptedException e
) {
536 getTraceHandler().error(e
);
541 private MetaData
removeCover(MetaData meta
) {
542 MetaData light
= null;
544 if (meta
.getCover() == null) {
547 light
= meta
.clone();
548 light
.setCover(null);