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