--tag -> --search-tag
[nikiroo-utils.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> *
37abe20c 40 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
ea734ab4
N
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
0fa0fe95 44 * command) with the given LUID, then return the LUID</li>
37abe20c
NR
45 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
46 * </li>
ea734ab4
N
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>
a85e8077
NR
56 * </ul>
57 *
58 * @author niki
59 */
62c63b07 60public class RemoteLibraryServer extends ServerObject {
ea734ab4 61 private final String key;
b0e88ebd 62
a85e8077
NR
63 /**
64 * Create a new remote server (will not be active until
65 * {@link RemoteLibraryServer#start()} is called).
66 *
2070ced5
NR
67 * @param key
68 * the key that will restrict access to this server
a85e8077
NR
69 * @param port
70 * the port to listen on
71 *
72 * @throws IOException
73 * in case of I/O error
74 */
2070ced5 75 public RemoteLibraryServer(String key, int port) throws IOException {
ea734ab4
N
76 super("Fanfix remote library", port, false);
77 this.key = key;
b9ce9cad
NR
78
79 setTraceHandler(Instance.getTraceHandler());
b0e88ebd
NR
80 }
81
82 @Override
62c63b07 83 protected Object onRequest(ConnectActionServerObject action,
b0e88ebd 84 Version clientVersion, Object data) throws Exception {
ea734ab4
N
85 long start = new Date().getTime();
86
085a2f9a
NR
87 String command = "";
88 Object[] args = new Object[0];
89 if (data instanceof Object[]) {
2070ced5
NR
90 Object[] dataArray = (Object[]) data;
91 if (dataArray.length >= 2) {
ea734ab4 92 command = "" + dataArray[0];
edf79e5e 93
ea734ab4
N
94 args = new Object[dataArray.length - 1];
95 for (int i = 1; i < dataArray.length; i++) {
96 args[i - 1] = dataArray[i];
2070ced5 97 }
b0e88ebd
NR
98 }
99 }
100
652fd9b0 101 String trace = "[ " + command + "] ";
085a2f9a 102 for (Object arg : args) {
b9ce9cad 103 trace += arg + " ";
085a2f9a 104 }
b9ce9cad 105 getTraceHandler().trace(trace);
b0e88ebd 106
ea734ab4
N
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 {
b9ce9cad
NR
120 getTraceHandler().trace("Key rejected.");
121 return null;
2070ced5
NR
122 }
123
9f51d8ab
NR
124 Object rep = doRequest(action, command, args);
125
37abe20c
NR
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)));
9f51d8ab
NR
131
132 return rep;
133 }
134
135 private Object doRequest(ConnectActionServerObject action, String command,
136 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
137 ClassNotFoundException, IOException {
3bbc86a5
NR
138 if ("PING".equals(command)) {
139 return "PONG";
140 } else if ("GET_METADATA".equals(command)) {
7efece85 141 if ("*".equals(args[0])) {
9b863b20 142 Progress pg = createPgForwarder(action);
9f51d8ab
NR
143
144 List<MetaData> metas = new ArrayList<MetaData>();
652fd9b0 145
9f51d8ab
NR
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
9b863b20 158 forcePgDoneSent(pg);
a85e8077
NR
159 return metas.toArray(new MetaData[] {});
160 }
e272f05f 161
37abe20c
NR
162 return new MetaData[] { Instance.getLibrary().getInfo(
163 (String) args[0]) };
a85e8077 164 } else if ("GET_STORY".equals(command)) {
7efece85 165 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
b9ce9cad
NR
166 meta = meta.clone();
167 meta.setCover(null);
168
169 action.send(meta);
170 action.rec();
171
37abe20c
NR
172 Story story = Instance.getLibrary()
173 .getStory((String) args[0], null);
b9ce9cad
NR
174 for (Object obj : breakStory(story)) {
175 action.send(obj);
176 action.rec();
177 }
085a2f9a 178 } else if ("SAVE_STORY".equals(command)) {
b9ce9cad
NR
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);
7efece85 190 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 191 return story.getMeta().getLuid();
edf79e5e 192 } else if ("IMPORT".equals(command)) {
9b863b20 193 Progress pg = createPgForwarder(action);
37abe20c
NR
194 Story story = Instance.getLibrary().imprt(
195 new URL((String) args[0]), pg);
9b863b20 196 forcePgDoneSent(pg);
edf79e5e 197 return story.getMeta().getLuid();
085a2f9a 198 } else if ("DELETE_STORY".equals(command)) {
7efece85 199 Instance.getLibrary().delete((String) args[0]);
e604986c 200 } else if ("GET_COVER".equals(command)) {
7efece85 201 return Instance.getLibrary().getCover((String) args[0]);
3989dfc5
NR
202 } else if ("GET_CUSTOM_COVER".equals(command)) {
203 if ("SOURCE".equals(args[0])) {
37abe20c
NR
204 return Instance.getLibrary().getCustomSourceCover(
205 (String) args[1]);
3989dfc5 206 } else if ("AUTHOR".equals(args[0])) {
37abe20c
NR
207 return Instance.getLibrary().getCustomAuthorCover(
208 (String) args[1]);
3989dfc5
NR
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 }
c8d48938 220 } else if ("CHANGE_STA".equals(command)) {
9b863b20 221 Progress pg = createPgForwarder(action);
c8d48938
NR
222 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
223 (String) args[2], (String) args[3], pg);
9b863b20 224 forcePgDoneSent(pg);
5e848e6a
NR
225 } else if ("EXIT".equals(command)) {
226 stop(0, false);
b0e88ebd
NR
227 }
228
229 return null;
230 }
74a40dfb 231
b9ce9cad
NR
232 @Override
233 protected void onError(Exception e) {
234 getTraceHandler().error(e);
235 }
74a40dfb 236
b9ce9cad
NR
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>();
74a40dfb
NR
247
248 story = story.clone();
b9ce9cad 249 list.add(story);
74a40dfb 250
b9ce9cad
NR
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>());
74a40dfb 256 }
b9ce9cad 257 story.setChapters(new ArrayList<Chapter>());
74a40dfb 258 }
74a40dfb 259
b9ce9cad
NR
260 return list;
261 }
74a40dfb 262
b9ce9cad
NR
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) {
74a40dfb 272 Story story = null;
b9ce9cad 273 Chapter chap = null;
74a40dfb 274
b9ce9cad
NR
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);
74a40dfb
NR
283 }
284 }
285
286 return story;
287 }
288
b9ce9cad
NR
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 }
74a40dfb 315 }
b9ce9cad
NR
316
317 return false;
74a40dfb
NR
318 }
319
b9ce9cad
NR
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) {
9b863b20
NR
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
b9ce9cad 339 final Integer[] p = new Integer[] { -1, -1, -1 };
9b863b20 340 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
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();
37abe20c
NR
346 int relativeProgress = min
347 + (int) Math.round(pg.getRelativeProgress()
348 * (max - min));
b9ce9cad 349
9b863b20
NR
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)) {
b9ce9cad
NR
355 p[0] = min;
356 p[1] = max;
357 p[2] = relativeProgress;
358
359 try {
37abe20c 360 action.send(new Integer[] { min, max, relativeProgress });
b9ce9cad
NR
361 action.rec();
362 } catch (Exception e) {
363 Instance.getTraceHandler().error(e);
364 }
9b863b20 365
9b863b20 366 lastTime[0] = new Date().getTime();
b9ce9cad 367 }
652fd9b0
NR
368
369 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
370 }
371 });
372
373 return pg;
74a40dfb 374 }
9b863b20
NR
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 }
b0e88ebd 388}