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