ssl -> cryptutils
[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
49f3dec5 29 * value not correct, the connection will be closed.
ea734ab4
N
30 * <p>
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
34 * Android).
a85e8077 35 * <ul>
ea734ab4
N
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> *
37abe20c 39 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
ea734ab4
N
40 * <li>GET_STORY [luid]: will return the given story if it exists (or NULL if
41 * not)</li>
42 * <li>SAVE_STORY [luid]: save the story (that must be sent just after the
0fa0fe95 43 * command) with the given LUID, then return the LUID</li>
37abe20c
NR
44 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
45 * </li>
ea734ab4
N
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
49 * source/author</li>
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
53 * luid</li>
54 * <li>EXIT: stop the server</li>
a85e8077
NR
55 * </ul>
56 *
57 * @author niki
58 */
62c63b07 59public class RemoteLibraryServer extends ServerObject {
ea734ab4 60 private final String key;
b0e88ebd 61
a85e8077
NR
62 /**
63 * Create a new remote server (will not be active until
64 * {@link RemoteLibraryServer#start()} is called).
65 *
2070ced5
NR
66 * @param key
67 * the key that will restrict access to this server
a85e8077
NR
68 * @param port
69 * the port to listen on
70 *
71 * @throws IOException
72 * in case of I/O error
73 */
2070ced5 74 public RemoteLibraryServer(String key, int port) throws IOException {
3040c4f0 75 super("Fanfix remote library", port, key);
ea734ab4 76 this.key = key;
b9ce9cad
NR
77
78 setTraceHandler(Instance.getTraceHandler());
b0e88ebd
NR
79 }
80
81 @Override
62c63b07 82 protected Object onRequest(ConnectActionServerObject action,
b0e88ebd 83 Version clientVersion, Object data) throws Exception {
ea734ab4
N
84 long start = new Date().getTime();
85
085a2f9a
NR
86 String command = "";
87 Object[] args = new Object[0];
88 if (data instanceof Object[]) {
2070ced5 89 Object[] dataArray = (Object[]) data;
27eba894 90 if (dataArray.length > 0) {
ea734ab4 91 command = "" + dataArray[0];
edf79e5e 92
ea734ab4
N
93 args = new Object[dataArray.length - 1];
94 for (int i = 1; i < dataArray.length; i++) {
95 args[i - 1] = dataArray[i];
2070ced5 96 }
b0e88ebd
NR
97 }
98 }
99
652fd9b0 100 String trace = "[ " + command + "] ";
085a2f9a 101 for (Object arg : args) {
b9ce9cad 102 trace += arg + " ";
085a2f9a 103 }
49f3dec5 104 System.out.println(trace);
b0e88ebd 105
ea734ab4
N
106 // Authentication:
107 String random = StringUtils.getMd5Hash(Double.toString(Math.random()));
108 action.send(random);
49f3dec5 109 String answer = "" + action.rec();
ea734ab4 110
49f3dec5
NR
111 if (!answer.equals(RemoteLibrary.hashKey(key, random))) {
112 System.out.println("Key rejected.");
113 action.close();
b9ce9cad 114 return null;
2070ced5 115 }
49f3dec5 116 //
2070ced5 117
9f51d8ab
NR
118 Object rep = doRequest(action, command, args);
119
37abe20c
NR
120 String rec = StringUtils.formatNumber(action.getBytesReceived()) + "b";
121 String sent = StringUtils.formatNumber(action.getBytesSent()) + "b";
49f3dec5
NR
122 System.out.println(String.format("[>%s]: (%s sent, %s rec) in %d ms",
123 command, sent, rec, (new Date().getTime() - start)));
9f51d8ab
NR
124
125 return rep;
126 }
127
128 private Object doRequest(ConnectActionServerObject action, String command,
129 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
130 ClassNotFoundException, IOException {
3bbc86a5
NR
131 if ("PING".equals(command)) {
132 return "PONG";
133 } else if ("GET_METADATA".equals(command)) {
7efece85 134 if ("*".equals(args[0])) {
9b863b20 135 Progress pg = createPgForwarder(action);
9f51d8ab
NR
136
137 List<MetaData> metas = new ArrayList<MetaData>();
652fd9b0 138
9f51d8ab
NR
139 for (MetaData meta : Instance.getLibrary().getMetas(pg)) {
140 MetaData light;
141 if (meta.getCover() == null) {
142 light = meta;
143 } else {
144 light = meta.clone();
145 light.setCover(null);
146 }
147
148 metas.add(light);
149 }
150
9b863b20 151 forcePgDoneSent(pg);
a85e8077
NR
152 return metas.toArray(new MetaData[] {});
153 }
e272f05f 154
37abe20c
NR
155 return new MetaData[] { Instance.getLibrary().getInfo(
156 (String) args[0]) };
a85e8077 157 } else if ("GET_STORY".equals(command)) {
7efece85 158 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
b9ce9cad
NR
159 meta = meta.clone();
160 meta.setCover(null);
161
162 action.send(meta);
163 action.rec();
164
37abe20c
NR
165 Story story = Instance.getLibrary()
166 .getStory((String) args[0], null);
b9ce9cad
NR
167 for (Object obj : breakStory(story)) {
168 action.send(obj);
169 action.rec();
170 }
085a2f9a 171 } else if ("SAVE_STORY".equals(command)) {
b9ce9cad
NR
172 List<Object> list = new ArrayList<Object>();
173
174 action.send(null);
175 Object obj = action.rec();
176 while (obj != null) {
177 list.add(obj);
178 action.send(null);
179 obj = action.rec();
180 }
181
182 Story story = rebuildStory(list);
7efece85 183 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 184 return story.getMeta().getLuid();
edf79e5e 185 } else if ("IMPORT".equals(command)) {
9b863b20 186 Progress pg = createPgForwarder(action);
37abe20c
NR
187 Story story = Instance.getLibrary().imprt(
188 new URL((String) args[0]), pg);
9b863b20 189 forcePgDoneSent(pg);
edf79e5e 190 return story.getMeta().getLuid();
085a2f9a 191 } else if ("DELETE_STORY".equals(command)) {
7efece85 192 Instance.getLibrary().delete((String) args[0]);
e604986c 193 } else if ("GET_COVER".equals(command)) {
7efece85 194 return Instance.getLibrary().getCover((String) args[0]);
3989dfc5
NR
195 } else if ("GET_CUSTOM_COVER".equals(command)) {
196 if ("SOURCE".equals(args[0])) {
37abe20c
NR
197 return Instance.getLibrary().getCustomSourceCover(
198 (String) args[1]);
3989dfc5 199 } else if ("AUTHOR".equals(args[0])) {
37abe20c
NR
200 return Instance.getLibrary().getCustomAuthorCover(
201 (String) args[1]);
3989dfc5
NR
202 } else {
203 return null;
204 }
205 } else if ("SET_COVER".equals(command)) {
206 if ("SOURCE".equals(args[0])) {
207 Instance.getLibrary().setSourceCover((String) args[1],
208 (String) args[2]);
209 } else if ("AUTHOR".equals(args[0])) {
210 Instance.getLibrary().setAuthorCover((String) args[1],
211 (String) args[2]);
212 }
c8d48938 213 } else if ("CHANGE_STA".equals(command)) {
9b863b20 214 Progress pg = createPgForwarder(action);
c8d48938
NR
215 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
216 (String) args[2], (String) args[3], pg);
9b863b20 217 forcePgDoneSent(pg);
5e848e6a
NR
218 } else if ("EXIT".equals(command)) {
219 stop(0, false);
b0e88ebd
NR
220 }
221
222 return null;
223 }
74a40dfb 224
b9ce9cad
NR
225 @Override
226 protected void onError(Exception e) {
227 getTraceHandler().error(e);
228 }
74a40dfb 229
b9ce9cad
NR
230 /**
231 * Break a story in multiple {@link Object}s for easier serialisation.
232 *
233 * @param story
234 * the {@link Story} to break
235 *
236 * @return the list of {@link Object}s
237 */
238 static List<Object> breakStory(Story story) {
239 List<Object> list = new ArrayList<Object>();
74a40dfb
NR
240
241 story = story.clone();
b9ce9cad 242 list.add(story);
74a40dfb 243
b9ce9cad
NR
244 if (story.getMeta().isImageDocument()) {
245 for (Chapter chap : story) {
246 list.add(chap);
247 list.addAll(chap.getParagraphs());
248 chap.setParagraphs(new ArrayList<Paragraph>());
74a40dfb 249 }
b9ce9cad 250 story.setChapters(new ArrayList<Chapter>());
74a40dfb 251 }
74a40dfb 252
b9ce9cad
NR
253 return list;
254 }
74a40dfb 255
b9ce9cad
NR
256 /**
257 * Rebuild a story from a list of broke up {@link Story} parts.
258 *
259 * @param list
260 * the list of {@link Story} parts
261 *
262 * @return the reconstructed {@link Story}
263 */
264 static Story rebuildStory(List<Object> list) {
74a40dfb 265 Story story = null;
b9ce9cad 266 Chapter chap = null;
74a40dfb 267
b9ce9cad
NR
268 for (Object obj : list) {
269 if (obj instanceof Story) {
270 story = (Story) obj;
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);
74a40dfb
NR
276 }
277 }
278
279 return story;
280 }
281
b9ce9cad
NR
282 /**
283 * Update the {@link Progress} with the adequate {@link Object} received
284 * from the network via {@link RemoteLibraryServer}.
285 *
286 * @param pg
287 * the {@link Progress} to update
288 * @param rep
289 * the object received from the network
290 *
291 * @return TRUE if it was a progress event, FALSE if not
292 */
293 static boolean updateProgress(Progress pg, Object rep) {
294 if (rep instanceof Integer[]) {
295 Integer[] a = (Integer[]) rep;
296 if (a.length == 3) {
297 int min = a[0];
298 int max = a[1];
299 int progress = a[2];
300
301 if (min >= 0 && min <= max) {
302 pg.setMinMax(min, max);
303 pg.setProgress(progress);
304
305 return true;
306 }
307 }
74a40dfb 308 }
b9ce9cad
NR
309
310 return false;
74a40dfb
NR
311 }
312
b9ce9cad
NR
313 /**
314 * Create a {@link Progress} that will forward its progress over the
315 * network.
316 *
317 * @param action
318 * the {@link ConnectActionServerObject} to use to forward it
319 *
320 * @return the {@link Progress}
321 */
49f3dec5 322 private Progress createPgForwarder(final ConnectActionServerObject action) {
9b863b20
NR
323 final Boolean[] isDoneForwarded = new Boolean[] { false };
324 final Progress pg = new Progress() {
325 @Override
326 public boolean isDone() {
327 return isDoneForwarded[0];
328 }
329 };
330
b9ce9cad 331 final Integer[] p = new Integer[] { -1, -1, -1 };
9b863b20 332 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
333 pg.addProgressListener(new ProgressListener() {
334 @Override
335 public void progress(Progress progress, String name) {
336 int min = pg.getMin();
337 int max = pg.getMax();
37abe20c
NR
338 int relativeProgress = min
339 + (int) Math.round(pg.getRelativeProgress()
340 * (max - min));
b9ce9cad 341
9b863b20
NR
342 // Do not re-send the same value twice over the wire,
343 // unless more than 2 seconds have elapsed (to maintain the
344 // connection)
345 if ((p[0] != min || p[1] != max || p[2] != relativeProgress)
346 || (new Date().getTime() - lastTime[0] > 2000)) {
b9ce9cad
NR
347 p[0] = min;
348 p[1] = max;
349 p[2] = relativeProgress;
350
351 try {
37abe20c 352 action.send(new Integer[] { min, max, relativeProgress });
b9ce9cad
NR
353 action.rec();
354 } catch (Exception e) {
49f3dec5 355 getTraceHandler().error(e);
b9ce9cad 356 }
9b863b20 357
9b863b20 358 lastTime[0] = new Date().getTime();
b9ce9cad 359 }
652fd9b0
NR
360
361 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
362 }
363 });
364
365 return pg;
74a40dfb 366 }
9b863b20
NR
367
368 // with 30 seconds timeout
49f3dec5 369 private void forcePgDoneSent(Progress pg) {
9b863b20
NR
370 long start = new Date().getTime();
371 pg.done();
372 while (!pg.isDone() && new Date().getTime() - start < 30000) {
373 try {
374 Thread.sleep(100);
375 } catch (InterruptedException e) {
49f3dec5 376 getTraceHandler().error(e);
9b863b20
NR
377 }
378 }
379 }
b0e88ebd 380}