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