1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.IOException
;
5 import java
.util
.ArrayList
;
9 import be
.nikiroo
.fanfix
.Instance
;
10 import be
.nikiroo
.fanfix
.data
.Chapter
;
11 import be
.nikiroo
.fanfix
.data
.MetaData
;
12 import be
.nikiroo
.fanfix
.data
.Paragraph
;
13 import be
.nikiroo
.fanfix
.data
.Story
;
14 import be
.nikiroo
.utils
.Progress
;
15 import be
.nikiroo
.utils
.Progress
.ProgressListener
;
16 import be
.nikiroo
.utils
.StringUtils
;
17 import be
.nikiroo
.utils
.Version
;
18 import be
.nikiroo
.utils
.serial
.server
.ConnectActionServerObject
;
19 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
22 * Create a new remote server that will listen for order on the given port.
24 * The available commands are given as arrays of objects (first item is the key,
25 * second is the command, the rest are the arguments).
27 * The md5 is always a String (the MD5 hash of the access key), the commands are
28 * also Strings; the parameters vary depending upon the command.
30 * <li>[md5] PING: will return PONG if the key is accepted</li>
31 * <li>[md5] GET_METADATA *: will return the metadata of all the stories in the
32 * library (array)</li>
34 * <li>[md5] GET_METADATA [luid]: will return the metadata of the story of LUID
36 * <li>[md5] GET_STORY [luid]: will return the given story if it exists (or NULL
38 * <li>[md5] SAVE_STORY [luid]: save the story (that must be sent just after the
39 * command) with the given LUID, then return the LUID</li>
40 * <li>[md5] IMPORT [url]: save the story found at the given URL, then return
42 * <li>[md5] DELETE_STORY [luid]: delete the story of LUID luid</li>
43 * <li>[md5] GET_COVER [luid]: return the cover of the story</li>
44 * <li>[md5] GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for
45 * this source/author</li>
46 * <li>[md5] SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover
47 * for the given source/author to the cover of the story denoted by luid</li>
48 * <li>[md5] CHANGE_SOURCE [luid] [new source]: change the source of the story
50 * <li>[md5] EXIT: stop the server</li>
55 public class RemoteLibraryServer
extends ServerObject
{
56 private final String md5
;
59 * Create a new remote server (will not be active until
60 * {@link RemoteLibraryServer#start()} is called).
63 * the key that will restrict access to this server
65 * the port to listen on
68 * in case of I/O error
70 public RemoteLibraryServer(String key
, int port
) throws IOException
{
71 super("Fanfix remote library", port
, true);
72 this.md5
= StringUtils
.getMd5Hash(key
);
74 setTraceHandler(Instance
.getTraceHandler());
78 protected Object
onRequest(ConnectActionServerObject action
,
79 Version clientVersion
, Object data
) throws Exception
{
82 Object
[] args
= new Object
[0];
83 if (data
instanceof Object
[]) {
84 Object
[] dataArray
= (Object
[]) data
;
85 if (dataArray
.length
>= 2) {
86 md5
= "" + dataArray
[0];
87 command
= "" + dataArray
[1];
89 args
= new Object
[dataArray
.length
- 2];
90 for (int i
= 2; i
< dataArray
.length
; i
++) {
91 args
[i
- 2] = dataArray
[i
];
96 String trace
= "[ " + command
+ "] ";
97 for (Object arg
: args
) {
100 getTraceHandler().trace(trace
);
102 if (!md5
.equals(this.md5
)) {
103 getTraceHandler().trace("Key rejected.");
107 long start
= new Date().getTime();
108 Object rep
= doRequest(action
, command
, args
);
110 getTraceHandler().trace(
111 String
.format("[>%s]: %d ms", command
,
112 (new Date().getTime() - start
)));
117 private Object
doRequest(ConnectActionServerObject action
, String command
,
118 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
119 ClassNotFoundException
, IOException
{
120 if ("PING".equals(command
)) {
122 } else if ("GET_METADATA".equals(command
)) {
123 if ("*".equals(args
[0])) {
124 Progress pg
= createPgForwarder(action
);
126 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
128 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
130 if (meta
.getCover() == null) {
133 light
= meta
.clone();
134 light
.setCover(null);
141 return metas
.toArray(new MetaData
[] {});
144 return new MetaData
[] { Instance
.getLibrary().getInfo(
146 } else if ("GET_STORY".equals(command
)) {
147 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
154 Story story
= Instance
.getLibrary()
155 .getStory((String
) args
[0], null);
156 for (Object obj
: breakStory(story
)) {
160 } else if ("SAVE_STORY".equals(command
)) {
161 List
<Object
> list
= new ArrayList
<Object
>();
164 Object obj
= action
.rec();
165 while (obj
!= null) {
171 Story story
= rebuildStory(list
);
172 Instance
.getLibrary().save(story
, (String
) args
[0], null);
173 return story
.getMeta().getLuid();
174 } else if ("IMPORT".equals(command
)) {
175 Progress pg
= createPgForwarder(action
);
176 Story story
= Instance
.getLibrary().imprt(
177 new URL((String
) args
[0]), pg
);
179 return story
.getMeta().getLuid();
180 } else if ("DELETE_STORY".equals(command
)) {
181 Instance
.getLibrary().delete((String
) args
[0]);
182 } else if ("GET_COVER".equals(command
)) {
183 return Instance
.getLibrary().getCover((String
) args
[0]);
184 } else if ("GET_CUSTOM_COVER".equals(command
)) {
185 if ("SOURCE".equals(args
[0])) {
186 return Instance
.getLibrary().getCustomSourceCover(
188 } else if ("AUTHOR".equals(args
[0])) {
189 return Instance
.getLibrary().getCustomAuthorCover(
194 } else if ("SET_COVER".equals(command
)) {
195 if ("SOURCE".equals(args
[0])) {
196 Instance
.getLibrary().setSourceCover((String
) args
[1],
198 } else if ("AUTHOR".equals(args
[0])) {
199 Instance
.getLibrary().setAuthorCover((String
) args
[1],
202 } else if ("CHANGE_STA".equals(command
)) {
203 Progress pg
= createPgForwarder(action
);
204 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
205 (String
) args
[2], (String
) args
[3], pg
);
207 } else if ("EXIT".equals(command
)) {
215 protected void onError(Exception e
) {
216 getTraceHandler().error(e
);
220 * Break a story in multiple {@link Object}s for easier serialisation.
223 * the {@link Story} to break
225 * @return the list of {@link Object}s
227 static List
<Object
> breakStory(Story story
) {
228 List
<Object
> list
= new ArrayList
<Object
>();
230 story
= story
.clone();
233 if (story
.getMeta().isImageDocument()) {
234 for (Chapter chap
: story
) {
236 list
.addAll(chap
.getParagraphs());
237 chap
.setParagraphs(new ArrayList
<Paragraph
>());
239 story
.setChapters(new ArrayList
<Chapter
>());
246 * Rebuild a story from a list of broke up {@link Story} parts.
249 * the list of {@link Story} parts
251 * @return the reconstructed {@link Story}
253 static Story
rebuildStory(List
<Object
> list
) {
257 for (Object obj
: list
) {
258 if (obj
instanceof Story
) {
260 } else if (obj
instanceof Chapter
) {
261 chap
= (Chapter
) obj
;
262 story
.getChapters().add(chap
);
263 } else if (obj
instanceof Paragraph
) {
264 chap
.getParagraphs().add((Paragraph
) obj
);
272 * Update the {@link Progress} with the adequate {@link Object} received
273 * from the network via {@link RemoteLibraryServer}.
276 * the {@link Progress} to update
278 * the object received from the network
280 * @return TRUE if it was a progress event, FALSE if not
282 static boolean updateProgress(Progress pg
, Object rep
) {
283 if (rep
instanceof Integer
[]) {
284 Integer
[] a
= (Integer
[]) rep
;
290 if (min
>= 0 && min
<= max
) {
291 pg
.setMinMax(min
, max
);
292 pg
.setProgress(progress
);
303 * Create a {@link Progress} that will forward its progress over the
307 * the {@link ConnectActionServerObject} to use to forward it
309 * @return the {@link Progress}
311 private static Progress
createPgForwarder(
312 final ConnectActionServerObject action
) {
313 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
314 final Progress pg
= new Progress() {
316 public boolean isDone() {
317 return isDoneForwarded
[0];
321 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
322 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
323 pg
.addProgressListener(new ProgressListener() {
325 public void progress(Progress progress
, String name
) {
326 int min
= pg
.getMin();
327 int max
= pg
.getMax();
328 int relativeProgress
= min
329 + (int) Math
.round(pg
.getRelativeProgress()
332 // Do not re-send the same value twice over the wire,
333 // unless more than 2 seconds have elapsed (to maintain the
335 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
336 || (new Date().getTime() - lastTime
[0] > 2000)) {
339 p
[2] = relativeProgress
;
342 action
.send(new Integer
[] { min
, max
, relativeProgress
});
344 } catch (Exception e
) {
345 Instance
.getTraceHandler().error(e
);
348 lastTime
[0] = new Date().getTime();
351 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
358 // with 30 seconds timeout
359 private static void forcePgDoneSent(Progress pg
) {
360 long start
= new Date().getTime();
362 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
365 } catch (InterruptedException e
) {
366 Instance
.getTraceHandler().error(e
);