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 * the key that will restrict access to this server
76 * the port to listen on
79 * in case of I/O error
81 public RemoteLibraryServer(String key
, int port
) throws IOException
{
82 super("Fanfix remote library", port
, key
);
83 setTraceHandler(Instance
.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
.getConfig().getList(
114 Config
.SERVER_WHITELIST
);
115 if (whitelist
== null) {
116 whitelist
= new ArrayList
<String
>();
119 if (whitelist
.isEmpty()) {
123 rw
= Instance
.getConfig().getBoolean(Config
.SERVER_RW
, rw
);
124 if (!subkey
.isEmpty()) {
125 List
<String
> allowed
= Instance
.getConfig().getList(
126 Config
.SERVER_ALLOWED_SUBKEYS
);
127 if (allowed
.contains(subkey
)) {
128 if ((subkey
+ "|").contains("|rw|")) {
131 if ((subkey
+ "|").contains("|wl|")) {
132 wl
= false; // |wl| = bypass whitelist
137 String mode
= display(wl
, rw
);
139 String trace
= mode
+ "[ " + command
+ "] ";
140 for (Object arg
: args
) {
143 System
.out
.println(trace
);
145 Object rep
= doRequest(action
, command
, args
, rw
, whitelist
);
147 commands
.put(id
, command
);
150 times
.put(id
, (new Date().getTime() - start
));
155 private String
display(boolean whitelist
, boolean rw
) {
168 protected void onRequestDone(long id
, long bytesReceived
, long bytesSent
) {
169 boolean whitelist
= wls
.get(id
);
170 boolean rw
= rws
.get(id
);
174 String rec
= StringUtils
.formatNumber(bytesReceived
) + "b";
175 String sent
= StringUtils
.formatNumber(bytesSent
) + "b";
176 System
.out
.println(String
.format("%s[>%s]: (%s sent, %s rec) in %d ms",
177 display(whitelist
, rw
), commands
.get(id
), sent
, rec
,
184 private Object
doRequest(ConnectActionServerObject action
, String command
,
185 Object
[] args
, boolean rw
, List
<String
> whitelist
)
186 throws NoSuchFieldException
, NoSuchMethodException
,
187 ClassNotFoundException
, IOException
{
188 if ("PING".equals(command
)) {
189 return rw ?
"r/w" : "r/o";
190 } else if ("GET_METADATA".equals(command
)) {
191 if ("*".equals(args
[0])) {
192 Progress pg
= createPgForwarder(action
);
194 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
196 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
198 if (meta
.getCover() == null) {
201 light
= meta
.clone();
202 light
.setCover(null);
209 return metas
.toArray(new MetaData
[] {});
212 return new MetaData
[] { Instance
.getLibrary().getInfo(
214 } else if ("GET_STORY".equals(command
)) {
215 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
222 Story story
= Instance
.getLibrary()
223 .getStory((String
) args
[0], null);
224 for (Object obj
: breakStory(story
)) {
228 } else if ("SAVE_STORY".equals(command
)) {
229 List
<Object
> list
= new ArrayList
<Object
>();
232 Object obj
= action
.rec();
233 while (obj
!= null) {
239 Story story
= rebuildStory(list
);
240 Instance
.getLibrary().save(story
, (String
) args
[0], null);
241 return story
.getMeta().getLuid();
242 } else if ("IMPORT".equals(command
)) {
243 Progress pg
= createPgForwarder(action
);
244 Story story
= Instance
.getLibrary().imprt(
245 new URL((String
) args
[0]), pg
);
247 return story
.getMeta().getLuid();
248 } else if ("DELETE_STORY".equals(command
)) {
249 Instance
.getLibrary().delete((String
) args
[0]);
250 } else if ("GET_COVER".equals(command
)) {
251 return Instance
.getLibrary().getCover((String
) args
[0]);
252 } else if ("GET_CUSTOM_COVER".equals(command
)) {
253 if ("SOURCE".equals(args
[0])) {
254 return Instance
.getLibrary().getCustomSourceCover(
256 } else if ("AUTHOR".equals(args
[0])) {
257 return Instance
.getLibrary().getCustomAuthorCover(
262 } else if ("SET_COVER".equals(command
)) {
263 if ("SOURCE".equals(args
[0])) {
264 Instance
.getLibrary().setSourceCover((String
) args
[1],
266 } else if ("AUTHOR".equals(args
[0])) {
267 Instance
.getLibrary().setAuthorCover((String
) args
[1],
270 } else if ("CHANGE_STA".equals(command
)) {
271 Progress pg
= createPgForwarder(action
);
272 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
273 (String
) args
[2], (String
) args
[3], pg
);
275 } else if ("EXIT".equals(command
)) {
283 protected void onError(Exception e
) {
284 if (e
instanceof SSLException
) {
285 System
.out
.println("[Client connection refused (bad key)]");
287 getTraceHandler().error(e
);
292 * Break a story in multiple {@link Object}s for easier serialisation.
295 * the {@link Story} to break
297 * @return the list of {@link Object}s
299 static List
<Object
> breakStory(Story story
) {
300 List
<Object
> list
= new ArrayList
<Object
>();
302 story
= story
.clone();
305 if (story
.getMeta().isImageDocument()) {
306 for (Chapter chap
: story
) {
308 list
.addAll(chap
.getParagraphs());
309 chap
.setParagraphs(new ArrayList
<Paragraph
>());
311 story
.setChapters(new ArrayList
<Chapter
>());
318 * Rebuild a story from a list of broke up {@link Story} parts.
321 * the list of {@link Story} parts
323 * @return the reconstructed {@link Story}
325 static Story
rebuildStory(List
<Object
> list
) {
329 for (Object obj
: list
) {
330 if (obj
instanceof Story
) {
332 } else if (obj
instanceof Chapter
) {
333 chap
= (Chapter
) obj
;
334 story
.getChapters().add(chap
);
335 } else if (obj
instanceof Paragraph
) {
336 chap
.getParagraphs().add((Paragraph
) obj
);
344 * Update the {@link Progress} with the adequate {@link Object} received
345 * from the network via {@link RemoteLibraryServer}.
348 * the {@link Progress} to update
350 * the object received from the network
352 * @return TRUE if it was a progress event, FALSE if not
354 static boolean updateProgress(Progress pg
, Object rep
) {
355 if (rep
instanceof Integer
[]) {
356 Integer
[] a
= (Integer
[]) rep
;
362 if (min
>= 0 && min
<= max
) {
363 pg
.setMinMax(min
, max
);
364 pg
.setProgress(progress
);
375 * Create a {@link Progress} that will forward its progress over the
379 * the {@link ConnectActionServerObject} to use to forward it
381 * @return the {@link Progress}
383 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
384 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
385 final Progress pg
= new Progress() {
387 public boolean isDone() {
388 return isDoneForwarded
[0];
392 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
393 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
394 pg
.addProgressListener(new ProgressListener() {
396 public void progress(Progress progress
, String name
) {
397 int min
= pg
.getMin();
398 int max
= pg
.getMax();
399 int relativeProgress
= min
400 + (int) Math
.round(pg
.getRelativeProgress()
403 // Do not re-send the same value twice over the wire,
404 // unless more than 2 seconds have elapsed (to maintain the
406 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
407 || (new Date().getTime() - lastTime
[0] > 2000)) {
410 p
[2] = relativeProgress
;
413 action
.send(new Integer
[] { min
, max
, relativeProgress
});
415 } catch (Exception e
) {
416 getTraceHandler().error(e
);
419 lastTime
[0] = new Date().getTime();
422 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
429 // with 30 seconds timeout
430 private void forcePgDoneSent(Progress pg
) {
431 long start
= new Date().getTime();
433 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
436 } catch (InterruptedException e
) {
437 getTraceHandler().error(e
);