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