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 not correct, the connection will be closed.
31 * BTW: this system <b>is by no means secure</b>. It is just slightly
32 * obfuscated, and operate on clear text (because Google decided not to support
33 * anonymous SSL exchanges on Android, and the main use case for this server is
36 * <li>PING: will return PONG if the key is accepted</li>
37 * <li>GET_METADATA *: will return the metadata of all the stories in the
38 * library (array)</li> *
39 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
40 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
42 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
43 * command) with the given LUID, then return the LUID</li>
44 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
46 * <li>DELETE_STORY [luid]: delete the story of LUID luid</li>
47 * <li>GET_COVER [luid]: return the cover of the story</li>
48 * <li>GET_CUSTOM_COVER ["SOURCE"|"AUTHOR"] [source]: return the cover for this
50 * <li>SET_COVER ["SOURCE"|"AUTHOR"] [value] [luid]: set the default cover for
51 * the given source/author to the cover of the story denoted by luid</li>
52 * <li>CHANGE_SOURCE [luid] [new source]: change the source of the story of LUID
54 * <li>EXIT: stop the server</li>
59 public class RemoteLibraryServer
extends ServerObject
{
60 private final String key
;
63 * Create a new remote server (will not be active until
64 * {@link RemoteLibraryServer#start()} is called).
67 * the key that will restrict access to this server
69 * the port to listen on
72 * in case of I/O error
74 public RemoteLibraryServer(String key
, int port
) throws IOException
{
75 super("Fanfix remote library", port
, key
);
78 setTraceHandler(Instance
.getTraceHandler());
82 protected Object
onRequest(ConnectActionServerObject action
,
83 Version clientVersion
, Object data
) throws Exception
{
84 long start
= new Date().getTime();
87 Object
[] args
= new Object
[0];
88 if (data
instanceof Object
[]) {
89 Object
[] dataArray
= (Object
[]) data
;
90 if (dataArray
.length
> 0) {
91 command
= "" + dataArray
[0];
93 args
= new Object
[dataArray
.length
- 1];
94 for (int i
= 1; i
< dataArray
.length
; i
++) {
95 args
[i
- 1] = dataArray
[i
];
100 String trace
= "[ " + command
+ "] ";
101 for (Object arg
: args
) {
104 System
.out
.println(trace
);
107 String random
= StringUtils
.getMd5Hash(Double
.toString(Math
.random()));
109 String answer
= "" + action
.rec();
111 if (!answer
.equals(RemoteLibrary
.hashKey(key
, random
))) {
112 System
.out
.println("Key rejected.");
118 Object rep
= doRequest(action
, command
, args
);
120 String rec
= StringUtils
.formatNumber(action
.getBytesReceived()) + "b";
121 String sent
= StringUtils
.formatNumber(action
.getBytesSent()) + "b";
122 System
.out
.println(String
.format("[>%s]: (%s sent, %s rec) in %d ms",
123 command
, sent
, rec
, (new Date().getTime() - start
)));
128 private Object
doRequest(ConnectActionServerObject action
, String command
,
129 Object
[] args
) throws NoSuchFieldException
, NoSuchMethodException
,
130 ClassNotFoundException
, IOException
{
131 if ("PING".equals(command
)) {
133 } else if ("GET_METADATA".equals(command
)) {
134 if ("*".equals(args
[0])) {
135 Progress pg
= createPgForwarder(action
);
137 List
<MetaData
> metas
= new ArrayList
<MetaData
>();
139 for (MetaData meta
: Instance
.getLibrary().getMetas(pg
)) {
141 if (meta
.getCover() == null) {
144 light
= meta
.clone();
145 light
.setCover(null);
152 return metas
.toArray(new MetaData
[] {});
155 return new MetaData
[] { Instance
.getLibrary().getInfo(
157 } else if ("GET_STORY".equals(command
)) {
158 MetaData meta
= Instance
.getLibrary().getInfo((String
) args
[0]);
165 Story story
= Instance
.getLibrary()
166 .getStory((String
) args
[0], null);
167 for (Object obj
: breakStory(story
)) {
171 } else if ("SAVE_STORY".equals(command
)) {
172 List
<Object
> list
= new ArrayList
<Object
>();
175 Object obj
= action
.rec();
176 while (obj
!= null) {
182 Story story
= rebuildStory(list
);
183 Instance
.getLibrary().save(story
, (String
) args
[0], null);
184 return story
.getMeta().getLuid();
185 } else if ("IMPORT".equals(command
)) {
186 Progress pg
= createPgForwarder(action
);
187 Story story
= Instance
.getLibrary().imprt(
188 new URL((String
) args
[0]), pg
);
190 return story
.getMeta().getLuid();
191 } else if ("DELETE_STORY".equals(command
)) {
192 Instance
.getLibrary().delete((String
) args
[0]);
193 } else if ("GET_COVER".equals(command
)) {
194 return Instance
.getLibrary().getCover((String
) args
[0]);
195 } else if ("GET_CUSTOM_COVER".equals(command
)) {
196 if ("SOURCE".equals(args
[0])) {
197 return Instance
.getLibrary().getCustomSourceCover(
199 } else if ("AUTHOR".equals(args
[0])) {
200 return Instance
.getLibrary().getCustomAuthorCover(
205 } else if ("SET_COVER".equals(command
)) {
206 if ("SOURCE".equals(args
[0])) {
207 Instance
.getLibrary().setSourceCover((String
) args
[1],
209 } else if ("AUTHOR".equals(args
[0])) {
210 Instance
.getLibrary().setAuthorCover((String
) args
[1],
213 } else if ("CHANGE_STA".equals(command
)) {
214 Progress pg
= createPgForwarder(action
);
215 Instance
.getLibrary().changeSTA((String
) args
[0], (String
) args
[1],
216 (String
) args
[2], (String
) args
[3], pg
);
218 } else if ("EXIT".equals(command
)) {
226 protected void onError(Exception e
) {
227 getTraceHandler().error(e
);
231 * Break a story in multiple {@link Object}s for easier serialisation.
234 * the {@link Story} to break
236 * @return the list of {@link Object}s
238 static List
<Object
> breakStory(Story story
) {
239 List
<Object
> list
= new ArrayList
<Object
>();
241 story
= story
.clone();
244 if (story
.getMeta().isImageDocument()) {
245 for (Chapter chap
: story
) {
247 list
.addAll(chap
.getParagraphs());
248 chap
.setParagraphs(new ArrayList
<Paragraph
>());
250 story
.setChapters(new ArrayList
<Chapter
>());
257 * Rebuild a story from a list of broke up {@link Story} parts.
260 * the list of {@link Story} parts
262 * @return the reconstructed {@link Story}
264 static Story
rebuildStory(List
<Object
> list
) {
268 for (Object obj
: list
) {
269 if (obj
instanceof Story
) {
271 } else if (obj
instanceof Chapter
) {
272 chap
= (Chapter
) obj
;
273 story
.getChapters().add(chap
);
274 } else if (obj
instanceof Paragraph
) {
275 chap
.getParagraphs().add((Paragraph
) obj
);
283 * Update the {@link Progress} with the adequate {@link Object} received
284 * from the network via {@link RemoteLibraryServer}.
287 * the {@link Progress} to update
289 * the object received from the network
291 * @return TRUE if it was a progress event, FALSE if not
293 static boolean updateProgress(Progress pg
, Object rep
) {
294 if (rep
instanceof Integer
[]) {
295 Integer
[] a
= (Integer
[]) rep
;
301 if (min
>= 0 && min
<= max
) {
302 pg
.setMinMax(min
, max
);
303 pg
.setProgress(progress
);
314 * Create a {@link Progress} that will forward its progress over the
318 * the {@link ConnectActionServerObject} to use to forward it
320 * @return the {@link Progress}
322 private Progress
createPgForwarder(final ConnectActionServerObject action
) {
323 final Boolean
[] isDoneForwarded
= new Boolean
[] { false };
324 final Progress pg
= new Progress() {
326 public boolean isDone() {
327 return isDoneForwarded
[0];
331 final Integer
[] p
= new Integer
[] { -1, -1, -1 };
332 final Long
[] lastTime
= new Long
[] { new Date().getTime() };
333 pg
.addProgressListener(new ProgressListener() {
335 public void progress(Progress progress
, String name
) {
336 int min
= pg
.getMin();
337 int max
= pg
.getMax();
338 int relativeProgress
= min
339 + (int) Math
.round(pg
.getRelativeProgress()
342 // Do not re-send the same value twice over the wire,
343 // unless more than 2 seconds have elapsed (to maintain the
345 if ((p
[0] != min
|| p
[1] != max
|| p
[2] != relativeProgress
)
346 || (new Date().getTime() - lastTime
[0] > 2000)) {
349 p
[2] = relativeProgress
;
352 action
.send(new Integer
[] { min
, max
, relativeProgress
});
354 } catch (Exception e
) {
355 getTraceHandler().error(e
);
358 lastTime
[0] = new Date().getTime();
361 isDoneForwarded
[0] = (pg
.getProgress() >= pg
.getMax());
368 // with 30 seconds timeout
369 private void forcePgDoneSent(Progress pg
) {
370 long start
= new Date().getTime();
372 while (!pg
.isDone() && new Date().getTime() - start
< 30000) {
375 } catch (InterruptedException e
) {
376 getTraceHandler().error(e
);