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
.Version
;
20 import be
.nikiroo
.utils
.serial
.server
.ConnectActionServerObject
;
21 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
24 * Create a new remote server that will listen for orders on the given port.
26 * The available commands are given as arrays of objects (first item is the
27 * command, the rest are the arguments).
30 * <li>PING: will return PONG if the key is accepted</li>
31 * <li>GET_METADATA *: will return the metadata of all the stories in the
32 * library (array)</li> *
33 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
34 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
36 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
37 * command) with the given LUID, then return the LUID</li>
38 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
40 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
41 * <li>GET_COVER [luid]: return the cover of the story</li>
42 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
44 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
45 * the given source/author to the cover of the story denoted by luid</li>
46 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
48 * <li>EXIT: stop the server</li>
53 public class RemoteLibraryServer
extends ServerObject
{
55 * Create a new remote server (will not be active until
56 * {@link RemoteLibraryServer#start()} is called).
59 * the key that will restrict access to this server
61 * the port to listen on
64 * in case of I/O error
66 public RemoteLibraryServer(String key
, int port
) throws IOException
{
67 super("Fanfix remote library", port
, key
);
69 setTraceHandler(Instance
.getTraceHandler());
73 protected Object
onRequest(ConnectActionServerObject action
,
74 Version clientVersion
, Object data
) throws Exception
{
75 long start
= new Date().getTime();
78 Object
[] args
= new Object
[0];
79 if (data
instanceof Object
[]) {
80 Object
[] dataArray
= (Object
[]) data
;
81 if (dataArray
.length
> 0) {
82 command
= "" + dataArray
[0];
84 args
= new Object
[dataArray
.length
- 1];
85 for (int i
= 1; i
< dataArray
.length
; i
++) {
86 args
[i
- 1] = dataArray
[i
];
91 String trace
= "[ " + command
+ "] ";
92 for (Object arg
: args
) {
95 System
.out
.println(trace
);
97 Object rep
= doRequest(action
, command
, args
);
99 String rec
= StringUtils
.formatNumber(action
.getBytesReceived()) + "b";
100 String sent
= StringUtils
.formatNumber(action
.getBytesSent()) + "b";
101 System
.out
.println(String
.format("[>%s]: (%s sent, %s rec) in %d ms",
102 command
, sent
, rec
, (new Date().getTime() - start
)));
107 private Object
doRequest(ConnectActionServerObject action
, String command
,
108 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
109 ClassNotFoundException
, IOException
{
110 if ("PING".equals(command
)) {
112 } else if ("GET_METADATA".equals(command
)) {
113 if ("*".equals(args
[0])) {
114 Progress pg
= createPgForwarder(action
);
116 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
118 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
120 if (meta
.getCover() == null) {
123 light
= meta
.clone();
124 light
.setCover(null);
131 return metas
.toArray(new MetaData
[] {});
134 return new MetaData
[] { Instance
.getLibrary().getInfo(
136 } else if ("GET_STORY".equals(command
)) {
137 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
144 Story story
= Instance
.getLibrary()
145 .getStory((String
) args
[0], null);
146 for (Object obj
: breakStory(story
)) {
150 } else if ("SAVE_STORY".equals(command
)) {
151 List
<Object
> list
= new ArrayList
<Object
>();
154 Object obj
= action
.rec();
155 while (obj
!= null) {
161 Story story
= rebuildStory(list
);
162 Instance
.getLibrary().save(story
, (String
) args
[0], null);
163 return story
.getMeta().getLuid();
164 } else if ("IMPORT".equals(command
)) {
165 Progress pg
= createPgForwarder(action
);
166 Story story
= Instance
.getLibrary().imprt(
167 new URL((String
) args
[0]), pg
);
169 return story
.getMeta().getLuid();
170 } else if ("DELETE_STORY".equals(command
)) {
171 Instance
.getLibrary().delete((String
) args
[0]);
172 } else if ("GET_COVER".equals(command
)) {
173 return Instance
.getLibrary().getCover((String
) args
[0]);
174 } else if ("GET_CUSTOM_COVER".equals(command
)) {
175 if ("SOURCE".equals(args
[0])) {
176 return Instance
.getLibrary().getCustomSourceCover(
178 } else if ("AUTHOR".equals(args
[0])) {
179 return Instance
.getLibrary().getCustomAuthorCover(
184 } else if ("SET_COVER".equals(command
)) {
185 if ("SOURCE".equals(args
[0])) {
186 Instance
.getLibrary().setSourceCover((String
) args
[1],
188 } else if ("AUTHOR".equals(args
[0])) {
189 Instance
.getLibrary().setAuthorCover((String
) args
[1],
192 } else if ("CHANGE_STA".equals(command
)) {
193 Progress pg
= createPgForwarder(action
);
194 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
195 (String
) args
[2], (String
) args
[3], pg
);
197 } else if ("EXIT".equals(command
)) {
205 protected void onError(Exception e
) {
206 if (e
instanceof SSLException
) {
207 System
.out
.println("[Client connection refused (bad key)]");
209 getTraceHandler().error(e
);
214 * Break a story in multiple {@link Object}s for easier serialisation.
217 * the {@link Story} to break
219 * @return the list of {@link Object}s
221 static List
<Object
> breakStory(Story story
) {
222 List
<Object
> list
= new ArrayList
<Object
>();
224 story
= story
.clone();
227 if (story
.getMeta().isImageDocument()) {
228 for (Chapter chap
: story
) {
230 list
.addAll(chap
.getParagraphs());
231 chap
.setParagraphs(new ArrayList
<Paragraph
>());
233 story
.setChapters(new ArrayList
<Chapter
>());
240 * Rebuild a story from a list of broke up {@link Story} parts.
243 * the list of {@link Story} parts
245 * @return the reconstructed {@link Story}
247 static Story
rebuildStory(List
<Object
> list
) {
251 for (Object obj
: list
) {
252 if (obj
instanceof Story
) {
254 } else if (obj
instanceof Chapter
) {
255 chap
= (Chapter
) obj
;
256 story
.getChapters().add(chap
);
257 } else if (obj
instanceof Paragraph
) {
258 chap
.getParagraphs().add((Paragraph
) obj
);
266 * Update the {@link Progress} with the adequate {@link Object} received
267 * from the network via {@link RemoteLibraryServer}.
270 * the {@link Progress} to update
272 * the object received from the network
274 * @return TRUE if it was a progress event, FALSE if not
276 static boolean updateProgress(Progress pg
, Object rep
) {
277 if (rep
instanceof Integer
[]) {
278 Integer
[] a
= (Integer
[]) rep
;
284 if (min
>= 0 && min
<= max
) {
285 pg
.setMinMax(min
, max
);
286 pg
.setProgress(progress
);
297 * Create a {@link Progress} that will forward its progress over the
301 * the {@link ConnectActionServerObject} to use to forward it
303 * @return the {@link Progress}
305 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
306 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
307 final Progress pg
= new Progress() {
309 public boolean isDone() {
310 return isDoneForwarded
[0];
314 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
315 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
316 pg
.addProgressListener(new ProgressListener() {
318 public void progress(Progress progress
, String name
) {
319 int min
= pg
.getMin();
320 int max
= pg
.getMax();
321 int relativeProgress
= min
322 + (int) Math
.round(pg
.getRelativeProgress()
325 // Do not re-send the same value twice over the wire,
326 // unless more than 2 seconds have elapsed (to maintain the
328 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
329 || (new Date().getTime() - lastTime
[0] > 2000)) {
332 p
[2] = relativeProgress
;
335 action
.send(new Integer
[] { min
, max
, relativeProgress
});
337 } catch (Exception e
) {
338 getTraceHandler().error(e
);
341 lastTime
[0] = new Date().getTime();
344 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
351 // with 30 seconds timeout
352 private void forcePgDoneSent(Progress pg
) {
353 long start
= new Date().getTime();
355 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
358 } catch (InterruptedException e
) {
359 getTraceHandler().error(e
);