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