1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.IOException
;
5 import java
.nio
.file
.AccessDeniedException
;
6 import java
.util
.ArrayList
;
8 import java
.util
.HashMap
;
12 import javax
.net
.ssl
.SSLException
;
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
;
28 * Create a new remote server that will listen for orders on the given port.
30 * The available commands are given as arrays of objects (first item is the
31 * command, the rest are the arguments).
33 * All the commands are always prefixed by the subkey (which can be EMPTY if
37 * <li>PING: will return the mode if the key is accepted (mode can be: "r/o" or
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
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
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
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
56 * <li>EXIT: stop the server</li>
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
>();
68 * Create a new remote server (will not be active until
69 * {@link RemoteLibraryServer#start()} is called).
71 * Note: the key we use here is the encryption key (it must not contain a
75 * the key that will restrict access to this server
77 * the port to listen on
80 * in case of I/O error
82 public RemoteLibraryServer(String key
, int port
) throws IOException
{
83 super("Fanfix remote library", port
, key
);
84 setTraceHandler(Instance
.getTraceHandler());
88 protected Object
onRequest(ConnectActionServerObject action
,
89 Version clientVersion
, Object data
, long id
) throws Exception
{
90 long start
= new Date().getTime();
92 // defaults are positive (as previous versions without the feature)
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];
104 if (dataArray
.length
> 1) {
105 command
= "" + dataArray
[1];
107 args
= new Object
[dataArray
.length
- 2];
108 for (int i
= 2; i
< dataArray
.length
; i
++) {
109 args
[i
- 2] = dataArray
[i
];
114 List
<String
> whitelist
= Instance
.getConfig().getList(
115 Config
.SERVER_WHITELIST
);
116 if (whitelist
== null) {
117 whitelist
= new ArrayList
<String
>();
120 if (whitelist
.isEmpty()) {
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|")) {
132 if ((subkey
+ "|").contains("|wl|")) {
133 wl
= false; // |wl| = bypass whitelist
134 whitelist
= new ArrayList
<String
>();
139 String mode
= display(wl
, rw
);
141 String trace
= mode
+ "[ " + command
+ "] ";
142 for (Object arg
: args
) {
145 long now
= System
.currentTimeMillis();
146 System
.out
.println(StringUtils
.fromTime(now
) + ": " + trace
);
150 rep
= doRequest(action
, command
, args
, rw
, whitelist
);
151 } catch (IOException e
) {
152 rep
= new RemoteLibraryException(e
);
155 commands
.put(id
, command
);
158 times
.put(id
, (new Date().getTime() - start
));
163 private String
display(boolean whitelist
, boolean rw
) {
176 protected void onRequestDone(long id
, long bytesReceived
, long bytesSent
) {
177 boolean whitelist
= wls
.get(id
);
178 boolean rw
= rws
.get(id
);
182 String rec
= StringUtils
.formatNumber(bytesReceived
) + "b";
183 String sent
= StringUtils
.formatNumber(bytesSent
) + "b";
184 long now
= System
.currentTimeMillis();
185 System
.out
.println(StringUtils
.fromTime(now
)
187 + String
.format("%s[>%s]: (%s sent, %s rec) in %d ms",
188 display(whitelist
, rw
), commands
.get(id
), sent
, rec
,
195 private Object
doRequest(ConnectActionServerObject action
, String command
,
196 Object
[] args
, boolean rw
, List
<String
> whitelist
)
197 throws NoSuchFieldException
, NoSuchMethodException
,
198 ClassNotFoundException
, IOException
{
199 if ("PING".equals(command
)) {
200 return rw ?
"r/w" : "r/o";
201 } else if ("GET_METADATA".equals(command
)) {
202 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
204 if ("*".equals(args
[0])) {
205 Progress pg
= createPgForwarder(action
);
207 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
209 if (meta
.getCover() == null) {
212 light
= meta
.clone();
213 light
.setCover(null);
221 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
223 if (meta
.getCover() == null) {
226 light
= meta
.clone();
227 light
.setCover(null);
233 if (!whitelist
.isEmpty()) {
234 for (int i
= 0; i
< metas
.size(); i
++) {
235 if (!whitelist
.contains(metas
.get(i
).getSource())) {
242 return metas
.toArray(new MetaData
[0]);
243 } else if ("GET_STORY".equals(command
)) {
244 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
249 if (!whitelist
.isEmpty()) {
250 if (!whitelist
.contains(meta
.getSource())) {
261 Story story
= Instance
.getLibrary()
262 .getStory((String
) args
[0], null);
263 for (Object obj
: breakStory(story
)) {
267 } else if ("SAVE_STORY".equals(command
)) {
269 throw new AccessDeniedException("" + args
[0], null,
270 "Read-Only remote library");
273 List
<Object
> list
= new ArrayList
<Object
>();
276 Object obj
= action
.rec();
277 while (obj
!= null) {
283 Story story
= rebuildStory(list
);
284 Instance
.getLibrary().save(story
, (String
) args
[0], null);
285 return story
.getMeta().getLuid();
286 } else if ("IMPORT".equals(command
)) {
288 throw new AccessDeniedException("" + args
[0], null,
289 "Read-Only remote library");
292 Progress pg
= createPgForwarder(action
);
293 Story story
= Instance
.getLibrary().imprt(
294 new URL((String
) args
[0]), pg
);
296 return story
.getMeta().getLuid();
297 } else if ("DELETE_STORY".equals(command
)) {
299 throw new AccessDeniedException("" + args
[0], null,
300 "Read-Only remote library");
303 Instance
.getLibrary().delete((String
) args
[0]);
304 } else if ("GET_COVER".equals(command
)) {
305 return Instance
.getLibrary().getCover((String
) args
[0]);
306 } else if ("GET_CUSTOM_COVER".equals(command
)) {
307 if ("SOURCE".equals(args
[0])) {
308 return Instance
.getLibrary().getCustomSourceCover(
310 } else if ("AUTHOR".equals(args
[0])) {
311 return Instance
.getLibrary().getCustomAuthorCover(
316 } else if ("SET_COVER".equals(command
)) {
318 throw new AccessDeniedException("" + args
[0], "" + args
[1],
319 "Read-Only remote library");
322 if ("SOURCE".equals(args
[0])) {
323 Instance
.getLibrary().setSourceCover((String
) args
[1],
325 } else if ("AUTHOR".equals(args
[0])) {
326 Instance
.getLibrary().setAuthorCover((String
) args
[1],
329 } else if ("CHANGE_STA".equals(command
)) {
331 throw new AccessDeniedException("" + args
[0], "" + args
[1],
332 "Read-Only remote library");
335 Progress pg
= createPgForwarder(action
);
336 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
337 (String
) args
[2], (String
) args
[3], pg
);
339 } else if ("EXIT".equals(command
)) {
341 throw new AccessDeniedException("EXIT", "",
342 "Read-Only remote library, cannot close it");
352 protected void onError(Exception e
) {
353 if (e
instanceof SSLException
) {
354 long now
= System
.currentTimeMillis();
355 System
.out
.println(StringUtils
.fromTime(now
) + ": "
356 + "[Client connection refused (bad key)]");
358 getTraceHandler().error(e
);
363 * Break a story in multiple {@link Object}s for easier serialisation.
366 * the {@link Story} to break
368 * @return the list of {@link Object}s
370 static List
<Object
> breakStory(Story story
) {
371 List
<Object
> list
= new ArrayList
<Object
>();
373 story
= story
.clone();
376 if (story
.getMeta().isImageDocument()) {
377 for (Chapter chap
: story
) {
379 list
.addAll(chap
.getParagraphs());
380 chap
.setParagraphs(new ArrayList
<Paragraph
>());
382 story
.setChapters(new ArrayList
<Chapter
>());
389 * Rebuild a story from a list of broke up {@link Story} parts.
392 * the list of {@link Story} parts
394 * @return the reconstructed {@link Story}
396 static Story
rebuildStory(List
<Object
> list
) {
400 for (Object obj
: list
) {
401 if (obj
instanceof Story
) {
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
);
415 * Update the {@link Progress} with the adequate {@link Object} received
416 * from the network via {@link RemoteLibraryServer}.
419 * the {@link Progress} to update
421 * the object received from the network
423 * @return TRUE if it was a progress event, FALSE if not
425 static boolean updateProgress(Progress pg
, Object rep
) {
426 if (rep
instanceof Integer
[]) {
427 Integer
[] a
= (Integer
[]) rep
;
433 if (min
>= 0 && min
<= max
) {
434 pg
.setMinMax(min
, max
);
435 pg
.setProgress(progress
);
446 * Create a {@link Progress} that will forward its progress over the
450 * the {@link ConnectActionServerObject} to use to forward it
452 * @return the {@link Progress}
454 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
455 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
456 final Progress pg
= new Progress() {
458 public boolean isDone() {
459 return isDoneForwarded
[0];
463 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
464 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
465 pg
.addProgressListener(new ProgressListener() {
467 public void progress(Progress progress
, String name
) {
468 int min
= pg
.getMin();
469 int max
= pg
.getMax();
470 int relativeProgress
= min
471 + (int) Math
.round(pg
.getRelativeProgress()
474 // Do not re-send the same value twice over the wire,
475 // unless more than 2 seconds have elapsed (to maintain the
477 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
478 || (new Date().getTime() - lastTime
[0] > 2000)) {
481 p
[2] = relativeProgress
;
484 action
.send(new Integer
[] { min
, max
, relativeProgress
});
486 } catch (Exception e
) {
487 getTraceHandler().error(e
);
490 lastTime
[0] = new Date().getTime();
493 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
500 // with 30 seconds timeout
501 private void forcePgDoneSent(Progress pg
) {
502 long start
= new Date().getTime();
504 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
507 } catch (InterruptedException e
) {
508 getTraceHandler().error(e
);