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