Fix remote saving
[nikiroo-utils.git] / src / be / nikiroo / fanfix / library / RemoteLibraryServer.java
CommitLineData
e42573a0 1package be.nikiroo.fanfix.library;
b0e88ebd 2
b0e88ebd 3import java.io.IOException;
085a2f9a 4import java.security.InvalidParameterException;
74a40dfb 5import java.util.ArrayList;
68e2c6d2 6import java.util.List;
b0e88ebd 7
e42573a0 8import be.nikiroo.fanfix.Instance;
74a40dfb 9import be.nikiroo.fanfix.data.Chapter;
b0e88ebd 10import be.nikiroo.fanfix.data.MetaData;
74a40dfb 11import be.nikiroo.fanfix.data.Paragraph;
085a2f9a 12import be.nikiroo.fanfix.data.Story;
b9ce9cad
NR
13import be.nikiroo.utils.Progress;
14import be.nikiroo.utils.Progress.ProgressListener;
416c54f8 15import be.nikiroo.utils.StringUtils;
b0e88ebd 16import be.nikiroo.utils.Version;
62c63b07
NR
17import be.nikiroo.utils.serial.server.ConnectActionServerObject;
18import be.nikiroo.utils.serial.server.ServerObject;
b0e88ebd 19
a85e8077
NR
20/**
21 * Create a new remote server that will listen for order on the given port.
22 * <p>
2a25f781
NR
23 * The available commands are given as arrays of objects (first item is the key,
24 * second is the command, the rest are the arguments).
25 * <p>
416c54f8
NR
26 * The md5 is always a String (the MD5 hash of the access key), the commands are
27 * also Strings; the parameters vary depending upon the command.
a85e8077 28 * <ul>
416c54f8
NR
29 * <li>[md5] PING: will return PONG if the key is accepted</li>
30 * <li>[md5] GET_METADATA *: will return the metadata of all the stories in the
085a2f9a 31 * library</li>
416c54f8 32 * <li>[md5] GET_STORY [luid]: will return the given story if it exists (or NULL
2070ced5 33 * if not)</li>
416c54f8 34 * <li>[md5] SAVE_STORY [luid]: save the story (that must be sent just after the
0fa0fe95 35 * command) with the given LUID, then return the LUID</li>
416c54f8
NR
36 * <li>[md5] DELETE_STORY [luid]: delete the story of LUID luid</li>
37 * <li>[md5] GET_COVER [luid]: return the cover of the story</li>
38 * <li>[md5] GET_SOURCE_COVER [source]: return the cover for this source</li>
39 * <li>[md5] SET_SOURCE_COVER [source], [luid]: set the default cover for the
2070ced5 40 * given source to the cover of the story denoted by luid</li>
416c54f8 41 * <li>[md5] EXIT: stop the server</li>
a85e8077
NR
42 * </ul>
43 *
44 * @author niki
45 */
62c63b07 46public class RemoteLibraryServer extends ServerObject {
416c54f8 47 private final String md5;
b0e88ebd 48
a85e8077
NR
49 /**
50 * Create a new remote server (will not be active until
51 * {@link RemoteLibraryServer#start()} is called).
52 *
2070ced5
NR
53 * @param key
54 * the key that will restrict access to this server
a85e8077
NR
55 * @param port
56 * the port to listen on
57 *
58 * @throws IOException
59 * in case of I/O error
60 */
2070ced5 61 public RemoteLibraryServer(String key, int port) throws IOException {
22b2b942 62 super("Fanfix remote library", port, true);
416c54f8 63 this.md5 = StringUtils.getMd5Hash(key);
b9ce9cad
NR
64
65 setTraceHandler(Instance.getTraceHandler());
b0e88ebd
NR
66 }
67
68 @Override
62c63b07 69 protected Object onRequest(ConnectActionServerObject action,
b0e88ebd 70 Version clientVersion, Object data) throws Exception {
416c54f8 71 String md5 = "";
085a2f9a
NR
72 String command = "";
73 Object[] args = new Object[0];
74 if (data instanceof Object[]) {
2070ced5
NR
75 Object[] dataArray = (Object[]) data;
76 if (dataArray.length >= 2) {
77 args = new Object[dataArray.length - 2];
78 for (int i = 2; i < dataArray.length; i++) {
f569d249 79 args[i - 2] = dataArray[i];
2070ced5
NR
80 }
81
416c54f8 82 md5 = "" + dataArray[0];
2070ced5 83 command = "" + dataArray[1];
b0e88ebd
NR
84 }
85 }
86
b9ce9cad 87 String trace = "[" + command + "] ";
085a2f9a 88 for (Object arg : args) {
b9ce9cad 89 trace += arg + " ";
085a2f9a 90 }
b9ce9cad 91 getTraceHandler().trace(trace);
b0e88ebd 92
416c54f8 93 if (!md5.equals(this.md5)) {
b9ce9cad
NR
94 getTraceHandler().trace("Key rejected.");
95 return null;
2070ced5
NR
96 }
97
3bbc86a5
NR
98 if ("PING".equals(command)) {
99 return "PONG";
100 } else if ("GET_METADATA".equals(command)) {
7efece85 101 if ("*".equals(args[0])) {
b9ce9cad
NR
102 List<MetaData> metas = Instance.getLibrary().getMetas(
103 createPgForwarder(action));
a85e8077
NR
104 return metas.toArray(new MetaData[] {});
105 }
085a2f9a 106 throw new InvalidParameterException(
2070ced5 107 "only * is valid here, but you passed: " + args[0]);
a85e8077 108 } else if ("GET_STORY".equals(command)) {
7efece85 109 MetaData meta = Instance.getLibrary().getInfo((String) args[0]);
b9ce9cad
NR
110 meta = meta.clone();
111 meta.setCover(null);
112
113 action.send(meta);
114 action.rec();
115
7efece85
NR
116 Story story = Instance.getLibrary()
117 .getStory((String) args[0], null);
b9ce9cad
NR
118 for (Object obj : breakStory(story)) {
119 action.send(obj);
120 action.rec();
121 }
085a2f9a 122 } else if ("SAVE_STORY".equals(command)) {
b9ce9cad
NR
123 List<Object> list = new ArrayList<Object>();
124
125 action.send(null);
126 Object obj = action.rec();
127 while (obj != null) {
128 list.add(obj);
129 action.send(null);
130 obj = action.rec();
131 }
132
133 Story story = rebuildStory(list);
7efece85 134 Instance.getLibrary().save(story, (String) args[0], null);
0fa0fe95 135 return story.getMeta().getLuid();
085a2f9a 136 } else if ("DELETE_STORY".equals(command)) {
7efece85 137 Instance.getLibrary().delete((String) args[0]);
e604986c 138 } else if ("GET_COVER".equals(command)) {
7efece85 139 return Instance.getLibrary().getCover((String) args[0]);
085a2f9a 140 } else if ("GET_SOURCE_COVER".equals(command)) {
7efece85 141 return Instance.getLibrary().getSourceCover((String) args[0]);
085a2f9a 142 } else if ("SET_SOURCE_COVER".equals(command)) {
7efece85
NR
143 Instance.getLibrary().setSourceCover((String) args[0],
144 (String) args[1]);
5e848e6a
NR
145 } else if ("EXIT".equals(command)) {
146 stop(0, false);
b0e88ebd
NR
147 }
148
149 return null;
150 }
74a40dfb 151
b9ce9cad
NR
152 @Override
153 protected void onError(Exception e) {
154 getTraceHandler().error(e);
155 }
74a40dfb 156
b9ce9cad
NR
157 /**
158 * Break a story in multiple {@link Object}s for easier serialisation.
159 *
160 * @param story
161 * the {@link Story} to break
162 *
163 * @return the list of {@link Object}s
164 */
165 static List<Object> breakStory(Story story) {
166 List<Object> list = new ArrayList<Object>();
74a40dfb
NR
167
168 story = story.clone();
b9ce9cad 169 list.add(story);
74a40dfb 170
b9ce9cad
NR
171 if (story.getMeta().isImageDocument()) {
172 for (Chapter chap : story) {
173 list.add(chap);
174 list.addAll(chap.getParagraphs());
175 chap.setParagraphs(new ArrayList<Paragraph>());
74a40dfb 176 }
b9ce9cad 177 story.setChapters(new ArrayList<Chapter>());
74a40dfb 178 }
74a40dfb 179
b9ce9cad
NR
180 return list;
181 }
74a40dfb 182
b9ce9cad
NR
183 /**
184 * Rebuild a story from a list of broke up {@link Story} parts.
185 *
186 * @param list
187 * the list of {@link Story} parts
188 *
189 * @return the reconstructed {@link Story}
190 */
191 static Story rebuildStory(List<Object> list) {
74a40dfb 192 Story story = null;
b9ce9cad 193 Chapter chap = null;
74a40dfb 194
b9ce9cad
NR
195 for (Object obj : list) {
196 if (obj instanceof Story) {
197 story = (Story) obj;
198 } else if (obj instanceof Chapter) {
199 chap = (Chapter) obj;
200 story.getChapters().add(chap);
201 } else if (obj instanceof Paragraph) {
202 chap.getParagraphs().add((Paragraph) obj);
74a40dfb
NR
203 }
204 }
205
206 return story;
207 }
208
b9ce9cad
NR
209 /**
210 * Update the {@link Progress} with the adequate {@link Object} received
211 * from the network via {@link RemoteLibraryServer}.
212 *
213 * @param pg
214 * the {@link Progress} to update
215 * @param rep
216 * the object received from the network
217 *
218 * @return TRUE if it was a progress event, FALSE if not
219 */
220 static boolean updateProgress(Progress pg, Object rep) {
221 if (rep instanceof Integer[]) {
222 Integer[] a = (Integer[]) rep;
223 if (a.length == 3) {
224 int min = a[0];
225 int max = a[1];
226 int progress = a[2];
227
228 if (min >= 0 && min <= max) {
229 pg.setMinMax(min, max);
230 pg.setProgress(progress);
231
232 return true;
233 }
234 }
74a40dfb 235 }
b9ce9cad
NR
236
237 return false;
74a40dfb
NR
238 }
239
b9ce9cad
NR
240 /**
241 * Create a {@link Progress} that will forward its progress over the
242 * network.
243 *
244 * @param action
245 * the {@link ConnectActionServerObject} to use to forward it
246 *
247 * @return the {@link Progress}
248 */
249 private static Progress createPgForwarder(
250 final ConnectActionServerObject action) {
251 final Progress pg = new Progress();
252 final Integer[] p = new Integer[] { -1, -1, -1 };
253 pg.addProgressListener(new ProgressListener() {
254 @Override
255 public void progress(Progress progress, String name) {
256 int min = pg.getMin();
257 int max = pg.getMax();
258 int relativeProgress = min
259 + (int) Math.round(pg.getRelativeProgress()
260 * (max - min));
261
262 // Do not re-send the same value twice over the wire
263 if (p[0] != min || p[1] != max || p[2] != relativeProgress) {
264 p[0] = min;
265 p[1] = max;
266 p[2] = relativeProgress;
267
268 try {
269 action.send(new Integer[] { min, max, relativeProgress });
270 action.rec();
271 } catch (Exception e) {
272 Instance.getTraceHandler().error(e);
273 }
274 }
275 }
276 });
277
278 return pg;
74a40dfb 279 }
b0e88ebd 280}