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