time in log from remote server
[nikiroo-utils.git] / src / be / nikiroo / fanfix / library / RemoteLibrary.java
CommitLineData
e42573a0 1package be.nikiroo.fanfix.library;
b0e88ebd
NR
2
3import java.io.File;
4import java.io.IOException;
edf79e5e 5import java.net.URL;
e6249b0f 6import java.net.UnknownHostException;
68e2c6d2
NR
7import java.util.ArrayList;
8import java.util.List;
b0e88ebd 9
7e51d91c
NR
10import javax.net.ssl.SSLException;
11
e42573a0 12import be.nikiroo.fanfix.Instance;
b0e88ebd
NR
13import be.nikiroo.fanfix.data.MetaData;
14import be.nikiroo.fanfix.data.Story;
16a81ef7 15import be.nikiroo.utils.Image;
b0e88ebd 16import be.nikiroo.utils.Progress;
fb25273c 17import be.nikiroo.utils.Version;
62c63b07 18import be.nikiroo.utils.serial.server.ConnectActionClientObject;
b0e88ebd 19
68e2c6d2
NR
20/**
21 * This {@link BasicLibrary} will access a remote server to list the available
a85e8077 22 * stories, and download the ones you try to load to the local directory
68e2c6d2
NR
23 * specified in the configuration.
24 *
25 * @author niki
26 */
27public class RemoteLibrary extends BasicLibrary {
5db598bc
NR
28 interface RemoteAction {
29 public void action(ConnectActionClientObject action) throws Exception;
30 }
31
32 class RemoteConnectAction extends ConnectActionClientObject {
33 public RemoteConnectAction() throws IOException {
34 super(host, port, key);
35 }
36
37 @Override
38 public Object send(Object data) throws IOException,
39 NoSuchFieldException, NoSuchMethodException,
40 ClassNotFoundException {
41 Object rep = super.send(data);
42 if (rep instanceof RemoteLibraryException) {
43 RemoteLibraryException remoteEx = (RemoteLibraryException) rep;
44 IOException cause = remoteEx.getCause();
45 if (cause == null) {
46 cause = new IOException("IOException");
47 }
48
49 throw cause;
50 }
51
52 return rep;
53 }
54 }
55
b0e88ebd
NR
56 private String host;
57 private int port;
ea734ab4 58 private final String key;
fb25273c
NR
59 private final String subkey;
60
61 // informative only (server will make the actual checks)
62 private boolean rw;
68e2c6d2 63
99206a39
NR
64 // TODO: error handling is not up to par!
65
68e2c6d2
NR
66 /**
67 * Create a {@link RemoteLibrary} linked to the given server.
fb25273c
NR
68 * <p>
69 * Note that the key is structured:
70 * <tt><b><i>xxx</i></b>(|<b><i>yyy</i></b>|<b>wl</b>)(|<b>rw</b>)</tt>
71 * <p>
72 * Note that anything before the first pipe (<tt>|</tt>) character is
73 * considered to be the encryption key, anything after that character is
74 * called the subkey (including the other pipe characters and flags!).
75 * <p>
76 * This is important because the subkey (including the pipe characters and
77 * flags) must be present as-is in the server configuration file to be
78 * allowed.
79 * <ul>
80 * <li><b><i>xxx</i></b>: the encryption key used to communicate with the
81 * server</li>
82 * <li><b><i>yyy</i></b>: the secondary key</li>
83 * <li><b>rw</b>: flag to allow read and write access if it is not the
84 * default on this server</li>
85 * <li><b>wl</b>: flag to allow access to all the stories (bypassing the
86 * whitelist if it exists)</li>
87 * </ul>
88 *
89 * Some examples:
90 * <ul>
91 * <li><b>my_key</b>: normal connection, will take the default server
92 * options</li>
93 * <li><b>my_key|agzyzz|wl</b>: will ask to bypass the white list (if it
94 * exists)</li>
95 * <li><b>my_key|agzyzz|rw</b>: will ask read-write access (if the default
96 * is read-only)</li>
97 * <li><b>my_key|agzyzz|wl|rw</b>: will ask both read-write access and white
98 * list bypass</li>
99 * </ul>
68e2c6d2 100 *
2070ced5
NR
101 * @param key
102 * the key that will allow us to exchange information with the
103 * server
68e2c6d2
NR
104 * @param host
105 * the host to contact or NULL for localhost
106 * @param port
107 * the port to contact it on
108 */
2070ced5 109 public RemoteLibrary(String key, String host, int port) {
fb25273c
NR
110 int index = -1;
111 if (key != null) {
651072f3 112 index = key.indexOf('|');
fb25273c
NR
113 }
114
115 if (index >= 0) {
651072f3
NR
116 this.key = key.substring(0, index);
117 this.subkey = key.substring(index + 1);
fb25273c
NR
118 } else {
119 this.key = key;
120 this.subkey = "";
121 }
122
b0e88ebd
NR
123 this.host = host;
124 this.port = port;
b0e88ebd
NR
125 }
126
99ccbdf6
NR
127 @Override
128 public String getLibraryName() {
129 return host + ":" + port;
130 }
131
e6249b0f
NR
132 @Override
133 public Status getStatus() {
99206a39
NR
134 Instance.getTraceHandler().trace("Getting remote lib status...");
135 Status status = getStatusDo();
136 Instance.getTraceHandler().trace("Remote lib status: " + status);
137 return status;
138 }
139
99206a39 140 private Status getStatusDo() {
e6249b0f
NR
141 final Status[] result = new Status[1];
142
143 result[0] = Status.INVALID;
144
e6249b0f 145 try {
5db598bc 146 new RemoteConnectAction() {
e6249b0f 147 @Override
fb25273c
NR
148 public void action(Version serverVersion) throws Exception {
149 Object rep = send(new Object[] { subkey, "PING" });
ea734ab4 150
fb25273c
NR
151 if ("r/w".equals(rep)) {
152 rw = true;
153 result[0] = Status.READY;
154 } else if ("r/o".equals(rep)) {
155 rw = false;
7e51d91c
NR
156 result[0] = Status.READY;
157 } else {
99206a39 158 result[0] = Status.UNAUTHORIZED;
e6249b0f
NR
159 }
160 }
161
162 @Override
163 protected void onError(Exception e) {
210465c3
NR
164 if (e instanceof SSLException) {
165 result[0] = Status.UNAUTHORIZED;
166 } else {
167 result[0] = Status.UNAVAILABLE;
168 }
e6249b0f 169 }
ea734ab4 170 }.connect();
e6249b0f
NR
171 } catch (UnknownHostException e) {
172 result[0] = Status.INVALID;
173 } catch (IllegalArgumentException e) {
174 result[0] = Status.INVALID;
175 } catch (Exception e) {
176 result[0] = Status.UNAVAILABLE;
177 }
178
e6249b0f
NR
179 return result[0];
180 }
181
b0e88ebd 182 @Override
16a81ef7
NR
183 public Image getCover(final String luid) {
184 final Image[] result = new Image[1];
b0e88ebd 185
5db598bc
NR
186 connectRemoteAction(new RemoteAction() {
187 @Override
188 public void action(ConnectActionClientObject action)
189 throws Exception {
190 Object rep = action.send(new Object[] { subkey, "GET_COVER",
191 luid });
192 result[0] = (Image) rep;
193 }
194 });
b0e88ebd 195
b9ce9cad 196 return result[0];
085a2f9a
NR
197 }
198
199 @Override
e1de8087 200 public Image getCustomSourceCover(final String source) {
3989dfc5
NR
201 return getCustomCover(source, "SOURCE");
202 }
203
204 @Override
205 public Image getCustomAuthorCover(final String author) {
206 return getCustomCover(author, "AUTHOR");
207 }
208
209 // type: "SOURCE" or "AUTHOR"
210 private Image getCustomCover(final String source, final String type) {
16a81ef7 211 final Image[] result = new Image[1];
b9ce9cad 212
5db598bc
NR
213 connectRemoteAction(new RemoteAction() {
214 @Override
215 public void action(ConnectActionClientObject action)
216 throws Exception {
217 Object rep = action.send(new Object[] { subkey,
218 "GET_CUSTOM_COVER", type, source });
219 result[0] = (Image) rep;
220 }
221 });
b9ce9cad
NR
222
223 return result[0];
b0e88ebd 224 }
68e2c6d2
NR
225
226 @Override
ff05b828 227 public synchronized Story getStory(final String luid, Progress pg) {
b9ce9cad
NR
228 final Progress pgF = pg;
229 final Story[] result = new Story[1];
68e2c6d2 230
5db598bc
NR
231 connectRemoteAction(new RemoteAction() {
232 @Override
233 public void action(ConnectActionClientObject action)
234 throws Exception {
235 Progress pg = pgF;
236 if (pg == null) {
237 pg = new Progress();
238 }
b9ce9cad 239
5db598bc
NR
240 Object rep = action.send(new Object[] { subkey, "GET_STORY",
241 luid });
b9ce9cad 242
5db598bc
NR
243 MetaData meta = null;
244 if (rep instanceof MetaData) {
245 meta = (MetaData) rep;
246 if (meta.getWords() <= Integer.MAX_VALUE) {
247 pg.setMinMax(0, (int) meta.getWords());
b9ce9cad 248 }
b9ce9cad
NR
249 }
250
5db598bc
NR
251 List<Object> list = new ArrayList<Object>();
252 for (Object obj = action.send(null); obj != null; obj = action
253 .send(null)) {
254 list.add(obj);
255 pg.add(1);
b9ce9cad 256 }
5db598bc
NR
257
258 result[0] = RemoteLibraryServer.rebuildStory(list);
259 pg.done();
260 }
261 });
b9ce9cad
NR
262
263 return result[0];
68e2c6d2
NR
264 }
265
266 @Override
b9ce9cad
NR
267 public synchronized Story save(final Story story, final String luid,
268 Progress pg) throws IOException {
99206a39 269
0fa0fe95
NR
270 final String[] luidSaved = new String[1];
271 Progress pgSave = new Progress();
272 Progress pgRefresh = new Progress();
273 if (pg == null) {
274 pg = new Progress();
275 }
276
277 pg.setMinMax(0, 10);
278 pg.addProgress(pgSave, 9);
279 pg.addProgress(pgRefresh, 1);
280
281 final Progress pgF = pgSave;
b9ce9cad 282
5db598bc 283 connectRemoteAction(new RemoteAction() {
b9ce9cad 284 @Override
5db598bc
NR
285 public void action(ConnectActionClientObject action)
286 throws Exception {
b9ce9cad 287 Progress pg = pgF;
b9ce9cad
NR
288 if (story.getMeta().getWords() <= Integer.MAX_VALUE) {
289 pg.setMinMax(0, (int) story.getMeta().getWords());
290 }
291
5db598bc 292 action.send(new Object[] { subkey, "SAVE_STORY", luid });
b9ce9cad
NR
293
294 List<Object> list = RemoteLibraryServer.breakStory(story);
295 for (Object obj : list) {
5db598bc 296 action.send(obj);
b9ce9cad
NR
297 pg.add(1);
298 }
299
5db598bc 300 luidSaved[0] = (String) action.send(null);
0fa0fe95 301
b9ce9cad
NR
302 pg.done();
303 }
5db598bc 304 });
085a2f9a
NR
305
306 // because the meta changed:
edf79e5e 307 MetaData meta = getInfo(luidSaved[0]);
efa3c511
NR
308 if (story.getMeta().getClass() != null) {
309 // If already available locally:
310 meta.setCover(story.getMeta().getCover());
311 } else {
312 // If required:
313 meta.setCover(getCover(meta.getLuid()));
314 }
edf79e5e 315 story.setMeta(meta);
0fa0fe95
NR
316
317 pg.done();
085a2f9a
NR
318
319 return story;
68e2c6d2
NR
320 }
321
322 @Override
b9ce9cad 323 public synchronized void delete(final String luid) throws IOException {
5db598bc 324 connectRemoteAction(new RemoteAction() {
b9ce9cad 325 @Override
5db598bc
NR
326 public void action(ConnectActionClientObject action)
327 throws Exception {
328 action.send(new Object[] { subkey, "DELETE_STORY", luid });
b9ce9cad 329 }
5db598bc 330 });
68e2c6d2
NR
331 }
332
333 @Override
b9ce9cad 334 public void setSourceCover(final String source, final String luid) {
3989dfc5
NR
335 setCover(source, luid, "SOURCE");
336 }
337
338 @Override
339 public void setAuthorCover(final String author, final String luid) {
340 setCover(author, luid, "AUTHOR");
341 }
342
343 // type = "SOURCE" | "AUTHOR"
344 private void setCover(final String value, final String luid,
345 final String type) {
5db598bc
NR
346 connectRemoteAction(new RemoteAction() {
347 @Override
348 public void action(ConnectActionClientObject action)
349 throws Exception {
350 action.send(new Object[] { subkey, "SET_COVER", type, value,
351 luid });
352 }
353 });
edf79e5e
NR
354 }
355
356 @Override
357 // Could work (more slowly) without it
358 public Story imprt(final URL url, Progress pg) throws IOException {
00f6344a
NR
359 // Import the file locally if it is actually a file
360 if (url == null || url.getProtocol().equalsIgnoreCase("file")) {
361 return super.imprt(url, pg);
362 }
363
364 // Import it remotely if it is an URL
365
edf79e5e
NR
366 if (pg == null) {
367 pg = new Progress();
368 }
369
370 pg.setMinMax(0, 2);
371 Progress pgImprt = new Progress();
372 Progress pgGet = new Progress();
373 pg.addProgress(pgImprt, 1);
374 pg.addProgress(pgGet, 1);
375
376 final Progress pgF = pgImprt;
377 final String[] luid = new String[1];
378
5db598bc
NR
379 connectRemoteAction(new RemoteAction() {
380 @Override
381 public void action(ConnectActionClientObject action)
382 throws Exception {
383 Progress pg = pgF;
edf79e5e 384
5db598bc
NR
385 Object rep = action.send(new Object[] { subkey, "IMPORT",
386 url.toString() });
edf79e5e 387
5db598bc
NR
388 while (true) {
389 if (!RemoteLibraryServer.updateProgress(pg, rep)) {
390 break;
edf79e5e
NR
391 }
392
5db598bc 393 rep = action.send(null);
edf79e5e
NR
394 }
395
5db598bc
NR
396 pg.done();
397 luid[0] = (String) rep;
398 }
399 });
edf79e5e
NR
400
401 if (luid[0] == null) {
402 throw new IOException("Remote failure");
403 }
404
405 Story story = getStory(luid[0], pgGet);
406 pgGet.done();
407
408 pg.done();
409 return story;
410 }
411
412 @Override
413 // Could work (more slowly) without it
c8d48938
NR
414 protected synchronized void changeSTA(final String luid,
415 final String newSource, final String newTitle,
416 final String newAuthor, Progress pg) throws IOException {
99206a39 417
edf79e5e
NR
418 final Progress pgF = pg == null ? new Progress() : pg;
419
5db598bc
NR
420 connectRemoteAction(new RemoteAction() {
421 @Override
422 public void action(ConnectActionClientObject action)
423 throws Exception {
424 Progress pg = pgF;
edf79e5e 425
5db598bc
NR
426 Object rep = action.send(new Object[] { subkey, "CHANGE_STA",
427 luid, newSource, newTitle, newAuthor });
428 while (true) {
429 if (!RemoteLibraryServer.updateProgress(pg, rep)) {
430 break;
edf79e5e 431 }
edf79e5e 432
5db598bc 433 rep = action.send(null);
edf79e5e 434 }
5db598bc
NR
435 }
436 });
68e2c6d2
NR
437 }
438
ff05b828 439 @Override
2249988a 440 public synchronized File getFile(final String luid, Progress pg) {
ff05b828
NR
441 throw new java.lang.InternalError(
442 "Operation not supportorted on remote Libraries");
443 }
444
468b960b
NR
445 /**
446 * Stop the server.
447 */
448 public void exit() {
5db598bc
NR
449 connectRemoteAction(new RemoteAction() {
450 @Override
451 public void action(ConnectActionClientObject action)
452 throws Exception {
453 action.send(new Object[] { subkey, "EXIT" });
454 }
455 });
468b960b
NR
456 }
457
e272f05f
NR
458 @Override
459 public synchronized MetaData getInfo(String luid) {
460 List<MetaData> metas = getMetasList(luid, null);
461 if (!metas.isEmpty()) {
462 return metas.get(0);
463 }
464
465 return null;
466 }
467
14b57448 468 @Override
b9ce9cad 469 protected List<MetaData> getMetas(Progress pg) {
e272f05f
NR
470 return getMetasList("*", pg);
471 }
472
473 @Override
efa3c511
NR
474 protected void updateInfo(MetaData meta) {
475 // Will be taken care of directly server side
476 }
477
478 @Override
c8d48938 479 protected void invalidateInfo(String luid) {
efa3c511 480 // Will be taken care of directly server side
e272f05f
NR
481 }
482
483 // The following methods are only used by Save and Delete in BasicLibrary:
484
485 @Override
486 protected int getNextId() {
487 throw new java.lang.InternalError("Should not have been called");
488 }
489
490 @Override
491 protected void doDelete(String luid) throws IOException {
492 throw new java.lang.InternalError("Should not have been called");
493 }
494
495 @Override
496 protected Story doSave(Story story, Progress pg) throws IOException {
497 throw new java.lang.InternalError("Should not have been called");
498 }
499
500 //
501
502 /**
503 * Return the meta of the given story or a list of all known metas if the
504 * luid is "*".
9f51d8ab
NR
505 * <p>
506 * Will not get the covers.
e272f05f
NR
507 *
508 * @param luid
509 * the luid of the story or *
510 * @param pg
511 * the optional progress
512 *
513 *
514 * @return the metas
515 */
516 private List<MetaData> getMetasList(final String luid, Progress pg) {
b9ce9cad
NR
517 final Progress pgF = pg;
518 final List<MetaData> metas = new ArrayList<MetaData>();
74a40dfb 519
5db598bc
NR
520 connectRemoteAction(new RemoteAction() {
521 @Override
522 public void action(ConnectActionClientObject action)
523 throws Exception {
524 Progress pg = pgF;
525 if (pg == null) {
526 pg = new Progress();
527 }
74a40dfb 528
5db598bc
NR
529 Object rep = action.send(new Object[] { subkey, "GET_METADATA",
530 luid });
74a40dfb 531
5db598bc
NR
532 while (true) {
533 if (!RemoteLibraryServer.updateProgress(pg, rep)) {
534 break;
ff05b828 535 }
851dd538 536
5db598bc
NR
537 rep = action.send(null);
538 }
539
540 if (rep instanceof MetaData[]) {
541 for (MetaData meta : (MetaData[]) rep) {
542 metas.add(meta);
b9ce9cad 543 }
5db598bc
NR
544 } else if (rep != null) {
545 metas.add((MetaData) rep);
546 }
547 }
548 });
549
550 return metas;
551 }
552
553 private void connectRemoteAction(final RemoteAction runAction) {
554 try {
555 final RemoteConnectAction[] array = new RemoteConnectAction[1];
556 RemoteConnectAction ra = new RemoteConnectAction() {
557 @Override
558 public void action(Version serverVersion) throws Exception {
559 runAction.action(array[0]);
851dd538
NR
560 }
561
562 @Override
563 protected void onError(Exception e) {
7e51d91c
NR
564 if (e instanceof SSLException) {
565 Instance.getTraceHandler().error(
566 "Connection refused (bad key)");
567 } else {
568 Instance.getTraceHandler().error(e);
569 }
ff05b828 570 }
5db598bc
NR
571 };
572 array[0] = ra;
573 ra.connect();
ff05b828 574 } catch (Exception e) {
62c63b07 575 Instance.getTraceHandler().error(e);
ff05b828 576 }
b9ce9cad 577 }
b0e88ebd 578}