1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.IOException
;
5 import java
.util
.ArrayList
;
9 import javax
.net
.ssl
.SSLException
;
11 import be
.nikiroo
.fanfix
.Instance
;
12 import be
.nikiroo
.fanfix
.data
.Chapter
;
13 import be
.nikiroo
.fanfix
.data
.MetaData
;
14 import be
.nikiroo
.fanfix
.data
.Paragraph
;
15 import be
.nikiroo
.fanfix
.data
.Story
;
16 import be
.nikiroo
.utils
.Progress
;
17 import be
.nikiroo
.utils
.Progress
.ProgressListener
;
18 import be
.nikiroo
.utils
.StringUtils
;
19 import be
.nikiroo
.utils
.serial
.server
.ConnectActionServerObject
;
20 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
23 * Create a new remote server that will listen for orders on the given port.
25 * The available commands are given as arrays of objects (first item is the
26 * command, the rest are the arguments).
29 * <li>PING: will return PONG if the key is accepted</li>
30 * <li>GET_METADATA *: will return the metadata of all the stories in the
31 * library (array)</li> *
32 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
33 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
35 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
36 * command) with the given LUID, then return the LUID</li>
37 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
39 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
40 * <li>GET_COVER [luid]: return the cover of the story</li>
41 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
43 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
44 * the given source/author to the cover of the story denoted by luid</li>
45 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
47 * <li>EXIT: stop the server</li>
52 public class RemoteLibraryServer
extends ServerObject
{
54 * Create a new remote server (will not be active until
55 * {@link RemoteLibraryServer#start()} is called).
58 * the key that will restrict access to this server
60 * the port to listen on
63 * in case of I/O error
65 public RemoteLibraryServer(String key
, int port
) throws IOException
{
66 super("Fanfix remote library", port
, key
);
68 setTraceHandler(Instance
.getTraceHandler());
72 protected Object
onRequest(ConnectActionServerObject action
, Object data
)
74 long start
= new Date().getTime();
77 Object
[] args
= new Object
[0];
78 if (data
instanceof Object
[]) {
79 Object
[] dataArray
= (Object
[]) data
;
80 if (dataArray
.length
> 0) {
81 command
= "" + dataArray
[0];
83 args
= new Object
[dataArray
.length
- 1];
84 for (int i
= 1; i
< dataArray
.length
; i
++) {
85 args
[i
- 1] = dataArray
[i
];
90 String trace
= "[ " + command
+ "] ";
91 for (Object arg
: args
) {
94 System
.out
.println(trace
);
96 Object rep
= doRequest(action
, command
, args
);
98 String rec
= StringUtils
.formatNumber(action
.getBytesReceived()) + "b";
99 String sent
= StringUtils
.formatNumber(action
.getBytesSent()) + "b";
100 System
.out
.println(String
.format("[>%s]: (%s sent, %s rec) in %d ms",
101 command
, sent
, rec
, (new Date().getTime() - start
)));
106 private Object
doRequest(ConnectActionServerObject action
, String command
,
107 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
108 ClassNotFoundException
, IOException
{
109 if ("PING".equals(command
)) {
111 } else if ("GET_METADATA".equals(command
)) {
112 if ("*".equals(args
[0])) {
113 Progress pg
= createPgForwarder(action
);
115 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
117 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
119 if (meta
.getCover() == null) {
122 light
= meta
.clone();
123 light
.setCover(null);
130 return metas
.toArray(new MetaData
[] {});
133 return new MetaData
[] { Instance
.getLibrary().getInfo(
135 } else if ("GET_STORY".equals(command
)) {
136 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
143 Story story
= Instance
.getLibrary()
144 .getStory((String
) args
[0], null);
145 for (Object obj
: breakStory(story
)) {
149 } else if ("SAVE_STORY".equals(command
)) {
150 List
<Object
> list
= new ArrayList
<Object
>();
153 Object obj
= action
.rec();
154 while (obj
!= null) {
160 Story story
= rebuildStory(list
);
161 Instance
.getLibrary().save(story
, (String
) args
[0], null);
162 return story
.getMeta().getLuid();
163 } else if ("IMPORT".equals(command
)) {
164 Progress pg
= createPgForwarder(action
);
165 Story story
= Instance
.getLibrary().imprt(
166 new URL((String
) args
[0]), pg
);
168 return story
.getMeta().getLuid();
169 } else if ("DELETE_STORY".equals(command
)) {
170 Instance
.getLibrary().delete((String
) args
[0]);
171 } else if ("GET_COVER".equals(command
)) {
172 return Instance
.getLibrary().getCover((String
) args
[0]);
173 } else if ("GET_CUSTOM_COVER".equals(command
)) {
174 if ("SOURCE".equals(args
[0])) {
175 return Instance
.getLibrary().getCustomSourceCover(
177 } else if ("AUTHOR".equals(args
[0])) {
178 return Instance
.getLibrary().getCustomAuthorCover(
183 } else if ("SET_COVER".equals(command
)) {
184 if ("SOURCE".equals(args
[0])) {
185 Instance
.getLibrary().setSourceCover((String
) args
[1],
187 } else if ("AUTHOR".equals(args
[0])) {
188 Instance
.getLibrary().setAuthorCover((String
) args
[1],
191 } else if ("CHANGE_STA".equals(command
)) {
192 Progress pg
= createPgForwarder(action
);
193 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
194 (String
) args
[2], (String
) args
[3], pg
);
196 } else if ("EXIT".equals(command
)) {
204 protected void onError(Exception e
) {
205 if (e
instanceof SSLException
) {
206 System
.out
.println("[Client connection refused (bad key)]");
208 getTraceHandler().error(e
);
213 * Break a story in multiple {@link Object}s for easier serialisation.
216 * the {@link Story} to break
218 * @return the list of {@link Object}s
220 static List
<Object
> breakStory(Story story
) {
221 List
<Object
> list
= new ArrayList
<Object
>();
223 story
= story
.clone();
226 if (story
.getMeta().isImageDocument()) {
227 for (Chapter chap
: story
) {
229 list
.addAll(chap
.getParagraphs());
230 chap
.setParagraphs(new ArrayList
<Paragraph
>());
232 story
.setChapters(new ArrayList
<Chapter
>());
239 * Rebuild a story from a list of broke up {@link Story} parts.
242 * the list of {@link Story} parts
244 * @return the reconstructed {@link Story}
246 static Story
rebuildStory(List
<Object
> list
) {
250 for (Object obj
: list
) {
251 if (obj
instanceof Story
) {
253 } else if (obj
instanceof Chapter
) {
254 chap
= (Chapter
) obj
;
255 story
.getChapters().add(chap
);
256 } else if (obj
instanceof Paragraph
) {
257 chap
.getParagraphs().add((Paragraph
) obj
);
265 * Update the {@link Progress} with the adequate {@link Object} received
266 * from the network via {@link RemoteLibraryServer}.
269 * the {@link Progress} to update
271 * the object received from the network
273 * @return TRUE if it was a progress event, FALSE if not
275 static boolean updateProgress(Progress pg
, Object rep
) {
276 if (rep
instanceof Integer
[]) {
277 Integer
[] a
= (Integer
[]) rep
;
283 if (min
>= 0 && min
<= max
) {
284 pg
.setMinMax(min
, max
);
285 pg
.setProgress(progress
);
296 * Create a {@link Progress} that will forward its progress over the
300 * the {@link ConnectActionServerObject} to use to forward it
302 * @return the {@link Progress}
304 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
305 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
306 final Progress pg
= new Progress() {
308 public boolean isDone() {
309 return isDoneForwarded
[0];
313 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
314 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
315 pg
.addProgressListener(new ProgressListener() {
317 public void progress(Progress progress
, String name
) {
318 int min
= pg
.getMin();
319 int max
= pg
.getMax();
320 int relativeProgress
= min
321 + (int) Math
.round(pg
.getRelativeProgress()
324 // Do not re-send the same value twice over the wire,
325 // unless more than 2 seconds have elapsed (to maintain the
327 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
328 || (new Date().getTime() - lastTime
[0] > 2000)) {
331 p
[2] = relativeProgress
;
334 action
.send(new Integer
[] { min
, max
, relativeProgress
});
336 } catch (Exception e
) {
337 getTraceHandler().error(e
);
340 lastTime
[0] = new Date().getTime();
343 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
350 // with 30 seconds timeout
351 private void forcePgDoneSent(Progress pg
) {
352 long start
= new Date().getTime();
354 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
357 } catch (InterruptedException e
) {
358 getTraceHandler().error(e
);