remote server -> plain text
[fanfix.git] / src / be / nikiroo / fanfix / library / RemoteLibraryServer.java
CommitLineData
e42573a0 1package be.nikiroo.fanfix.library;
b0e88ebd 2
b0e88ebd 3import java.io.IOException;
edf79e5e 4import java.net.URL;
74a40dfb 5import java.util.ArrayList;
9b863b20 6import java.util.Date;
68e2c6d2 7import java.util.List;
b0e88ebd 8
e42573a0 9import be.nikiroo.fanfix.Instance;
74a40dfb 10import be.nikiroo.fanfix.data.Chapter;
b0e88ebd 11import be.nikiroo.fanfix.data.MetaData;
74a40dfb 12import be.nikiroo.fanfix.data.Paragraph;
085a2f9a 13import be.nikiroo.fanfix.data.Story;
b9ce9cad
NR
14import be.nikiroo.utils.Progress;
15import be.nikiroo.utils.Progress.ProgressListener;
416c54f8 16import be.nikiroo.utils.StringUtils;
b0e88ebd 17import be.nikiroo.utils.Version;
62c63b07
NR
18import be.nikiroo.utils.serial.server.ConnectActionServerObject;
19import be.nikiroo.utils.serial.server.ServerObject;
b0e88ebd 20
a85e8077 21/**
ea734ab4 22 * Create a new remote server that will listen for orders on the given port.
a85e8077 23 * <p>
ea734ab4
N
24 * The available commands are given as arrays of objects (first item is the
25 * command, the rest are the arguments).
2a25f781 26 * <p>
ea734ab4
N
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).
a85e8077 36 * <ul>
ea734ab4
N
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
e272f05f 41 * luid</li>
ea734ab4
N
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
0fa0fe95 45 * command) with the given LUID, then return the LUID</li>
ea734ab4
N
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>
a85e8077
NR
57 * </ul>
58 *
59 * @author niki
60 */
62c63b07 61public class RemoteLibraryServer extends ServerObject {
ea734ab4 62 private final String key;
b0e88ebd 63
a85e8077
NR
64 /**
65 * Create a new remote server (will not be active until
66 * {@link RemoteLibraryServer#start()} is called).
67 *
2070ced5
NR
68 * @param key
69 * the key that will restrict access to this server
a85e8077
NR
70 * @param port
71 * the port to listen on
72 *
73 * @throws IOException
74 * in case of I/O error
75 */
2070ced5 76 public RemoteLibraryServer(String key, int port) throws IOException {
ea734ab4
N
77 super("Fanfix remote library", port, false);
78 this.key = key;
b9ce9cad
NR
79
80 setTraceHandler(Instance.getTraceHandler());
b0e88ebd
NR
81 }
82
83 @Override
62c63b07 84 protected Object onRequest(ConnectActionServerObject action,
b0e88ebd 85 Version clientVersion, Object data) throws Exception {
ea734ab4
N
86 long start = new Date().getTime();
87
085a2f9a
NR
88 String command = "";
89 Object[] args = new Object[0];
90 if (data instanceof Object[]) {
2070ced5
NR
91 Object[] dataArray = (Object[]) data;
92 if (dataArray.length >= 2) {
ea734ab4 93 command = "" + dataArray[0];
edf79e5e 94
ea734ab4
N
95 args = new Object[dataArray.length - 1];
96 for (int i = 1; i < dataArray.length; i++) {
97 args[i - 1] = dataArray[i];
2070ced5 98 }
b0e88ebd
NR
99 }
100 }
101
652fd9b0 102 String trace = "[ " + command + "] ";
085a2f9a 103 for (Object arg : args) {
b9ce9cad 104 trace += arg + " ";
085a2f9a 105 }
b9ce9cad 106 getTraceHandler().trace(trace);
b0e88ebd 107
ea734ab4
N
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 {
b9ce9cad
NR
121 getTraceHandler().trace("Key rejected.");
122 return null;
2070ced5
NR
123 }
124
9f51d8ab
NR
125 Object rep = doRequest(action, command, args);
126
ea734ab4
N
127 getTraceHandler().trace(String.format("[>%s]: %d ms", command,
128 (new Date().getTime() - start)));
9f51d8ab
NR
129
130 return rep;
131 }
132
133 private Object doRequest(ConnectActionServerObject action, String command,
134 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
135 ClassNotFoundException, IOException {
3bbc86a5
NR
136 if ("PING".equals(command)) {
137 return "PONG";
138 } else if ("GET_METADATA".equals(command)) {
7efece85 139 if ("*".equals(args[0])) {
9b863b20 140 Progress pg = createPgForwarder(action);
9f51d8ab
NR
141
142 List<MetaData> metas = new ArrayList<MetaData>();
652fd9b0 143
9f51d8ab
NR
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
9b863b20 156 forcePgDoneSent(pg);
a85e8077
NR
157 return metas.toArray(new MetaData[] {});
158 }
e272f05f 159
ea734ab4
N
160 return new MetaData[] {
161 Instance.getLibrary().getInfo((String) args[0]) };
a85e8077 162 } else if ("GET_STORY".equals(command)) {
7efece85 163 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
b9ce9cad
NR
164 meta = meta.clone();
165 meta.setCover(null);
166
167 action.send(meta);
168 action.rec();
169
ea734ab4
N
170 Story story = Instance.getLibrary().getStory((String) args[0],
171 null);
b9ce9cad
NR
172 for (Object obj : breakStory(story)) {
173 action.send(obj);
174 action.rec();
175 }
085a2f9a 176 } else if ("SAVE_STORY".equals(command)) {
b9ce9cad
NR
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);
7efece85 188 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 189 return story.getMeta().getLuid();
edf79e5e 190 } else if ("IMPORT".equals(command)) {
9b863b20 191 Progress pg = createPgForwarder(action);
ea734ab4
N
192 Story story = Instance.getLibrary().imprt(new URL((String) args[0]),
193 pg);
9b863b20 194 forcePgDoneSent(pg);
edf79e5e 195 return story.getMeta().getLuid();
085a2f9a 196 } else if ("DELETE_STORY".equals(command)) {
7efece85 197 Instance.getLibrary().delete((String) args[0]);
e604986c 198 } else if ("GET_COVER".equals(command)) {
7efece85 199 return Instance.getLibrary().getCover((String) args[0]);
3989dfc5
NR
200 } else if ("GET_CUSTOM_COVER".equals(command)) {
201 if ("SOURCE".equals(args[0])) {
ea734ab4
N
202 return Instance.getLibrary()
203 .getCustomSourceCover((String) args[1]);
3989dfc5 204 } else if ("AUTHOR".equals(args[0])) {
ea734ab4
N
205 return Instance.getLibrary()
206 .getCustomAuthorCover((String) args[1]);
3989dfc5
NR
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 }
c8d48938 218 } else if ("CHANGE_STA".equals(command)) {
9b863b20 219 Progress pg = createPgForwarder(action);
c8d48938
NR
220 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
221 (String) args[2], (String) args[3], pg);
9b863b20 222 forcePgDoneSent(pg);
5e848e6a
NR
223 } else if ("EXIT".equals(command)) {
224 stop(0, false);
b0e88ebd
NR
225 }
226
227 return null;
228 }
74a40dfb 229
b9ce9cad
NR
230 @Override
231 protected void onError(Exception e) {
232 getTraceHandler().error(e);
233 }
74a40dfb 234
b9ce9cad
NR
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>();
74a40dfb
NR
245
246 story = story.clone();
b9ce9cad 247 list.add(story);
74a40dfb 248
b9ce9cad
NR
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>());
74a40dfb 254 }
b9ce9cad 255 story.setChapters(new ArrayList<Chapter>());
74a40dfb 256 }
74a40dfb 257
b9ce9cad
NR
258 return list;
259 }
74a40dfb 260
b9ce9cad
NR
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) {
74a40dfb 270 Story story = null;
b9ce9cad 271 Chapter chap = null;
74a40dfb 272
b9ce9cad
NR
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);
74a40dfb
NR
281 }
282 }
283
284 return story;
285 }
286
b9ce9cad
NR
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 }
74a40dfb 313 }
b9ce9cad
NR
314
315 return false;
74a40dfb
NR
316 }
317
b9ce9cad
NR
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) {
9b863b20
NR
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
b9ce9cad 337 final Integer[] p = new Integer[] { -1, -1, -1 };
9b863b20 338 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
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();
ea734ab4
N
344 int relativeProgress = min + (int) Math
345 .round(pg.getRelativeProgress() * (max - min));
b9ce9cad 346
9b863b20
NR
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)) {
b9ce9cad
NR
352 p[0] = min;
353 p[1] = max;
354 p[2] = relativeProgress;
355
356 try {
ea734ab4
N
357 action.send(
358 new Integer[] { min, max, relativeProgress });
b9ce9cad
NR
359 action.rec();
360 } catch (Exception e) {
361 Instance.getTraceHandler().error(e);
362 }
9b863b20 363
9b863b20 364 lastTime[0] = new Date().getTime();
b9ce9cad 365 }
652fd9b0
NR
366
367 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
368 }
369 });
370
371 return pg;
74a40dfb 372 }
9b863b20
NR
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 }
b0e88ebd 386}