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
42 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
44 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
45 * command) with the given LUID, then return the LUID</li>
46 * <li>IMPORT [url]: save the story found at the given URL, then return the
48 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
49 * <li>GET_COVER [luid]: return the cover of the story</li>
50 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
52 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
53 * the given source/author to the cover of the story denoted by luid</li>
54 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
56 * <li>EXIT: stop the server</li>
61 public class RemoteLibraryServer
extends ServerObject
{
62 private final String key
;
65 * Create a new remote server (will not be active until
66 * {@link RemoteLibraryServer#start()} is called).
69 * the key that will restrict access to this server
71 * the port to listen on
74 * in case of I/O error
76 public RemoteLibraryServer(String key
, int port
) throws IOException
{
77 super("Fanfix remote library", port
, false);
80 setTraceHandler(Instance
.getTraceHandler());
84 protected Object
onRequest(ConnectActionServerObject action
,
85 Version clientVersion
, Object data
) throws Exception
{
86 long start
= new Date().getTime();
89 Object
[] args
= new Object
[0];
90 if (data
instanceof Object
[]) {
91 Object
[] dataArray
= (Object
[]) data
;
92 if (dataArray
.length
>= 2) {
93 command
= "" + dataArray
[0];
95 args
= new Object
[dataArray
.length
- 1];
96 for (int i
= 1; i
< dataArray
.length
; i
++) {
97 args
[i
- 1] = dataArray
[i
];
102 String trace
= "[ " + command
+ "] ";
103 for (Object arg
: args
) {
106 getTraceHandler().trace(trace
);
109 String random
= StringUtils
.getMd5Hash(Double
.toString(Math
.random()));
113 answer
+= action
.rec();
114 } catch (NullPointerException e
) {
118 if (answer
.equals(RemoteLibrary
.hashKey(key
, random
))) {
121 getTraceHandler().trace("Key rejected.");
125 Object rep
= doRequest(action
, command
, args
);
127 getTraceHandler().trace(String
.format("[>%s]: %d ms", command
,
128 (new Date().getTime() - start
)));
133 private Object
doRequest(ConnectActionServerObject action
, String command
,
134 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
135 ClassNotFoundException
, IOException
{
136 if ("PING".equals(command
)) {
138 } else if ("GET_METADATA".equals(command
)) {
139 if ("*".equals(args
[0])) {
140 Progress pg
= createPgForwarder(action
);
142 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
144 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
146 if (meta
.getCover() == null) {
149 light
= meta
.clone();
150 light
.setCover(null);
157 return metas
.toArray(new MetaData
[] {});
160 return new MetaData
[] {
161 Instance
.getLibrary().getInfo((String
) args
[0]) };
162 } else if ("GET_STORY".equals(command
)) {
163 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
170 Story story
= Instance
.getLibrary().getStory((String
) args
[0],
172 for (Object obj
: breakStory(story
)) {
176 } else if ("SAVE_STORY".equals(command
)) {
177 List
<Object
> list
= new ArrayList
<Object
>();
180 Object obj
= action
.rec();
181 while (obj
!= null) {
187 Story story
= rebuildStory(list
);
188 Instance
.getLibrary().save(story
, (String
) args
[0], null);
189 return story
.getMeta().getLuid();
190 } else if ("IMPORT".equals(command
)) {
191 Progress pg
= createPgForwarder(action
);
192 Story story
= Instance
.getLibrary().imprt(new URL((String
) args
[0]),
195 return story
.getMeta().getLuid();
196 } else if ("DELETE_STORY".equals(command
)) {
197 Instance
.getLibrary().delete((String
) args
[0]);
198 } else if ("GET_COVER".equals(command
)) {
199 return Instance
.getLibrary().getCover((String
) args
[0]);
200 } else if ("GET_CUSTOM_COVER".equals(command
)) {
201 if ("SOURCE".equals(args
[0])) {
202 return Instance
.getLibrary()
203 .getCustomSourceCover((String
) args
[1]);
204 } else if ("AUTHOR".equals(args
[0])) {
205 return Instance
.getLibrary()
206 .getCustomAuthorCover((String
) args
[1]);
210 } else if ("SET_COVER".equals(command
)) {
211 if ("SOURCE".equals(args
[0])) {
212 Instance
.getLibrary().setSourceCover((String
) args
[1],
214 } else if ("AUTHOR".equals(args
[0])) {
215 Instance
.getLibrary().setAuthorCover((String
) args
[1],
218 } else if ("CHANGE_STA".equals(command
)) {
219 Progress pg
= createPgForwarder(action
);
220 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
221 (String
) args
[2], (String
) args
[3], pg
);
223 } else if ("EXIT".equals(command
)) {
231 protected void onError(Exception e
) {
232 getTraceHandler().error(e
);
236 * Break a story in multiple {@link Object}s for easier serialisation.
239 * the {@link Story} to break
241 * @return the list of {@link Object}s
243 static List
<Object
> breakStory(Story story
) {
244 List
<Object
> list
= new ArrayList
<Object
>();
246 story
= story
.clone();
249 if (story
.getMeta().isImageDocument()) {
250 for (Chapter chap
: story
) {
252 list
.addAll(chap
.getParagraphs());
253 chap
.setParagraphs(new ArrayList
<Paragraph
>());
255 story
.setChapters(new ArrayList
<Chapter
>());
262 * Rebuild a story from a list of broke up {@link Story} parts.
265 * the list of {@link Story} parts
267 * @return the reconstructed {@link Story}
269 static Story
rebuildStory(List
<Object
> list
) {
273 for (Object obj
: list
) {
274 if (obj
instanceof Story
) {
276 } else if (obj
instanceof Chapter
) {
277 chap
= (Chapter
) obj
;
278 story
.getChapters().add(chap
);
279 } else if (obj
instanceof Paragraph
) {
280 chap
.getParagraphs().add((Paragraph
) obj
);
288 * Update the {@link Progress} with the adequate {@link Object} received
289 * from the network via {@link RemoteLibraryServer}.
292 * the {@link Progress} to update
294 * the object received from the network
296 * @return TRUE if it was a progress event, FALSE if not
298 static boolean updateProgress(Progress pg
, Object rep
) {
299 if (rep
instanceof Integer
[]) {
300 Integer
[] a
= (Integer
[]) rep
;
306 if (min
>= 0 && min
<= max
) {
307 pg
.setMinMax(min
, max
);
308 pg
.setProgress(progress
);
319 * Create a {@link Progress} that will forward its progress over the
323 * the {@link ConnectActionServerObject} to use to forward it
325 * @return the {@link Progress}
327 private static Progress
createPgForwarder(
328 final ConnectActionServerObject action
) {
329 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
330 final Progress pg
= new Progress() {
332 public boolean isDone() {
333 return isDoneForwarded
[0];
337 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
338 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
339 pg
.addProgressListener(new ProgressListener() {
341 public void progress(Progress progress
, String name
) {
342 int min
= pg
.getMin();
343 int max
= pg
.getMax();
344 int relativeProgress
= min
+ (int) Math
345 .round(pg
.getRelativeProgress() * (max
- min
));
347 // Do not re-send the same value twice over the wire,
348 // unless more than 2 seconds have elapsed (to maintain the
350 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
351 || (new Date().getTime() - lastTime
[0] > 2000)) {
354 p
[2] = relativeProgress
;
358 new Integer
[] { min
, max
, relativeProgress
});
360 } catch (Exception e
) {
361 Instance
.getTraceHandler().error(e
);
364 lastTime
[0] = new Date().getTime();
367 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
374 // with 30 seconds timeout
375 private static void forcePgDoneSent(Progress pg
) {
376 long start
= new Date().getTime();
378 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
381 } catch (InterruptedException e
) {
382 Instance
.getTraceHandler().error(e
);