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