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
);
67 setTraceHandler(Instance
.getTraceHandler());
71 protected Object
onRequest(ConnectActionServerObject action
, Object data
)
73 long start
= new Date().getTime();
76 Object
[] args
= new Object
[0];
77 if (data
instanceof Object
[]) {
78 Object
[] dataArray
= (Object
[]) data
;
79 if (dataArray
.length
> 0) {
80 command
= "" + dataArray
[0];
82 args
= new Object
[dataArray
.length
- 1];
83 for (int i
= 1; i
< dataArray
.length
; i
++) {
84 args
[i
- 1] = dataArray
[i
];
89 String trace
= "[ " + command
+ "] ";
90 for (Object arg
: args
) {
93 System
.out
.println(trace
);
95 Object rep
= doRequest(action
, command
, args
);
97 String rec
= StringUtils
.formatNumber(action
.getBytesReceived()) + "b";
98 String sent
= StringUtils
.formatNumber(action
.getBytesSent()) + "b";
99 System
.out
.println(String
.format("[>%s]: (%s sent, %s rec) in %d ms",
100 command
, sent
, rec
, (new Date().getTime() - start
)));
105 private Object
doRequest(ConnectActionServerObject action
, String command
,
106 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
107 ClassNotFoundException
, IOException
{
108 if ("PING".equals(command
)) {
110 } else if ("GET_METADATA".equals(command
)) {
111 if ("*".equals(args
[0])) {
112 Progress pg
= createPgForwarder(action
);
114 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
116 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
118 if (meta
.getCover() == null) {
121 light
= meta
.clone();
122 light
.setCover(null);
129 return metas
.toArray(new MetaData
[] {});
132 return new MetaData
[] { Instance
.getLibrary().getInfo(
134 } else if ("GET_STORY".equals(command
)) {
135 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
142 Story story
= Instance
.getLibrary()
143 .getStory((String
) args
[0], null);
144 for (Object obj
: breakStory(story
)) {
148 } else if ("SAVE_STORY".equals(command
)) {
149 List
<Object
> list
= new ArrayList
<Object
>();
152 Object obj
= action
.rec();
153 while (obj
!= null) {
159 Story story
= rebuildStory(list
);
160 Instance
.getLibrary().save(story
, (String
) args
[0], null);
161 return story
.getMeta().getLuid();
162 } else if ("IMPORT".equals(command
)) {
163 Progress pg
= createPgForwarder(action
);
164 Story story
= Instance
.getLibrary().imprt(
165 new URL((String
) args
[0]), pg
);
167 return story
.getMeta().getLuid();
168 } else if ("DELETE_STORY".equals(command
)) {
169 Instance
.getLibrary().delete((String
) args
[0]);
170 } else if ("GET_COVER".equals(command
)) {
171 return Instance
.getLibrary().getCover((String
) args
[0]);
172 } else if ("GET_CUSTOM_COVER".equals(command
)) {
173 if ("SOURCE".equals(args
[0])) {
174 return Instance
.getLibrary().getCustomSourceCover(
176 } else if ("AUTHOR".equals(args
[0])) {
177 return Instance
.getLibrary().getCustomAuthorCover(
182 } else if ("SET_COVER".equals(command
)) {
183 if ("SOURCE".equals(args
[0])) {
184 Instance
.getLibrary().setSourceCover((String
) args
[1],
186 } else if ("AUTHOR".equals(args
[0])) {
187 Instance
.getLibrary().setAuthorCover((String
) args
[1],
190 } else if ("CHANGE_STA".equals(command
)) {
191 Progress pg
= createPgForwarder(action
);
192 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
193 (String
) args
[2], (String
) args
[3], pg
);
195 } else if ("EXIT".equals(command
)) {
203 protected void onError(Exception e
) {
204 if (e
instanceof SSLException
) {
205 System
.out
.println("[Client connection refused (bad key)]");
207 getTraceHandler().error(e
);
212 * Break a story in multiple {@link Object}s for easier serialisation.
215 * the {@link Story} to break
217 * @return the list of {@link Object}s
219 static List
<Object
> breakStory(Story story
) {
220 List
<Object
> list
= new ArrayList
<Object
>();
222 story
= story
.clone();
225 if (story
.getMeta().isImageDocument()) {
226 for (Chapter chap
: story
) {
228 list
.addAll(chap
.getParagraphs());
229 chap
.setParagraphs(new ArrayList
<Paragraph
>());
231 story
.setChapters(new ArrayList
<Chapter
>());
238 * Rebuild a story from a list of broke up {@link Story} parts.
241 * the list of {@link Story} parts
243 * @return the reconstructed {@link Story}
245 static Story
rebuildStory(List
<Object
> list
) {
249 for (Object obj
: list
) {
250 if (obj
instanceof Story
) {
252 } else if (obj
instanceof Chapter
) {
253 chap
= (Chapter
) obj
;
254 story
.getChapters().add(chap
);
255 } else if (obj
instanceof Paragraph
) {
256 chap
.getParagraphs().add((Paragraph
) obj
);
264 * Update the {@link Progress} with the adequate {@link Object} received
265 * from the network via {@link RemoteLibraryServer}.
268 * the {@link Progress} to update
270 * the object received from the network
272 * @return TRUE if it was a progress event, FALSE if not
274 static boolean updateProgress(Progress pg
, Object rep
) {
275 if (rep
instanceof Integer
[]) {
276 Integer
[] a
= (Integer
[]) rep
;
282 if (min
>= 0 && min
<= max
) {
283 pg
.setMinMax(min
, max
);
284 pg
.setProgress(progress
);
295 * Create a {@link Progress} that will forward its progress over the
299 * the {@link ConnectActionServerObject} to use to forward it
301 * @return the {@link Progress}
303 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
304 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
305 final Progress pg
= new Progress() {
307 public boolean isDone() {
308 return isDoneForwarded
[0];
312 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
313 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
314 pg
.addProgressListener(new ProgressListener() {
316 public void progress(Progress progress
, String name
) {
317 int min
= pg
.getMin();
318 int max
= pg
.getMax();
319 int relativeProgress
= min
320 + (int) Math
.round(pg
.getRelativeProgress()
323 // Do not re-send the same value twice over the wire,
324 // unless more than 2 seconds have elapsed (to maintain the
326 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
327 || (new Date().getTime() - lastTime
[0] > 2000)) {
330 p
[2] = relativeProgress
;
333 action
.send(new Integer
[] { min
, max
, relativeProgress
});
335 } catch (Exception e
) {
336 getTraceHandler().error(e
);
339 lastTime
[0] = new Date().getTime();
342 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
349 // with 30 seconds timeout
350 private void forcePgDoneSent(Progress pg
) {
351 long start
= new Date().getTime();
353 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
356 } catch (InterruptedException e
) {
357 getTraceHandler().error(e
);