remote: better handling of key error
[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;
b0e88ebd 19import be.nikiroo.utils.Version;
62c63b07
NR
20import be.nikiroo.utils.serial.server.ConnectActionServerObject;
21import be.nikiroo.utils.serial.server.ServerObject;
b0e88ebd 22
a85e8077 23/**
ea734ab4 24 * Create a new remote server that will listen for orders on the given port.
a85e8077 25 * <p>
ea734ab4
N
26 * The available commands are given as arrays of objects (first item is the
27 * command, the rest are the arguments).
2a25f781 28 * <p>
a85e8077 29 * <ul>
ea734ab4
N
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> *
37abe20c 33 * <li>GET_METADATA [luid]: will return the metadata of the story of LUID luid</li>
ea734ab4
N
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
0fa0fe95 37 * command) with the given LUID, then return the LUID</li>
37abe20c
NR
38 * <li>IMPORT [url]: save the story found at the given URL, then return the LUID
39 * </li>
ea734ab4
N
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>
a85e8077
NR
49 * </ul>
50 *
51 * @author niki
52 */
62c63b07 53public class RemoteLibraryServer extends ServerObject {
a85e8077
NR
54 /**
55 * Create a new remote server (will not be active until
56 * {@link RemoteLibraryServer#start()} is called).
57 *
2070ced5
NR
58 * @param key
59 * the key that will restrict access to this server
a85e8077
NR
60 * @param port
61 * the port to listen on
62 *
63 * @throws IOException
64 * in case of I/O error
65 */
2070ced5 66 public RemoteLibraryServer(String key, int port) throws IOException {
3040c4f0 67 super("Fanfix remote library", port, key);
b9ce9cad
NR
68
69 setTraceHandler(Instance.getTraceHandler());
b0e88ebd
NR
70 }
71
72 @Override
62c63b07 73 protected Object onRequest(ConnectActionServerObject action,
b0e88ebd 74 Version clientVersion, Object data) throws Exception {
ea734ab4
N
75 long start = new Date().getTime();
76
085a2f9a
NR
77 String command = "";
78 Object[] args = new Object[0];
79 if (data instanceof Object[]) {
2070ced5 80 Object[] dataArray = (Object[]) data;
27eba894 81 if (dataArray.length > 0) {
ea734ab4 82 command = "" + dataArray[0];
edf79e5e 83
ea734ab4
N
84 args = new Object[dataArray.length - 1];
85 for (int i = 1; i < dataArray.length; i++) {
86 args[i - 1] = dataArray[i];
2070ced5 87 }
b0e88ebd
NR
88 }
89 }
90
652fd9b0 91 String trace = "[ " + command + "] ";
085a2f9a 92 for (Object arg : args) {
b9ce9cad 93 trace += arg + " ";
085a2f9a 94 }
49f3dec5 95 System.out.println(trace);
b0e88ebd 96
9f51d8ab
NR
97 Object rep = doRequest(action, command, args);
98
37abe20c
NR
99 String rec = StringUtils.formatNumber(action.getBytesReceived()) + "b";
100 String sent = StringUtils.formatNumber(action.getBytesSent()) + "b";
49f3dec5
NR
101 System.out.println(String.format("[>%s]: (%s sent, %s rec) in %d ms",
102 command, sent, rec, (new Date().getTime() - start)));
9f51d8ab
NR
103
104 return rep;
105 }
106
107 private Object doRequest(ConnectActionServerObject action, String command,
108 Object[] args) throws NoSuchFieldException, NoSuchMethodException,
109 ClassNotFoundException, IOException {
3bbc86a5
NR
110 if ("PING".equals(command)) {
111 return "PONG";
112 } else if ("GET_METADATA".equals(command)) {
7efece85 113 if ("*".equals(args[0])) {
9b863b20 114 Progress pg = createPgForwarder(action);
9f51d8ab
NR
115
116 List<MetaData> metas = new ArrayList<MetaData>();
652fd9b0 117
9f51d8ab
NR
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
9b863b20 130 forcePgDoneSent(pg);
a85e8077
NR
131 return metas.toArray(new MetaData[] {});
132 }
e272f05f 133
37abe20c
NR
134 return new MetaData[] { Instance.getLibrary().getInfo(
135 (String) args[0]) };
a85e8077 136 } else if ("GET_STORY".equals(command)) {
7efece85 137 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
b9ce9cad
NR
138 meta = meta.clone();
139 meta.setCover(null);
140
141 action.send(meta);
142 action.rec();
143
37abe20c
NR
144 Story story = Instance.getLibrary()
145 .getStory((String) args[0], null);
b9ce9cad
NR
146 for (Object obj : breakStory(story)) {
147 action.send(obj);
148 action.rec();
149 }
085a2f9a 150 } else if ("SAVE_STORY".equals(command)) {
b9ce9cad
NR
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);
7efece85 162 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 163 return story.getMeta().getLuid();
edf79e5e 164 } else if ("IMPORT".equals(command)) {
9b863b20 165 Progress pg = createPgForwarder(action);
37abe20c
NR
166 Story story = Instance.getLibrary().imprt(
167 new URL((String) args[0]), pg);
9b863b20 168 forcePgDoneSent(pg);
edf79e5e 169 return story.getMeta().getLuid();
085a2f9a 170 } else if ("DELETE_STORY".equals(command)) {
7efece85 171 Instance.getLibrary().delete((String) args[0]);
e604986c 172 } else if ("GET_COVER".equals(command)) {
7efece85 173 return Instance.getLibrary().getCover((String) args[0]);
3989dfc5
NR
174 } else if ("GET_CUSTOM_COVER".equals(command)) {
175 if ("SOURCE".equals(args[0])) {
37abe20c
NR
176 return Instance.getLibrary().getCustomSourceCover(
177 (String) args[1]);
3989dfc5 178 } else if ("AUTHOR".equals(args[0])) {
37abe20c
NR
179 return Instance.getLibrary().getCustomAuthorCover(
180 (String) args[1]);
3989dfc5
NR
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 }
c8d48938 192 } else if ("CHANGE_STA".equals(command)) {
9b863b20 193 Progress pg = createPgForwarder(action);
c8d48938
NR
194 Instance.getLibrary().changeSTA((String) args[0], (String) args[1],
195 (String) args[2], (String) args[3], pg);
9b863b20 196 forcePgDoneSent(pg);
5e848e6a
NR
197 } else if ("EXIT".equals(command)) {
198 stop(0, false);
b0e88ebd
NR
199 }
200
201 return null;
202 }
74a40dfb 203
b9ce9cad
NR
204 @Override
205 protected void onError(Exception e) {
7e51d91c
NR
206 if (e instanceof SSLException) {
207 System.out.println("[Client connection refused (bad key)]");
208 } else {
209 getTraceHandler().error(e);
210 }
b9ce9cad 211 }
74a40dfb 212
b9ce9cad
NR
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>();
74a40dfb
NR
223
224 story = story.clone();
b9ce9cad 225 list.add(story);
74a40dfb 226
b9ce9cad
NR
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>());
74a40dfb 232 }
b9ce9cad 233 story.setChapters(new ArrayList<Chapter>());
74a40dfb 234 }
74a40dfb 235
b9ce9cad
NR
236 return list;
237 }
74a40dfb 238
b9ce9cad
NR
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) {
74a40dfb 248 Story story = null;
b9ce9cad 249 Chapter chap = null;
74a40dfb 250
b9ce9cad
NR
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);
74a40dfb
NR
259 }
260 }
261
262 return story;
263 }
264
b9ce9cad
NR
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 }
74a40dfb 291 }
b9ce9cad
NR
292
293 return false;
74a40dfb
NR
294 }
295
b9ce9cad
NR
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 */
49f3dec5 305 private Progress createPgForwarder(final ConnectActionServerObject action) {
9b863b20
NR
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
b9ce9cad 314 final Integer[] p = new Integer[] { -1, -1, -1 };
9b863b20 315 final Long[] lastTime = new Long[] { new Date().getTime() };
b9ce9cad
NR
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();
37abe20c
NR
321 int relativeProgress = min
322 + (int) Math.round(pg.getRelativeProgress()
323 * (max - min));
b9ce9cad 324
9b863b20
NR
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)) {
b9ce9cad
NR
330 p[0] = min;
331 p[1] = max;
332 p[2] = relativeProgress;
333
334 try {
37abe20c 335 action.send(new Integer[] { min, max, relativeProgress });
b9ce9cad
NR
336 action.rec();
337 } catch (Exception e) {
49f3dec5 338 getTraceHandler().error(e);
b9ce9cad 339 }
9b863b20 340
9b863b20 341 lastTime[0] = new Date().getTime();
b9ce9cad 342 }
652fd9b0
NR
343
344 isDoneForwarded[0] = (pg.getProgress() >= pg.getMax());
b9ce9cad
NR
345 }
346 });
347
348 return pg;
74a40dfb 349 }
9b863b20
NR
350
351 // with 30 seconds timeout
49f3dec5 352 private void forcePgDoneSent(Progress pg) {
9b863b20
NR
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) {
49f3dec5 359 getTraceHandler().error(e);
9b863b20
NR
360 }
361 }
362 }
b0e88ebd 363}