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