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