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