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