update from master
[fanfix.git] / Main.java
CommitLineData
08fe2e33
NR
1package be.nikiroo.fanfix;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import java.net.URL;
91b82a5c 7import java.util.ArrayList;
f569d249 8import java.util.List;
08fe2e33 9
0bb51c9c
NR
10import javax.net.ssl.SSLException;
11
fb25273c 12import be.nikiroo.fanfix.bundles.Config;
08fe2e33
NR
13import be.nikiroo.fanfix.bundles.StringId;
14import be.nikiroo.fanfix.data.Chapter;
b6b65795 15import be.nikiroo.fanfix.data.MetaData;
08fe2e33 16import be.nikiroo.fanfix.data.Story;
ff05b828
NR
17import be.nikiroo.fanfix.library.BasicLibrary;
18import be.nikiroo.fanfix.library.CacheLibrary;
e42573a0
NR
19import be.nikiroo.fanfix.library.LocalLibrary;
20import be.nikiroo.fanfix.library.RemoteLibrary;
21import be.nikiroo.fanfix.library.RemoteLibraryServer;
6d465e88 22import be.nikiroo.fanfix.library.WebLibrary;
f433d153 23import be.nikiroo.fanfix.library.WebLibraryServer;
08fe2e33
NR
24import be.nikiroo.fanfix.output.BasicOutput;
25import be.nikiroo.fanfix.output.BasicOutput.OutputType;
3727aae2 26import be.nikiroo.fanfix.reader.BasicReader;
9b75402f 27import be.nikiroo.fanfix.reader.CliReader;
91b82a5c 28import be.nikiroo.fanfix.searchable.BasicSearchable;
08fe2e33 29import be.nikiroo.fanfix.supported.BasicSupport;
0ffa4754 30import be.nikiroo.fanfix.supported.SupportType;
3b2b638f 31import be.nikiroo.utils.Progress;
39c3c689 32import be.nikiroo.utils.Version;
bb0c30ac 33import be.nikiroo.utils.VersionCheck;
08fe2e33
NR
34
35/**
36 * Main program entry point.
37 *
38 * @author niki
39 */
40public class Main {
d0114000 41 private enum MainAction {
9b75402f 42 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, START, VERSION, SERVER, STOP_SERVER, REMOTE, SET_SOURCE, SET_TITLE, SET_AUTHOR, SEARCH, SEARCH_TAG
d0114000
NR
43 }
44
08fe2e33
NR
45 /**
46 * Main program entry point.
47 * <p>
48 * Known environment variables:
49 * <ul>
d0114000 50 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
08fe2e33
NR
51 * {@link String}s when possible</li>
52 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
edd46289
NR
53 * before taking the usual ones; they will also be saved/updated into this
54 * path when the program starts</li>
d0114000
NR
55 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
56 * configuration value with 'true'</li>
57 * </ul>
58 * <p>
59 * <ul>
60 * <li>--import [URL]: import into library</li>
61 * <li>--export [id] [output_type] [target]: export story to target</li>
62 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
63 * target</li>
64 * <li>--read [id] ([chapter number]): read the given story from the library
65 * </li>
333f0e7b 66 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
d0114000 67 * story, without saving it</li>
8b153400
NR
68 * <li>--search: list the supported websites (where)</li>
69 * <li>--search [where] [keywords] (page [page]) (item [item]): search on
70 * the supported website and display the given results page of stories it
71 * found, or the story details if asked</li>
8141d7ac
NR
72 * <li>--search-tag [where]: list all the tags supported by this website</li>
73 * <li>--search-tag [index 1]... (page [page]) (item [item]): search for the
74 * given stories or subtags, tag by tag, and display information about a
75 * specific page of results or about a specific item if requested</li>
333f0e7b 76 * <li>--list ([type]): list the stories present in the library</li>
e10b51a2
NR
77 * <li>--set-source [id] [new source]: change the source of the given story</li>
78 * <li>--set-title [id] [new title]: change the title of the given story</li>
79 * <li>--set-author [id] [new author]: change the author of the given story</li>
39c3c689 80 * <li>--version: get the version of the program</li>
fb25273c
NR
81 * <li>--server: start the server mode (see config file for parameters)</li>
82 * <li>--stop-server: stop the running server on this port if any</li>
f433d153 83 * <li>--remote [key] [host] [port]: use the given remote library</li>
08fe2e33
NR
84 * </ul>
85 *
86 * @param args
d0114000 87 * see method description
08fe2e33
NR
88 */
89 public static void main(String[] args) {
9a553563
NR
90 new Main().start(args);
91 }
92
93 /**
94 * Start the default handling for the application.
95 * <p>
96 * If specific actions were asked (with correct parameters), they will be
97 * forwarded to the different protected methods that you can override.
98 * <p>
99 * At the end of the method, {@link Main#exit(int)} will be called; by
100 * default, it calls {@link System#exit(int)} if the status is not 0.
101 *
102 * @param args
103 * the arguments received from the system
104 */
105 public void start(String [] args) {
ee9b7083
NR
106 // Only one line, but very important:
107 Instance.init();
108
d0114000
NR
109 String urlString = null;
110 String luid = null;
b0e88ebd 111 String sourceString = null;
e10b51a2
NR
112 String titleString = null;
113 String authorString = null;
d0114000
NR
114 String chapString = null;
115 String target = null;
2070ced5 116 String key = null;
333f0e7b 117 MainAction action = MainAction.START;
d0114000 118 Boolean plusInfo = null;
b0e88ebd
NR
119 String host = null;
120 Integer port = null;
91b82a5c
NR
121 SupportType searchOn = null;
122 String search = null;
8b153400 123 List<Integer> tags = new ArrayList<Integer>();
91b82a5c
NR
124 Integer page = null;
125 Integer item = null;
73ce17ef 126
d0114000
NR
127 boolean noMoreActions = false;
128
129 int exitCode = 0;
130 for (int i = 0; exitCode == 0 && i < args.length; i++) {
59f1f1bf
NR
131 if (args[i] == null)
132 continue;
133
d0114000
NR
134 // Action (--) handling:
135 if (!noMoreActions && args[i].startsWith("--")) {
136 if (args[i].equals("--")) {
137 noMoreActions = true;
138 } else {
139 try {
140 action = MainAction.valueOf(args[i].substring(2)
141 .toUpperCase().replace("-", "_"));
142 } catch (Exception e) {
d66deb8d
NR
143 Instance.getInstance().getTraceHandler()
144 .error(new IllegalArgumentException("Unknown action: " + args[i], e));
d0114000
NR
145 exitCode = 255;
146 }
147 }
08fe2e33 148
d0114000
NR
149 continue;
150 }
151
152 switch (action) {
153 case IMPORT:
154 if (urlString == null) {
155 urlString = args[i];
156 } else {
157 exitCode = 255;
158 }
159 break;
160 case EXPORT:
161 if (luid == null) {
162 luid = args[i];
b0e88ebd
NR
163 } else if (sourceString == null) {
164 sourceString = args[i];
d0114000
NR
165 } else if (target == null) {
166 target = args[i];
167 } else {
168 exitCode = 255;
169 }
170 break;
171 case CONVERT:
172 if (urlString == null) {
173 urlString = args[i];
b0e88ebd
NR
174 } else if (sourceString == null) {
175 sourceString = args[i];
d0114000
NR
176 } else if (target == null) {
177 target = args[i];
178 } else if (plusInfo == null) {
179 if ("+info".equals(args[i])) {
180 plusInfo = true;
181 } else {
182 exitCode = 255;
183 }
184 } else {
185 exitCode = 255;
08fe2e33 186 }
d0114000
NR
187 break;
188 case LIST:
b0e88ebd
NR
189 if (sourceString == null) {
190 sourceString = args[i];
d0114000
NR
191 } else {
192 exitCode = 255;
08fe2e33 193 }
d0114000 194 break;
e10b51a2
NR
195 case SET_SOURCE:
196 if (luid == null) {
197 luid = args[i];
198 } else if (sourceString == null) {
199 sourceString = args[i];
200 } else {
201 exitCode = 255;
202 }
203 break;
204 case SET_TITLE:
205 if (luid == null) {
206 luid = args[i];
207 } else if (sourceString == null) {
208 titleString = args[i];
209 } else {
210 exitCode = 255;
211 }
212 break;
213 case SET_AUTHOR:
214 if (luid == null) {
215 luid = args[i];
216 } else if (sourceString == null) {
217 authorString = args[i];
218 } else {
219 exitCode = 255;
220 }
221 break;
d0114000
NR
222 case READ:
223 if (luid == null) {
224 luid = args[i];
225 } else if (chapString == null) {
226 chapString = args[i];
227 } else {
228 exitCode = 255;
08fe2e33 229 }
d0114000
NR
230 break;
231 case READ_URL:
232 if (urlString == null) {
233 urlString = args[i];
234 } else if (chapString == null) {
235 chapString = args[i];
236 } else {
237 exitCode = 255;
08fe2e33 238 }
d0114000 239 break;
91b82a5c
NR
240 case SEARCH:
241 if (searchOn == null) {
242 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 243
91b82a5c 244 if (searchOn == null) {
d66deb8d 245 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
b31a0db0
NR
246 exitCode = 41;
247 break;
91b82a5c 248 }
8b153400 249
91b82a5c 250 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 251 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
b31a0db0
NR
252 exitCode = 42;
253 break;
91b82a5c
NR
254 }
255 } else if (search == null) {
256 search = args[i];
8b153400 257 } else if (page != null && page == -1) {
91b82a5c
NR
258 try {
259 page = Integer.parseInt(args[i]);
8b153400
NR
260 } catch (Exception e) {
261 page = -2;
91b82a5c 262 }
8b153400 263 } else if (item != null && item == -1) {
91b82a5c
NR
264 try {
265 item = Integer.parseInt(args[i]);
8b153400
NR
266 } catch (Exception e) {
267 item = -2;
268 }
269 } else if (page == null || item == null) {
270 if (page == null && "page".equals(args[i])) {
271 page = -1;
272 } else if (item == null && "item".equals(args[i])) {
273 item = -1;
274 } else {
91b82a5c
NR
275 exitCode = 255;
276 }
277 } else {
278 exitCode = 255;
279 }
280 break;
8141d7ac 281 case SEARCH_TAG:
91b82a5c
NR
282 if (searchOn == null) {
283 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 284
91b82a5c 285 if (searchOn == null) {
d66deb8d 286 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
91b82a5c
NR
287 exitCode = 255;
288 }
8b153400 289
91b82a5c 290 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 291 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
91b82a5c
NR
292 exitCode = 255;
293 }
8b153400
NR
294 } else if (page == null && item == null) {
295 if ("page".equals(args[i])) {
296 page = -1;
297 } else if ("item".equals(args[i])) {
298 item = -1;
299 } else {
300 try {
301 int index = Integer.parseInt(args[i]);
302 tags.add(index);
303 } catch (NumberFormatException e) {
d66deb8d 304 Instance.getInstance().getTraceHandler().error("Invalid tag index: " + args[i]);
8b153400
NR
305 exitCode = 255;
306 }
307 }
308 } else if (page != null && page == -1) {
309 try {
310 page = Integer.parseInt(args[i]);
311 } catch (Exception e) {
312 page = -2;
313 }
314 } else if (item != null && item == -1) {
315 try {
316 item = Integer.parseInt(args[i]);
317 } catch (Exception e) {
318 item = -2;
319 }
320 } else if (page == null || item == null) {
321 if (page == null && "page".equals(args[i])) {
322 page = -1;
323 } else if (item == null && "item".equals(args[i])) {
324 item = -1;
325 } else {
326 exitCode = 255;
327 }
91b82a5c 328 } else {
8b153400 329 exitCode = 255;
91b82a5c
NR
330 }
331 break;
d0114000
NR
332 case HELP:
333 exitCode = 255;
334 break;
333f0e7b
NR
335 case START:
336 exitCode = 255; // not supposed to be selected by user
337 break;
39c3c689
NR
338 case VERSION:
339 exitCode = 255; // no arguments for this option
b0e88ebd
NR
340 break;
341 case SERVER:
fb25273c
NR
342 exitCode = 255; // no arguments for this option
343 break;
5e848e6a 344 case STOP_SERVER:
fb25273c 345 exitCode = 255; // no arguments for this option
b0e88ebd
NR
346 break;
347 case REMOTE:
2070ced5
NR
348 if (key == null) {
349 key = args[i];
350 } else if (host == null) {
b0e88ebd
NR
351 host = args[i];
352 } else if (port == null) {
353 port = Integer.parseInt(args[i]);
ff05b828 354
6d465e88
NR
355 BasicLibrary lib;
356 if (host.startsWith("http://")
357 || host.startsWith("https://")) {
358 lib = new WebLibrary(key, host, port);
359 } else {
360 lib = new RemoteLibrary(key, host, port);
361 }
362
9b75402f
NR
363 lib = new CacheLibrary(
364 Instance.getInstance().getRemoteDir(host), lib,
d66deb8d 365 Instance.getInstance().getUiConfig());
ff05b828 366
9b75402f 367 Instance.getInstance().setLibrary(lib);
5e848e6a 368
b0e88ebd
NR
369 action = MainAction.START;
370 } else {
371 exitCode = 255;
372 }
373 break;
d0114000
NR
374 }
375 }
376
92fb0719
NR
377 final Progress mainProgress = new Progress(0, 80);
378 mainProgress.addProgressListener(new Progress.ProgressListener() {
379 private int current = mainProgress.getMin();
380
211f7ddb 381 @Override
92fb0719
NR
382 public void progress(Progress progress, String name) {
383 int diff = progress.getProgress() - current;
384 current += diff;
385
1822d603
NR
386 if (diff <= 0)
387 return;
388
92fb0719
NR
389 StringBuilder builder = new StringBuilder();
390 for (int i = 0; i < diff; i++) {
391 builder.append('.');
392 }
393
394 System.err.print(builder.toString());
395
396 if (progress.isDone()) {
397 System.err.println("");
398 }
399 }
400 });
401 Progress pg = new Progress();
402 mainProgress.addProgress(pg, mainProgress.getMax());
403
9a553563 404 VersionCheck updates = checkUpdates();
b42117f1 405
b31a0db0 406 if (exitCode == 0) {
d0114000
NR
407 switch (action) {
408 case IMPORT:
bb0c30ac
NR
409 if (updates != null) {
410 // we consider it read
411 Instance.getInstance().setVersionChecked();
412 }
9a553563
NR
413
414 try {
415 exitCode = imprt(BasicReader.getUrl(urlString), pg);
416 } catch (MalformedURLException e) {
417 Instance.getInstance().getTraceHandler().error(e);
418 exitCode = 1;
419 }
420
d0114000
NR
421 break;
422 case EXPORT:
bb0c30ac
NR
423 if (updates != null) {
424 // we consider it read
425 Instance.getInstance().setVersionChecked();
426 }
9a553563
NR
427
428 OutputType exportType = OutputType.valueOfNullOkUC(sourceString, null);
429 if (exportType == null) {
430 Instance.getInstance().getTraceHandler().error(new Exception(trans(StringId.OUTPUT_DESC, sourceString)));
431 exitCode = 1;
432 break;
433 }
434
435 exitCode = export(luid, exportType, target, pg);
436
d0114000
NR
437 break;
438 case CONVERT:
bb0c30ac
NR
439 if (updates != null) {
440 // we consider it read
441 Instance.getInstance().setVersionChecked();
442 }
9a553563
NR
443
444 OutputType convertType = OutputType.valueOfAllOkUC(sourceString, null);
445 if (convertType == null) {
446 Instance.getInstance().getTraceHandler()
447 .error(new IOException(trans(StringId.ERR_BAD_OUTPUT_TYPE, sourceString)));
448
449 exitCode = 2;
450 break;
451 }
452
453 exitCode = convert(urlString, convertType, target,
92fb0719 454 plusInfo == null ? false : plusInfo, pg);
9a553563 455
d0114000
NR
456 break;
457 case LIST:
b0e88ebd 458 exitCode = list(sourceString);
d0114000 459 break;
e10b51a2
NR
460 case SET_SOURCE:
461 try {
d66deb8d 462 Instance.getInstance().getLibrary().changeSource(luid, sourceString, pg);
e10b51a2 463 } catch (IOException e1) {
d66deb8d 464 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
465 exitCode = 21;
466 }
467 break;
468 case SET_TITLE:
469 try {
d66deb8d 470 Instance.getInstance().getLibrary().changeTitle(luid, titleString, pg);
e10b51a2 471 } catch (IOException e1) {
d66deb8d 472 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
473 exitCode = 22;
474 }
475 break;
476 case SET_AUTHOR:
477 try {
d66deb8d 478 Instance.getInstance().getLibrary().changeAuthor(luid, authorString, pg);
e10b51a2 479 } catch (IOException e1) {
d66deb8d 480 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
481 exitCode = 23;
482 }
483 break;
d0114000 484 case READ:
9b75402f
NR
485 if (luid == null || luid.isEmpty()) {
486 syntax(false);
487 exitCode = 255;
99ccbdf6
NR
488 break;
489 }
9b75402f
NR
490
491 try {
9a553563
NR
492 Integer chap = null;
493 if (chapString != null) {
494 try {
495 chap = Integer.parseInt(chapString);
496 } catch (NumberFormatException e) {
497 Instance.getInstance().getTraceHandler().error(new IOException(
498 "Chapter number cannot be parsed: " + chapString, e));
499 exitCode = 2;
500 break;
501 }
502 }
503
9b75402f 504 BasicLibrary lib = Instance.getInstance().getLibrary();
9a553563 505 exitCode = read(lib.getStory(luid, null), chap);
9b75402f
NR
506 } catch (IOException e) {
507 Instance.getInstance().getTraceHandler()
508 .error(new IOException("Failed to read book", e));
509 exitCode = 2;
510 }
511
d0114000
NR
512 break;
513 case READ_URL:
9b75402f
NR
514 if (urlString == null || urlString.isEmpty()) {
515 syntax(false);
516 exitCode = 255;
99ccbdf6
NR
517 break;
518 }
9b75402f
NR
519
520 try {
9a553563
NR
521 Integer chap = null;
522 if (chapString != null) {
523 try {
524 chap = Integer.parseInt(chapString);
525 } catch (NumberFormatException e) {
526 Instance.getInstance().getTraceHandler().error(new IOException(
527 "Chapter number cannot be parsed: " + chapString, e));
528 exitCode = 2;
529 break;
530 }
531 }
532
9b75402f
NR
533 BasicSupport support = BasicSupport
534 .getSupport(BasicReader.getUrl(urlString));
535 if (support == null) {
536 Instance.getInstance().getTraceHandler()
537 .error("URL not supported: " + urlString);
538 exitCode = 2;
539 break;
540 }
541
9a553563 542 exitCode = read(support.process(null), chap);
9b75402f
NR
543 } catch (IOException e) {
544 Instance.getInstance().getTraceHandler()
545 .error(new IOException("Failed to read book", e));
546 exitCode = 2;
547 }
548
91b82a5c
NR
549 break;
550 case SEARCH:
8b153400
NR
551 page = page == null ? 1 : page;
552 if (page < 0) {
d66deb8d 553 Instance.getInstance().getTraceHandler().error("Incorrect page number");
91b82a5c
NR
554 exitCode = 255;
555 break;
556 }
8b153400
NR
557
558 item = item == null ? 0 : item;
559 if (item < 0) {
d66deb8d 560 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
561 exitCode = 255;
562 break;
91b82a5c 563 }
8b153400 564
9a553563
NR
565 if (searchOn == null) {
566 try {
567 search();
568 } catch (IOException e) {
569 Instance.getInstance().getTraceHandler().error(e);
570 exitCode = 1;
8b153400 571 }
9a553563
NR
572 } else if (search != null) {
573 try {
574 searchKeywords(searchOn, search, page, item);
575 } catch (IOException e) {
576 Instance.getInstance().getTraceHandler().error(e);
577 exitCode = 20;
578 }
579 } else {
580 exitCode = 255;
91b82a5c 581 }
8b153400 582
91b82a5c 583 break;
8141d7ac 584 case SEARCH_TAG:
91b82a5c
NR
585 if (searchOn == null) {
586 exitCode = 255;
587 break;
588 }
91b82a5c 589
8b153400
NR
590 page = page == null ? 1 : page;
591 if (page < 0) {
d66deb8d 592 Instance.getInstance().getTraceHandler().error("Incorrect page number");
8b153400
NR
593 exitCode = 255;
594 break;
91b82a5c 595 }
8b153400
NR
596
597 item = item == null ? 0 : item;
598 if (item < 0) {
d66deb8d 599 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
600 exitCode = 255;
601 break;
602 }
603
91b82a5c 604 try {
9a553563
NR
605 searchTags(searchOn, page, item,
606 tags.toArray(new Integer[] {}));
607 } catch (IOException e) {
608 Instance.getInstance().getTraceHandler().error(e);
91b82a5c 609 }
8b153400 610
d0114000
NR
611 break;
612 case HELP:
613 syntax(true);
614 exitCode = 0;
615 break;
39c3c689 616 case VERSION:
bb0c30ac
NR
617 if (updates != null) {
618 // we consider it read
619 Instance.getInstance().setVersionChecked();
620 }
9a553563 621
39c3c689
NR
622 System.out
623 .println(String.format("Fanfix version %s"
9fe3f177
NR
624 + "%nhttps://github.com/nikiroo/fanfix/"
625 + "%n\tWritten by Nikiroo",
39c3c689
NR
626 Version.getCurrentVersion()));
627 break;
333f0e7b 628 case START:
0bb51c9c 629 try {
9a553563 630 start();
0bb51c9c 631 } catch (IOException e) {
d66deb8d 632 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
633 exitCode = 66;
634 }
b0e88ebd
NR
635 break;
636 case SERVER:
b0e88ebd 637 try {
f433d153 638 startServer();
b0e88ebd 639 } catch (IOException e) {
d66deb8d 640 Instance.getInstance().getTraceHandler().error(e);
b0e88ebd 641 }
9a553563
NR
642
643 break;
5e848e6a 644 case STOP_SERVER:
aad0e5ae 645 // Can be given via "--remote XX XX XX"
002972e9
NR
646 if (key == null) {
647 key = Instance.getInstance().getConfig()
648 .getString(Config.SERVER_KEY);
649
650 // If a subkey in RW mode exists, use it
651 for (String subkey : Instance.getInstance().getConfig()
652 .getList(Config.SERVER_ALLOWED_SUBKEYS,
653 new ArrayList<String>())) {
654 if ((subkey + "|").contains("|rw|")) {
655 key = key + "|" + subkey;
656 break;
657 }
658 }
659 }
660
661 if (port == null) {
d66deb8d 662 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
002972e9
NR
663 }
664
665 if (host == null) {
666 String mode = Instance.getInstance().getConfig()
667 .getString(Config.SERVER_MODE, "fanfix");
668 if ("http".equals(mode)) {
669 host = "http://localhost";
670 } else if ("https".equals(mode)) {
671 host = "https://localhost";
672 } else if ("fanfix".equals(mode)) {
673 host = "fanfix://localhost";
674 }
675 }
aad0e5ae 676
5e848e6a 677 if (port == null) {
aad0e5ae 678 System.err.println("No port given nor configured in the config file");
fb25273c 679 exitCode = 15;
5e848e6a
NR
680 break;
681 }
0bb51c9c 682 try {
9a553563 683 stopServer(key, host, port);
0bb51c9c 684 } catch (SSLException e) {
d66deb8d 685 Instance.getInstance().getTraceHandler().error(
0bb51c9c
NR
686 "Bad access key for remote library");
687 exitCode = 43;
688 } catch (IOException e) {
d66deb8d 689 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
690 exitCode = 44;
691 }
5e848e6a 692
5e848e6a 693 break;
b0e88ebd 694 case REMOTE:
99ccbdf6 695 exitCode = 255; // should not be reachable (REMOTE -> START)
333f0e7b 696 break;
08fe2e33
NR
697 }
698 }
699
350bc060 700 try {
d66deb8d 701 Instance.getInstance().getTempFiles().close();
350bc060 702 } catch (IOException e) {
9a553563
NR
703 Instance.getInstance().getTraceHandler().error(new IOException(
704 "Cannot dispose of the temporary files", e));
2aac79c7
NR
705 }
706
08fe2e33 707 if (exitCode == 255) {
d0114000 708 syntax(false);
08fe2e33
NR
709 }
710
9a553563
NR
711 exit(exitCode);
712 }
713
714 /**
715 * A normal invocation of the program (without parameters or at least
716 * without "action" parameters).
717 * <p>
718 * You will probably want to override that one if you offer a user
719 * interface.
720 *
721 * @throws IOException
722 * in case of I/O error
723 */
724 protected void start() throws IOException {
725 new CliReader().listBooks(null);
726 }
727
728 /**
98b95fb8 729 * Will check if updates are available, synchronously.
9a553563
NR
730 * <p>
731 * For this, it will simply forward the call to
732 * {@link Main#checkUpdates(String)} with a value of "nikiroo/fanfix".
98b95fb8
NR
733 * <p>
734 * You may want to override it so you call the forward method with the right
735 * parameters (or also if you want it to be asynchronous).
9a553563
NR
736 *
737 * @return the newer version information or NULL if nothing new
738 */
739 protected VersionCheck checkUpdates() {
740 return checkUpdates("nikiroo/fanfix");
741 }
742
743 /**
744 * Will check if updates are available on a specific GitHub project.
745 * <p>
746 * Will be called by {@link Main#checkUpdates()}, but if you override that
747 * one you mall call it with another project.
748 *
749 * @param githubProject
750 * the GitHub project, for instance "nikiroo/fanfix"
751 *
752 * @return the newer version information or NULL if nothing new
753 */
754 protected VersionCheck checkUpdates(String githubProject) {
bb0c30ac
NR
755 try {
756 VersionCheck updates = VersionCheck.check(githubProject,
757 Instance.getInstance().getTrans().getLocale());
758 if (updates.isNewVersionAvailable()) {
759 notifyUpdates(updates);
760 return updates;
761 }
762 } catch (IOException e) {
763 // Maybe no internet. Do not report any update.
9a553563 764 }
bb0c30ac 765
9a553563 766 return null;
08fe2e33
NR
767 }
768
9a553563
NR
769 /**
770 * Notify the user about available updates.
771 * <p>
772 * Will only be called when a version is available.
773 * <p>
bb0c30ac
NR
774 * Note that you can call {@link Instance#setVersionChecked()} on it if the
775 * user has read the information (by default, it is marked read only on
776 * certain other actions).
9a553563
NR
777 *
778 * @param updates
779 * the new version information
780 */
781 protected void notifyUpdates(VersionCheck updates) {
782 // Sent to syserr so not to cause problem if one tries to capture a
783 // story content in text mode
784 System.err.println(
785 "A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
786 System.err.println("");
787 for (Version v : updates.getNewer()) {
788 System.err.println("\tVersion " + v);
789 System.err.println("\t-------------");
790 System.err.println("");
791 for (String it : updates.getChanges().get(v)) {
792 System.err.println("\t- " + it);
793 }
794 System.err.println("");
795 }
796 }
797
08fe2e33 798 /**
68e2c6d2 799 * Import the given resource into the {@link LocalLibrary}.
08fe2e33 800 *
9a553563 801 * @param url
08fe2e33 802 * the resource to import
92fb0719
NR
803 * @param pg
804 * the optional progress reporter
08fe2e33
NR
805 *
806 * @return the exit return code (0 = success)
807 */
9a553563 808 protected static int imprt(URL url, Progress pg) {
08fe2e33 809 try {
9a553563 810 MetaData meta = Instance.getInstance().getLibrary().imprt(url, pg);
d66deb8d 811 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
08fe2e33 812 } catch (IOException e) {
d66deb8d 813 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
814 return 1;
815 }
816
817 return 0;
818 }
819
820 /**
68e2c6d2
NR
821 * Export the {@link Story} from the {@link LocalLibrary} to the given
822 * target.
08fe2e33 823 *
73ce17ef 824 * @param luid
08fe2e33 825 * the story LUID
9a553563 826 * @param type
08fe2e33
NR
827 * the {@link OutputType} to use
828 * @param target
829 * the target
92fb0719
NR
830 * @param pg
831 * the optional progress reporter
08fe2e33
NR
832 *
833 * @return the exit return code (0 = success)
834 */
9a553563 835 protected static int export(String luid, OutputType type, String target,
92fb0719 836 Progress pg) {
08fe2e33 837 try {
d66deb8d 838 Instance.getInstance().getLibrary().export(luid, type, target, pg);
08fe2e33 839 } catch (IOException e) {
d66deb8d 840 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
841 return 4;
842 }
843
844 return 0;
845 }
9a553563 846
08fe2e33 847 /**
68e2c6d2
NR
848 * List the stories of the given source from the {@link LocalLibrary}
849 * (unless NULL is passed, in which case all stories will be listed).
08fe2e33 850 *
b0e88ebd
NR
851 * @param source
852 * the source to list the known stories of, or NULL to list all
333f0e7b 853 * stories
08fe2e33
NR
854 *
855 * @return the exit return code (0 = success)
856 */
9a553563 857 protected int list(String source) {
0bb51c9c 858 try {
9b75402f 859 new CliReader().listBooks(source);
0bb51c9c 860 } catch (IOException e) {
d66deb8d 861 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c 862 return 66;
f569d249 863 }
0bb51c9c 864
08fe2e33
NR
865 return 0;
866 }
867
868 /**
350bc060 869 * Start the current reader for this {@link Story}.
08fe2e33
NR
870 *
871 * @param story
9b75402f 872 * the story to read
9a553563 873 * @param chap
08fe2e33
NR
874 * which {@link Chapter} to read (starting at 1), or NULL to get
875 * the {@link Story} description
08fe2e33
NR
876 *
877 * @return the exit return code (0 = success)
878 */
9a553563 879 protected int read(Story story, Integer chap) {
9b75402f
NR
880 if (story != null) {
881 try {
882 if (chap == null) {
883 new CliReader().listChapters(story);
884 } else {
885 new CliReader().printChapter(story, chap);
d0114000 886 }
9b75402f
NR
887 } catch (IOException e) {
888 Instance.getInstance().getTraceHandler()
889 .error(new IOException("Failed to read book", e));
890 return 2;
08fe2e33 891 }
9b75402f
NR
892 } else {
893 Instance.getInstance().getTraceHandler()
9a553563 894 .error("Cannot find book: " + story);
9b75402f 895 return 2;
08fe2e33
NR
896 }
897
898 return 0;
899 }
900
901 /**
902 * Convert the {@link Story} into another format.
903 *
d0114000 904 * @param urlString
08fe2e33 905 * the source {@link Story} to convert
9a553563 906 * @param type
08fe2e33 907 * the {@link OutputType} to convert to
d0114000 908 * @param target
08fe2e33
NR
909 * the target file
910 * @param infoCover
911 * TRUE to also export the cover and info file, even if the given
912 * {@link OutputType} does not usually save them
92fb0719
NR
913 * @param pg
914 * the optional progress reporter
08fe2e33
NR
915 *
916 * @return the exit return code (0 = success)
917 */
9a553563 918 protected int convert(String urlString, OutputType type,
92fb0719 919 String target, boolean infoCover, Progress pg) {
08fe2e33
NR
920 int exitCode = 0;
921
d66deb8d 922 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
d0114000 923 String sourceName = urlString;
08fe2e33 924 try {
3b2b638f 925 URL source = BasicReader.getUrl(urlString);
08fe2e33 926 sourceName = source.toString();
3ddb5591 927 if (sourceName.startsWith("file://")) {
08fe2e33
NR
928 sourceName = sourceName.substring("file://".length());
929 }
930
9a553563
NR
931 try {
932 BasicSupport support = BasicSupport.getSupport(source);
08fe2e33 933
9a553563
NR
934 if (support != null) {
935 Instance.getInstance().getTraceHandler()
936 .trace("Support found: " + support.getClass());
937 Progress pgIn = new Progress();
938 Progress pgOut = new Progress();
939 if (pg != null) {
940 pg.setMax(2);
941 pg.addProgress(pgIn, 1);
942 pg.addProgress(pgOut, 1);
943 }
08fe2e33 944
9a553563
NR
945 Story story = support.process(pgIn);
946 try {
947 target = new File(target).getAbsolutePath();
948 BasicOutput.getOutput(type, infoCover, infoCover)
949 .process(story, target, pgOut);
950 } catch (IOException e) {
d66deb8d 951 Instance.getInstance().getTraceHandler()
9a553563
NR
952 .error(new IOException(
953 trans(StringId.ERR_SAVING, target), e));
954 exitCode = 5;
08fe2e33 955 }
9a553563 956 } else {
d66deb8d 957 Instance.getInstance().getTraceHandler()
9a553563
NR
958 .error(new IOException(
959 trans(StringId.ERR_NOT_SUPPORTED, source)));
960
961 exitCode = 4;
08fe2e33 962 }
9a553563
NR
963 } catch (IOException e) {
964 Instance.getInstance().getTraceHandler().error(new IOException(
965 trans(StringId.ERR_LOADING, sourceName), e));
966 exitCode = 3;
08fe2e33
NR
967 }
968 } catch (MalformedURLException e) {
d66deb8d 969 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
08fe2e33
NR
970 exitCode = 1;
971 }
972
973 return exitCode;
974 }
975
08fe2e33 976 /**
d0114000
NR
977 * Display the correct syntax of the program to the user to stdout, or an
978 * error message if the syntax used was wrong on stderr.
979 *
980 * @param showHelp
981 * TRUE to show the syntax help, FALSE to show "syntax error"
08fe2e33 982 */
9a553563 983 protected void syntax(boolean showHelp) {
d0114000
NR
984 if (showHelp) {
985 StringBuilder builder = new StringBuilder();
986 for (SupportType type : SupportType.values()) {
987 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
988 type.getDesc()));
989 builder.append('\n');
990 }
08fe2e33 991
d0114000
NR
992 String typesIn = builder.toString();
993 builder.setLength(0);
08fe2e33 994
d0114000
NR
995 for (OutputType type : OutputType.values()) {
996 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
4d205683 997 type.getDesc(true)));
d0114000
NR
998 builder.append('\n');
999 }
08fe2e33 1000
d0114000 1001 String typesOut = builder.toString();
08fe2e33 1002
d0114000
NR
1003 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
1004 } else {
1005 System.err.println(trans(StringId.ERR_SYNTAX));
1006 }
1007 }
9a553563
NR
1008
1009 /**
1010 * Starts a search operation (i.e., list the available web sites we can
1011 * search on).
1012 *
1013 * @throws IOException
1014 * in case of I/O errors
1015 */
1016 protected void search() throws IOException {
1017 new CliReader().listSearchables();
1018 }
1019
1020 /**
1021 * Search for books by keywords on the given supported web site.
1022 *
1023 * @param searchOn
1024 * the web site to search on
1025 * @param search
1026 * the keyword to look for
1027 * @param page
1028 * the page of results to get, or 0 to inquire about the number
1029 * of pages
1030 * @param item
1031 * the index of the book we are interested by, or 0 to query
1032 * about how many books are in that page of results
1033 *
1034 * @throws IOException
1035 * in case of I/O error
1036 */
1037 protected void searchKeywords(SupportType searchOn, String search,
1038 int page, Integer item) throws IOException {
1039 new CliReader().searchBooksByKeyword(searchOn, search, page, item);
1040 }
1041
1042 /**
1043 * Search for books by tags on the given supported web site.
1044 *
1045 * @param searchOn
1046 * the web site to search on
1047 * @param page
1048 * the page of results to get, or 0 to inquire about the number
1049 * of pages
1050 * @param item
1051 * the index of the book we are interested by, or 0 to query
1052 * about how many books are in that page of results
1053 * @param tags
1054 * the tags to look for
1055 *
1056 * @throws IOException
1057 * in case of I/O error
1058 */
1059 protected void searchTags(SupportType searchOn, Integer page, Integer item,
1060 Integer[] tags) throws IOException {
1061 new CliReader().searchBooksByTag(searchOn, page, item, tags);
1062 }
1063
1064 /**
1065 * Start a Fanfix server.
1066 *
9a553563
NR
1067 * @throws IOException
1068 * in case of I/O errors
1069 * @throws SSLException
1070 * when the key was not accepted
1071 */
f433d153
NR
1072 private void startServer() throws IOException {
1073 String mode = Instance.getInstance().getConfig()
1074 .getString(Config.SERVER_MODE, "fanfix");
1075 if (mode.equals("fanfix")) {
1076 RemoteLibraryServer server = new RemoteLibraryServer();
1077 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1078 server.run();
1079 } else if (mode.equals("http")) {
1080 WebLibraryServer server = new WebLibraryServer(false);
1081 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1082 server.run();
1083 } else if (mode.equals("https")) {
1084 WebLibraryServer server = new WebLibraryServer(true);
1085 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1086 server.run();
1087 } else {
1088 throw new IOException("Unknown server mode: " + mode);
1089 }
9a553563
NR
1090 }
1091
1092 /**
1093 * Stop a running Fanfix server.
1094 *
1095 * @param key
1096 * the key to contact the Fanfix server
1097 * @param host
002972e9 1098 * the host on which it runs
9a553563
NR
1099 * @param port
1100 * the port on which it runs
1101 *
1102 * @throws IOException
1103 * in case of I/O errors
1104 * @throws SSLException
1105 * when the key was not accepted
1106 */
002972e9 1107 private void stopServer(String key, String host, int port)
9a553563 1108 throws IOException, SSLException {
6d465e88
NR
1109 if (host.startsWith("http://") || host.startsWith("https://")) {
1110 new WebLibrary(key, host, port).stop();
1111 } else {
1112 new RemoteLibrary(key, host, port).stop();
1113 }
9a553563
NR
1114 }
1115
1116 /**
1117 * We are done and ready to exit.
1118 * <p>
1119 * By default, it will call {@link System#exit(int)} if the status is not 0.
1120 *
1121 * @param status
1122 * the exit status
1123 */
1124 protected void exit(int status) {
1125 if (status != 0) {
1126 System.exit(status);
1127 }
1128 }
1129
1130 /**
1131 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
1132 *
1133 * @param id
1134 * the ID to translate
1135 *
1136 * @return the translated result
1137 */
1138 static private String trans(StringId id, Object... params) {
1139 return Instance.getInstance().getTrans().getString(id, params);
1140 }
08fe2e33 1141}