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