update nikiroo-utils, better rec/send remote server info
[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.HashMap;
8 import java.util.List;
9 import java.util.Map;
10
11 import javax.net.ssl.SSLException;
12
13 import be.nikiroo.fanfix.Instance;
14 import be.nikiroo.fanfix.data.Chapter;
15 import be.nikiroo.fanfix.data.MetaData;
16 import be.nikiroo.fanfix.data.Paragraph;
17 import be.nikiroo.fanfix.data.Story;
18 import be.nikiroo.utils.Progress;
19 import be.nikiroo.utils.Progress.ProgressListener;
20 import be.nikiroo.utils.StringUtils;
21 import be.nikiroo.utils.serial.server.ConnectActionServerObject;
22 import be.nikiroo.utils.serial.server.ServerObject;
23
24 /**
25 * Create a new remote server that will listen for orders on the given port.
26 * <p>
27 * The available commands are given as arrays of objects (first item is the
28 * command, the rest are the arguments).
29 * <p>
30 * <ul>
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> *
34 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
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
38 * command) with the given LUID, then return the LUID</li>
39 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
40 * </li>
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>
50 * </ul>
51 *
52 * @author niki
53 */
54 public class RemoteLibraryServer extends ServerObject {
55 private Map<Long, String> commands = new HashMap<Long, String>();
56 private Map<Long, Long> times = new HashMap<Long, Long>();
57
58 /**
59 * Create a new remote server (will not be active until
60 * {@link RemoteLibraryServer#start()} is called).
61 *
62 * @param key
63 * the key that will restrict access to this server
64 * @param port
65 * the port to listen on
66 *
67 * @throws IOException
68 * in case of I/O error
69 */
70 public RemoteLibraryServer(String key, int port) throws IOException {
71 super("Fanfix remote library", port, key);
72 setTraceHandler(Instance.getTraceHandler());
73 }
74
75 @Override
76 protected Object onRequest(ConnectActionServerObject action, Object data,
77 long id) throws Exception {
78 long start = new Date().getTime();
79
80 String command = "";
81 Object[] args = new Object[0];
82 if (data instanceof Object[]) {
83 Object[] dataArray = (Object[]) data;
84 if (dataArray.length > 0) {
85 command = "" + dataArray[0];
86
87 args = new Object[dataArray.length - 1];
88 for (int i = 1; i < dataArray.length; i++) {
89 args[i - 1] = dataArray[i];
90 }
91 }
92 }
93
94 String trace = "[ " + command + "] ";
95 for (Object arg : args) {
96 trace += arg + " ";
97 }
98 System.out.println(trace);
99
100 Object rep = doRequest(action, command, args);
101
102 commands.put(id, command);
103 times.put(id, (new Date().getTime() - start));
104
105 return rep;
106 }
107
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
118 private Object doRequest(ConnectActionServerObject action, String command,
119 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
120 ClassNotFoundException, IOException {
121 if ("PING".equals(command)) {
122 return "PONG";
123 } else if ("GET_METADATA".equals(command)) {
124 if ("*".equals(args[0])) {
125 Progress pg = createPgForwarder(action);
126
127 List<MetaData> metas = new ArrayList<MetaData>();
128
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
141 forcePgDoneSent(pg);
142 return metas.toArray(new MetaData[] {});
143 }
144
145 return new MetaData[] { Instance.getLibrary().getInfo(
146 (String) args[0]) };
147 } else if ("GET_STORY".equals(command)) {
148 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
149 meta = meta.clone();
150 meta.setCover(null);
151
152 action.send(meta);
153 action.rec();
154
155 Story story = Instance.getLibrary()
156 .getStory((String) args[0], null);
157 for (Object obj : breakStory(story)) {
158 action.send(obj);
159 action.rec();
160 }
161 } else if ("SAVE_STORY".equals(command)) {
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);
173 Instance.getLibrary().save(story, (String) args[0], null);
174 return story.getMeta().getLuid();
175 } else if ("IMPORT".equals(command)) {
176 Progress pg = createPgForwarder(action);
177 Story story = Instance.getLibrary().imprt(
178 new URL((String) args[0]), pg);
179 forcePgDoneSent(pg);
180 return story.getMeta().getLuid();
181 } else if ("DELETE_STORY".equals(command)) {
182 Instance.getLibrary().delete((String) args[0]);
183 } else if ("GET_COVER".equals(command)) {
184 return Instance.getLibrary().getCover((String) args[0]);
185 } else if ("GET_CUSTOM_COVER".equals(command)) {
186 if ("SOURCE".equals(args[0])) {
187 return Instance.getLibrary().getCustomSourceCover(
188 (String) args[1]);
189 } else if ("AUTHOR".equals(args[0])) {
190 return Instance.getLibrary().getCustomAuthorCover(
191 (String) args[1]);
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 }
203 } else if ("CHANGE_STA".equals(command)) {
204 Progress pg = createPgForwarder(action);
205 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
206 (String) args[2], (String) args[3], pg);
207 forcePgDoneSent(pg);
208 } else if ("EXIT".equals(command)) {
209 stop(0, false);
210 }
211
212 return null;
213 }
214
215 @Override
216 protected void onError(Exception e) {
217 if (e instanceof SSLException) {
218 System.out.println("[Client connection refused (bad key)]");
219 } else {
220 getTraceHandler().error(e);
221 }
222 }
223
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>();
234
235 story = story.clone();
236 list.add(story);
237
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>());
243 }
244 story.setChapters(new ArrayList<Chapter>());
245 }
246
247 return list;
248 }
249
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) {
259 Story story = null;
260 Chapter chap = null;
261
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);
270 }
271 }
272
273 return story;
274 }
275
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 }
302 }
303
304 return false;
305 }
306
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 */
316 private Progress createPgForwarder(final ConnectActionServerObject action) {
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
325 final Integer[] p = new Integer[] { -1, -1, -1 };
326 final Long[] lastTime = new Long[] { new Date().getTime() };
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();
332 int relativeProgress = min
333 + (int) Math.round(pg.getRelativeProgress()
334 * (max - min));
335
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)) {
341 p[0] = min;
342 p[1] = max;
343 p[2] = relativeProgress;
344
345 try {
346 action.send(new Integer[] { min, max, relativeProgress });
347 action.rec();
348 } catch (Exception e) {
349 getTraceHandler().error(e);
350 }
351
352 lastTime[0] = new Date().getTime();
353 }
354
355 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
356 }
357 });
358
359 return pg;
360 }
361
362 // with 30 seconds timeout
363 private void forcePgDoneSent(Progress pg) {
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) {
370 getTraceHandler().error(e);
371 }
372 }
373 }
374 }