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