1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.IOException
;
5 import java
.util
.ArrayList
;
7 import java
.util
.HashMap
;
11 import javax
.net
.ssl
.SSLException
;
13 import be
.nikiroo
.fanfix
.Instance
;
14 import be
.nikiroo
.fanfix
.data
.Chapter
;
15 import be
.nikiroo
.fanfix
.data
.MetaData
;
16 import be
.nikiroo
.fanfix
.data
.Paragraph
;
17 import be
.nikiroo
.fanfix
.data
.Story
;
18 import be
.nikiroo
.utils
.Progress
;
19 import be
.nikiroo
.utils
.Progress
.ProgressListener
;
20 import be
.nikiroo
.utils
.StringUtils
;
21 import be
.nikiroo
.utils
.serial
.server
.ConnectActionServerObject
;
22 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
25 * Create a new remote server that will listen for orders on the given port.
27 * The available commands are given as arrays of objects (first item is the
28 * command, the rest are the arguments).
31 * <li>PING: will return PONG if the key is accepted</li>
32 * <li>GET_METADATA *: will return the metadata of all the stories in the
33 * library (array)</li> *
34 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
35 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
37 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
38 * command) with the given LUID, then return the LUID</li>
39 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
41 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
42 * <li>GET_COVER [luid]: return the cover of the story</li>
43 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
45 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
46 * the given source/author to the cover of the story denoted by luid</li>
47 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
49 * <li>EXIT: stop the server</li>
54 public class RemoteLibraryServer
extends ServerObject
{
55 private Map
<Long
, String
> commands
= new HashMap
<Long
, String
>();
56 private Map
<Long
, Long
> times
= new HashMap
<Long
, Long
>();
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
, key
);
72 setTraceHandler(Instance
.getTraceHandler());
76 protected Object
onRequest(ConnectActionServerObject action
, Object data
,
77 long id
) throws Exception
{
78 long start
= new Date().getTime();
81 Object
[] args
= new Object
[0];
82 if (data
instanceof Object
[]) {
83 Object
[] dataArray
= (Object
[]) data
;
84 if (dataArray
.length
> 0) {
85 command
= "" + dataArray
[0];
87 args
= new Object
[dataArray
.length
- 1];
88 for (int i
= 1; i
< dataArray
.length
; i
++) {
89 args
[i
- 1] = dataArray
[i
];
94 String trace
= "[ " + command
+ "] ";
95 for (Object arg
: args
) {
98 System
.out
.println(trace
);
100 Object rep
= doRequest(action
, command
, args
);
102 commands
.put(id
, command
);
103 times
.put(id
, (new Date().getTime() - start
));
109 protected void onRequestDone(long id
, long bytesReceived
, long bytesSent
) {
110 String rec
= StringUtils
.formatNumber(bytesReceived
) + "b";
111 String sent
= StringUtils
.formatNumber(bytesSent
) + "b";
112 System
.out
.println(String
.format("[>%s]: (%s sent, %s rec) in %d ms",
113 commands
.get(id
), sent
, rec
, times
.get(id
)));
118 private Object
doRequest(ConnectActionServerObject action
, String command
,
119 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
120 ClassNotFoundException
, IOException
{
121 if ("PING".equals(command
)) {
123 } else if ("GET_METADATA".equals(command
)) {
124 if ("*".equals(args
[0])) {
125 Progress pg
= createPgForwarder(action
);
127 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
129 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
131 if (meta
.getCover() == null) {
134 light
= meta
.clone();
135 light
.setCover(null);
142 return metas
.toArray(new MetaData
[] {});
145 return new MetaData
[] { Instance
.getLibrary().getInfo(
147 } else if ("GET_STORY".equals(command
)) {
148 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
155 Story story
= Instance
.getLibrary()
156 .getStory((String
) args
[0], null);
157 for (Object obj
: breakStory(story
)) {
161 } else if ("SAVE_STORY".equals(command
)) {
162 List
<Object
> list
= new ArrayList
<Object
>();
165 Object obj
= action
.rec();
166 while (obj
!= null) {
172 Story story
= rebuildStory(list
);
173 Instance
.getLibrary().save(story
, (String
) args
[0], null);
174 return story
.getMeta().getLuid();
175 } else if ("IMPORT".equals(command
)) {
176 Progress pg
= createPgForwarder(action
);
177 Story story
= Instance
.getLibrary().imprt(
178 new URL((String
) args
[0]), pg
);
180 return story
.getMeta().getLuid();
181 } else if ("DELETE_STORY".equals(command
)) {
182 Instance
.getLibrary().delete((String
) args
[0]);
183 } else if ("GET_COVER".equals(command
)) {
184 return Instance
.getLibrary().getCover((String
) args
[0]);
185 } else if ("GET_CUSTOM_COVER".equals(command
)) {
186 if ("SOURCE".equals(args
[0])) {
187 return Instance
.getLibrary().getCustomSourceCover(
189 } else if ("AUTHOR".equals(args
[0])) {
190 return Instance
.getLibrary().getCustomAuthorCover(
195 } else if ("SET_COVER".equals(command
)) {
196 if ("SOURCE".equals(args
[0])) {
197 Instance
.getLibrary().setSourceCover((String
) args
[1],
199 } else if ("AUTHOR".equals(args
[0])) {
200 Instance
.getLibrary().setAuthorCover((String
) args
[1],
203 } else if ("CHANGE_STA".equals(command
)) {
204 Progress pg
= createPgForwarder(action
);
205 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
206 (String
) args
[2], (String
) args
[3], pg
);
208 } else if ("EXIT".equals(command
)) {
216 protected void onError(Exception e
) {
217 if (e
instanceof SSLException
) {
218 System
.out
.println("[Client connection refused (bad key)]");
220 getTraceHandler().error(e
);
225 * Break a story in multiple {@link Object}s for easier serialisation.
228 * the {@link Story} to break
230 * @return the list of {@link Object}s
232 static List
<Object
> breakStory(Story story
) {
233 List
<Object
> list
= new ArrayList
<Object
>();
235 story
= story
.clone();
238 if (story
.getMeta().isImageDocument()) {
239 for (Chapter chap
: story
) {
241 list
.addAll(chap
.getParagraphs());
242 chap
.setParagraphs(new ArrayList
<Paragraph
>());
244 story
.setChapters(new ArrayList
<Chapter
>());
251 * Rebuild a story from a list of broke up {@link Story} parts.
254 * the list of {@link Story} parts
256 * @return the reconstructed {@link Story}
258 static Story
rebuildStory(List
<Object
> list
) {
262 for (Object obj
: list
) {
263 if (obj
instanceof Story
) {
265 } else if (obj
instanceof Chapter
) {
266 chap
= (Chapter
) obj
;
267 story
.getChapters().add(chap
);
268 } else if (obj
instanceof Paragraph
) {
269 chap
.getParagraphs().add((Paragraph
) obj
);
277 * Update the {@link Progress} with the adequate {@link Object} received
278 * from the network via {@link RemoteLibraryServer}.
281 * the {@link Progress} to update
283 * the object received from the network
285 * @return TRUE if it was a progress event, FALSE if not
287 static boolean updateProgress(Progress pg
, Object rep
) {
288 if (rep
instanceof Integer
[]) {
289 Integer
[] a
= (Integer
[]) rep
;
295 if (min
>= 0 && min
<= max
) {
296 pg
.setMinMax(min
, max
);
297 pg
.setProgress(progress
);
308 * Create a {@link Progress} that will forward its progress over the
312 * the {@link ConnectActionServerObject} to use to forward it
314 * @return the {@link Progress}
316 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
317 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
318 final Progress pg
= new Progress() {
320 public boolean isDone() {
321 return isDoneForwarded
[0];
325 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
326 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
327 pg
.addProgressListener(new ProgressListener() {
329 public void progress(Progress progress
, String name
) {
330 int min
= pg
.getMin();
331 int max
= pg
.getMax();
332 int relativeProgress
= min
333 + (int) Math
.round(pg
.getRelativeProgress()
336 // Do not re-send the same value twice over the wire,
337 // unless more than 2 seconds have elapsed (to maintain the
339 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
340 || (new Date().getTime() - lastTime
[0] > 2000)) {
343 p
[2] = relativeProgress
;
346 action
.send(new Integer
[] { min
, max
, relativeProgress
});
348 } catch (Exception e
) {
349 getTraceHandler().error(e
);
352 lastTime
[0] = new Date().getTime();
355 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
362 // with 30 seconds timeout
363 private void forcePgDoneSent(Progress pg
) {
364 long start
= new Date().getTime();
366 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
369 } catch (InterruptedException e
) {
370 getTraceHandler().error(e
);