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 orders on the given port.
24 * The available commands are given as arrays of objects (first item is the
25 * command, the rest are the arguments).
27 * All commands, including PING, will first return a random value to you that
28 * you must hash with your key and return before processing the rest; if the
29 * value is OK, it will return "true", if not, it will return NULL and stop the
32 * BTW: this system <b>is by no means secure</b>. It is just slightly
33 * obfuscated, and operate on clear text (because Google decided not to support
34 * anonymous SSL exchanges on Android, and the main use case for this server is
37 * <li>PING: will return PONG if the key is accepted</li>
38 * <li>GET_METADATA *: will return the metadata of all the stories in the
39 * library (array)</li> *
40 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
41 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
43 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
44 * command) with the given LUID, then return the LUID</li>
45 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
47 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
48 * <li>GET_COVER [luid]: return the cover of the story</li>
49 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
51 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
52 * the given source/author to the cover of the story denoted by luid</li>
53 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
55 * <li>EXIT: stop the server</li>
60 public class RemoteLibraryServer
extends ServerObject
{
61 private final String key
;
64 * Create a new remote server (will not be active until
65 * {@link RemoteLibraryServer#start()} is called).
68 * the key that will restrict access to this server
70 * the port to listen on
73 * in case of I/O error
75 public RemoteLibraryServer(String key
, int port
) throws IOException
{
76 super("Fanfix remote library", port
, false);
79 setTraceHandler(Instance
.getTraceHandler());
83 protected Object
onRequest(ConnectActionServerObject action
,
84 Version clientVersion
, Object data
) throws Exception
{
85 long start
= new Date().getTime();
88 Object
[] args
= new Object
[0];
89 if (data
instanceof Object
[]) {
90 Object
[] dataArray
= (Object
[]) data
;
91 if (dataArray
.length
>= 2) {
92 command
= "" + dataArray
[0];
94 args
= new Object
[dataArray
.length
- 1];
95 for (int i
= 1; i
< dataArray
.length
; i
++) {
96 args
[i
- 1] = dataArray
[i
];
101 String trace
= "[ " + command
+ "] ";
102 for (Object arg
: args
) {
105 getTraceHandler().trace(trace
);
108 String random
= StringUtils
.getMd5Hash(Double
.toString(Math
.random()));
112 answer
+= action
.rec();
113 } catch (NullPointerException e
) {
117 if (answer
.equals(RemoteLibrary
.hashKey(key
, random
))) {
120 getTraceHandler().trace("Key rejected.");
124 Object rep
= doRequest(action
, command
, args
);
126 String rec
= StringUtils
.formatNumber(action
.getBytesReceived()) + "b";
127 String sent
= StringUtils
.formatNumber(action
.getBytesSent()) + "b";
128 getTraceHandler().trace(
129 String
.format("[>%s]: (%s sent, %s rec) in %d ms", command
,
130 sent
, rec
, (new Date().getTime() - start
)));
135 private Object
doRequest(ConnectActionServerObject action
, String command
,
136 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
137 ClassNotFoundException
, IOException
{
138 if ("PING".equals(command
)) {
140 } else if ("GET_METADATA".equals(command
)) {
141 if ("*".equals(args
[0])) {
142 Progress pg
= createPgForwarder(action
);
144 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
146 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
148 if (meta
.getCover() == null) {
151 light
= meta
.clone();
152 light
.setCover(null);
159 return metas
.toArray(new MetaData
[] {});
162 return new MetaData
[] { Instance
.getLibrary().getInfo(
164 } else if ("GET_STORY".equals(command
)) {
165 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
172 Story story
= Instance
.getLibrary()
173 .getStory((String
) args
[0], null);
174 for (Object obj
: breakStory(story
)) {
178 } else if ("SAVE_STORY".equals(command
)) {
179 List
<Object
> list
= new ArrayList
<Object
>();
182 Object obj
= action
.rec();
183 while (obj
!= null) {
189 Story story
= rebuildStory(list
);
190 Instance
.getLibrary().save(story
, (String
) args
[0], null);
191 return story
.getMeta().getLuid();
192 } else if ("IMPORT".equals(command
)) {
193 Progress pg
= createPgForwarder(action
);
194 Story story
= Instance
.getLibrary().imprt(
195 new URL((String
) args
[0]), pg
);
197 return story
.getMeta().getLuid();
198 } else if ("DELETE_STORY".equals(command
)) {
199 Instance
.getLibrary().delete((String
) args
[0]);
200 } else if ("GET_COVER".equals(command
)) {
201 return Instance
.getLibrary().getCover((String
) args
[0]);
202 } else if ("GET_CUSTOM_COVER".equals(command
)) {
203 if ("SOURCE".equals(args
[0])) {
204 return Instance
.getLibrary().getCustomSourceCover(
206 } else if ("AUTHOR".equals(args
[0])) {
207 return Instance
.getLibrary().getCustomAuthorCover(
212 } else if ("SET_COVER".equals(command
)) {
213 if ("SOURCE".equals(args
[0])) {
214 Instance
.getLibrary().setSourceCover((String
) args
[1],
216 } else if ("AUTHOR".equals(args
[0])) {
217 Instance
.getLibrary().setAuthorCover((String
) args
[1],
220 } else if ("CHANGE_STA".equals(command
)) {
221 Progress pg
= createPgForwarder(action
);
222 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
223 (String
) args
[2], (String
) args
[3], pg
);
225 } else if ("EXIT".equals(command
)) {
233 protected void onError(Exception e
) {
234 getTraceHandler().error(e
);
238 * Break a story in multiple {@link Object}s for easier serialisation.
241 * the {@link Story} to break
243 * @return the list of {@link Object}s
245 static List
<Object
> breakStory(Story story
) {
246 List
<Object
> list
= new ArrayList
<Object
>();
248 story
= story
.clone();
251 if (story
.getMeta().isImageDocument()) {
252 for (Chapter chap
: story
) {
254 list
.addAll(chap
.getParagraphs());
255 chap
.setParagraphs(new ArrayList
<Paragraph
>());
257 story
.setChapters(new ArrayList
<Chapter
>());
264 * Rebuild a story from a list of broke up {@link Story} parts.
267 * the list of {@link Story} parts
269 * @return the reconstructed {@link Story}
271 static Story
rebuildStory(List
<Object
> list
) {
275 for (Object obj
: list
) {
276 if (obj
instanceof Story
) {
278 } else if (obj
instanceof Chapter
) {
279 chap
= (Chapter
) obj
;
280 story
.getChapters().add(chap
);
281 } else if (obj
instanceof Paragraph
) {
282 chap
.getParagraphs().add((Paragraph
) obj
);
290 * Update the {@link Progress} with the adequate {@link Object} received
291 * from the network via {@link RemoteLibraryServer}.
294 * the {@link Progress} to update
296 * the object received from the network
298 * @return TRUE if it was a progress event, FALSE if not
300 static boolean updateProgress(Progress pg
, Object rep
) {
301 if (rep
instanceof Integer
[]) {
302 Integer
[] a
= (Integer
[]) rep
;
308 if (min
>= 0 && min
<= max
) {
309 pg
.setMinMax(min
, max
);
310 pg
.setProgress(progress
);
321 * Create a {@link Progress} that will forward its progress over the
325 * the {@link ConnectActionServerObject} to use to forward it
327 * @return the {@link Progress}
329 private static Progress
createPgForwarder(
330 final ConnectActionServerObject action
) {
331 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
332 final Progress pg
= new Progress() {
334 public boolean isDone() {
335 return isDoneForwarded
[0];
339 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
340 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
341 pg
.addProgressListener(new ProgressListener() {
343 public void progress(Progress progress
, String name
) {
344 int min
= pg
.getMin();
345 int max
= pg
.getMax();
346 int relativeProgress
= min
347 + (int) Math
.round(pg
.getRelativeProgress()
350 // Do not re-send the same value twice over the wire,
351 // unless more than 2 seconds have elapsed (to maintain the
353 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
354 || (new Date().getTime() - lastTime
[0] > 2000)) {
357 p
[2] = relativeProgress
;
360 action
.send(new Integer
[] { min
, max
, relativeProgress
});
362 } catch (Exception e
) {
363 Instance
.getTraceHandler().error(e
);
366 lastTime
[0] = new Date().getTime();
369 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
376 // with 30 seconds timeout
377 private static void forcePgDoneSent(Progress pg
) {
378 long start
= new Date().getTime();
380 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
383 } catch (InterruptedException e
) {
384 Instance
.getTraceHandler().error(e
);