b1aebb32e7214f9dcaa6df27e8536d00117dc835
[fanfix.git] / src / be / nikiroo / fanfix / library / RemoteLibraryServer.java
1 package be.nikiroo.fanfix.library;
2
3 import java.io.IOException;
4 import java.net.URL;
5 import java.util.ArrayList;
6 import java.util.Date;
7 import java.util.List;
8
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;
20
21 /**
22 * Create a new remote server that will listen for orders on the given port.
23 * <p>
24 * The available commands are given as arrays of objects (first item is the
25 * command, the rest are the arguments).
26 * <p>
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
30 * connection.
31 * <p>
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
35 * Android).
36 * <ul>
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
42 * not)</li>
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
46 * </li>
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
50 * source/author</li>
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
54 * luid</li>
55 * <li>EXIT: stop the server</li>
56 * </ul>
57 *
58 * @author niki
59 */
60 public class RemoteLibraryServer extends ServerObject {
61 private final String key;
62
63 /**
64 * Create a new remote server (will not be active until
65 * {@link RemoteLibraryServer#start()} is called).
66 *
67 * @param key
68 * the key that will restrict access to this server
69 * @param port
70 * the port to listen on
71 *
72 * @throws IOException
73 * in case of I/O error
74 */
75 public RemoteLibraryServer(String key, int port) throws IOException {
76 super("Fanfix remote library", port, false);
77 this.key = key;
78
79 setTraceHandler(Instance.getTraceHandler());
80 }
81
82 @Override
83 protected Object onRequest(ConnectActionServerObject action,
84 Version clientVersion, Object data) throws Exception {
85 long start = new Date().getTime();
86
87 String command = "";
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];
93
94 args = new Object[dataArray.length - 1];
95 for (int i = 1; i < dataArray.length; i++) {
96 args[i - 1] = dataArray[i];
97 }
98 }
99 }
100
101 String trace = "[ " + command + "] ";
102 for (Object arg : args) {
103 trace += arg + " ";
104 }
105 getTraceHandler().trace(trace);
106
107 // Authentication:
108 String random = StringUtils.getMd5Hash(Double.toString(Math.random()));
109 action.send(random);
110 String answer = "";
111 try {
112 answer += action.rec();
113 } catch (NullPointerException e) {
114 return null;
115 }
116
117 if (answer.equals(RemoteLibrary.hashKey(key, random))) {
118 action.send(true);
119 } else {
120 getTraceHandler().trace("Key rejected.");
121 return null;
122 }
123
124 Object rep = doRequest(action, command, args);
125
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)));
131
132 return rep;
133 }
134
135 private Object doRequest(ConnectActionServerObject action, String command,
136 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
137 ClassNotFoundException, IOException {
138 if ("PING".equals(command)) {
139 return "PONG";
140 } else if ("GET_METADATA".equals(command)) {
141 if ("*".equals(args[0])) {
142 Progress pg = createPgForwarder(action);
143
144 List<MetaData> metas = new ArrayList<MetaData>();
145
146 for (MetaData meta : Instance.getLibrary().getMetas(pg)) {
147 MetaData light;
148 if (meta.getCover() == null) {
149 light = meta;
150 } else {
151 light = meta.clone();
152 light.setCover(null);
153 }
154
155 metas.add(light);
156 }
157
158 forcePgDoneSent(pg);
159 return metas.toArray(new MetaData[] {});
160 }
161
162 return new MetaData[] { Instance.getLibrary().getInfo(
163 (String) args[0]) };
164 } else if ("GET_STORY".equals(command)) {
165 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
166 meta = meta.clone();
167 meta.setCover(null);
168
169 action.send(meta);
170 action.rec();
171
172 Story story = Instance.getLibrary()
173 .getStory((String) args[0], null);
174 for (Object obj : breakStory(story)) {
175 action.send(obj);
176 action.rec();
177 }
178 } else if ("SAVE_STORY".equals(command)) {
179 List<Object> list = new ArrayList<Object>();
180
181 action.send(null);
182 Object obj = action.rec();
183 while (obj != null) {
184 list.add(obj);
185 action.send(null);
186 obj = action.rec();
187 }
188
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);
196 forcePgDoneSent(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(
205 (String) args[1]);
206 } else if ("AUTHOR".equals(args[0])) {
207 return Instance.getLibrary().getCustomAuthorCover(
208 (String) args[1]);
209 } else {
210 return null;
211 }
212 } else if ("SET_COVER".equals(command)) {
213 if ("SOURCE".equals(args[0])) {
214 Instance.getLibrary().setSourceCover((String) args[1],
215 (String) args[2]);
216 } else if ("AUTHOR".equals(args[0])) {
217 Instance.getLibrary().setAuthorCover((String) args[1],
218 (String) args[2]);
219 }
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);
224 forcePgDoneSent(pg);
225 } else if ("EXIT".equals(command)) {
226 stop(0, false);
227 }
228
229 return null;
230 }
231
232 @Override
233 protected void onError(Exception e) {
234 getTraceHandler().error(e);
235 }
236
237 /**
238 * Break a story in multiple {@link Object}s for easier serialisation.
239 *
240 * @param story
241 * the {@link Story} to break
242 *
243 * @return the list of {@link Object}s
244 */
245 static List<Object> breakStory(Story story) {
246 List<Object> list = new ArrayList<Object>();
247
248 story = story.clone();
249 list.add(story);
250
251 if (story.getMeta().isImageDocument()) {
252 for (Chapter chap : story) {
253 list.add(chap);
254 list.addAll(chap.getParagraphs());
255 chap.setParagraphs(new ArrayList<Paragraph>());
256 }
257 story.setChapters(new ArrayList<Chapter>());
258 }
259
260 return list;
261 }
262
263 /**
264 * Rebuild a story from a list of broke up {@link Story} parts.
265 *
266 * @param list
267 * the list of {@link Story} parts
268 *
269 * @return the reconstructed {@link Story}
270 */
271 static Story rebuildStory(List<Object> list) {
272 Story story = null;
273 Chapter chap = null;
274
275 for (Object obj : list) {
276 if (obj instanceof Story) {
277 story = (Story) obj;
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);
283 }
284 }
285
286 return story;
287 }
288
289 /**
290 * Update the {@link Progress} with the adequate {@link Object} received
291 * from the network via {@link RemoteLibraryServer}.
292 *
293 * @param pg
294 * the {@link Progress} to update
295 * @param rep
296 * the object received from the network
297 *
298 * @return TRUE if it was a progress event, FALSE if not
299 */
300 static boolean updateProgress(Progress pg, Object rep) {
301 if (rep instanceof Integer[]) {
302 Integer[] a = (Integer[]) rep;
303 if (a.length == 3) {
304 int min = a[0];
305 int max = a[1];
306 int progress = a[2];
307
308 if (min >= 0 && min <= max) {
309 pg.setMinMax(min, max);
310 pg.setProgress(progress);
311
312 return true;
313 }
314 }
315 }
316
317 return false;
318 }
319
320 /**
321 * Create a {@link Progress} that will forward its progress over the
322 * network.
323 *
324 * @param action
325 * the {@link ConnectActionServerObject} to use to forward it
326 *
327 * @return the {@link Progress}
328 */
329 private static Progress createPgForwarder(
330 final ConnectActionServerObject action) {
331 final Boolean[] isDoneForwarded = new Boolean[] { false };
332 final Progress pg = new Progress() {
333 @Override
334 public boolean isDone() {
335 return isDoneForwarded[0];
336 }
337 };
338
339 final Integer[] p = new Integer[] { -1, -1, -1 };
340 final Long[] lastTime = new Long[] { new Date().getTime() };
341 pg.addProgressListener(new ProgressListener() {
342 @Override
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()
348 * (max - min));
349
350 // Do not re-send the same value twice over the wire,
351 // unless more than 2 seconds have elapsed (to maintain the
352 // connection)
353 if ((p[0] != min || p[1] != max || p[2] != relativeProgress)
354 || (new Date().getTime() - lastTime[0] > 2000)) {
355 p[0] = min;
356 p[1] = max;
357 p[2] = relativeProgress;
358
359 try {
360 action.send(new Integer[] { min, max, relativeProgress });
361 action.rec();
362 } catch (Exception e) {
363 Instance.getTraceHandler().error(e);
364 }
365
366 lastTime[0] = new Date().getTime();
367 }
368
369 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
370 }
371 });
372
373 return pg;
374 }
375
376 // with 30 seconds timeout
377 private static void forcePgDoneSent(Progress pg) {
378 long start = new Date().getTime();
379 pg.done();
380 while (!pg.isDone() && new Date().getTime() - start < 30000) {
381 try {
382 Thread.sleep(100);
383 } catch (InterruptedException e) {
384 Instance.getTraceHandler().error(e);
385 }
386 }
387 }
388 }