fix STOP server
[fanfix.git] / src / be / nikiroo / fanfix / Main.java
1 package be.nikiroo.fanfix;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.net.MalformedURLException;
6 import java.net.URL;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 import javax.net.ssl.SSLException;
11
12 import be.nikiroo.fanfix.bundles.Config;
13 import be.nikiroo.fanfix.bundles.StringId;
14 import be.nikiroo.fanfix.data.Chapter;
15 import be.nikiroo.fanfix.data.MetaData;
16 import be.nikiroo.fanfix.data.Story;
17 import be.nikiroo.fanfix.library.BasicLibrary;
18 import be.nikiroo.fanfix.library.CacheLibrary;
19 import be.nikiroo.fanfix.library.LocalLibrary;
20 import be.nikiroo.fanfix.library.RemoteLibrary;
21 import be.nikiroo.fanfix.library.RemoteLibraryServer;
22 import be.nikiroo.fanfix.library.WebLibrary;
23 import be.nikiroo.fanfix.library.WebLibraryServer;
24 import be.nikiroo.fanfix.output.BasicOutput;
25 import be.nikiroo.fanfix.output.BasicOutput.OutputType;
26 import be.nikiroo.fanfix.reader.BasicReader;
27 import be.nikiroo.fanfix.reader.CliReader;
28 import be.nikiroo.fanfix.searchable.BasicSearchable;
29 import be.nikiroo.fanfix.supported.BasicSupport;
30 import be.nikiroo.fanfix.supported.SupportType;
31 import be.nikiroo.utils.Progress;
32 import be.nikiroo.utils.Version;
33 import be.nikiroo.utils.VersionCheck;
34
35 /**
36 * Main program entry point.
37 *
38 * @author niki
39 */
40 public class Main {
41 private enum MainAction {
42 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, START, VERSION, SERVER, STOP_SERVER, REMOTE, SET_SOURCE, SET_TITLE, SET_AUTHOR, SEARCH, SEARCH_TAG
43 }
44
45 /**
46 * Main program entry point.
47 * <p>
48 * Known environment variables:
49 * <ul>
50 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
51 * {@link String}s when possible</li>
52 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
53 * before taking the usual ones; they will also be saved/updated into this
54 * path when the program starts</li>
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>
66 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
67 * story, without saving it</li>
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>
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>
76 * <li>--list ([type]): list the stories present in the library</li>
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>
80 * <li>--version: get the version of the program</li>
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>
83 * <li>--remote [key] [host] [port]: use the given remote library</li>
84 * </ul>
85 *
86 * @param args
87 * see method description
88 */
89 public static void main(String[] args) {
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) {
106 // Only one line, but very important:
107 Instance.init();
108
109 String urlString = null;
110 String luid = null;
111 String sourceString = null;
112 String titleString = null;
113 String authorString = null;
114 String chapString = null;
115 String target = null;
116 String key = null;
117 MainAction action = MainAction.START;
118 Boolean plusInfo = null;
119 String host = null;
120 Integer port = null;
121 SupportType searchOn = null;
122 String search = null;
123 List<Integer> tags = new ArrayList<Integer>();
124 Integer page = null;
125 Integer item = null;
126
127 boolean noMoreActions = false;
128
129 int exitCode = 0;
130 for (int i = 0; exitCode == 0 && i < args.length; i++) {
131 if (args[i] == null)
132 continue;
133
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) {
143 Instance.getInstance().getTraceHandler()
144 .error(new IllegalArgumentException("Unknown action: " + args[i], e));
145 exitCode = 255;
146 }
147 }
148
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];
163 } else if (sourceString == null) {
164 sourceString = args[i];
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];
174 } else if (sourceString == null) {
175 sourceString = args[i];
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;
186 }
187 break;
188 case LIST:
189 if (sourceString == null) {
190 sourceString = args[i];
191 } else {
192 exitCode = 255;
193 }
194 break;
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;
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;
229 }
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;
238 }
239 break;
240 case SEARCH:
241 if (searchOn == null) {
242 searchOn = SupportType.valueOfAllOkUC(args[i]);
243
244 if (searchOn == null) {
245 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
246 exitCode = 41;
247 break;
248 }
249
250 if (BasicSearchable.getSearchable(searchOn) == null) {
251 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
252 exitCode = 42;
253 break;
254 }
255 } else if (search == null) {
256 search = args[i];
257 } else if (page != null && page == -1) {
258 try {
259 page = Integer.parseInt(args[i]);
260 } catch (Exception e) {
261 page = -2;
262 }
263 } else if (item != null && item == -1) {
264 try {
265 item = Integer.parseInt(args[i]);
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 {
275 exitCode = 255;
276 }
277 } else {
278 exitCode = 255;
279 }
280 break;
281 case SEARCH_TAG:
282 if (searchOn == null) {
283 searchOn = SupportType.valueOfAllOkUC(args[i]);
284
285 if (searchOn == null) {
286 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
287 exitCode = 255;
288 }
289
290 if (BasicSearchable.getSearchable(searchOn) == null) {
291 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
292 exitCode = 255;
293 }
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) {
304 Instance.getInstance().getTraceHandler().error("Invalid tag index: " + args[i]);
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 }
328 } else {
329 exitCode = 255;
330 }
331 break;
332 case HELP:
333 exitCode = 255;
334 break;
335 case START:
336 exitCode = 255; // not supposed to be selected by user
337 break;
338 case VERSION:
339 exitCode = 255; // no arguments for this option
340 break;
341 case SERVER:
342 exitCode = 255; // no arguments for this option
343 break;
344 case STOP_SERVER:
345 exitCode = 255; // no arguments for this option
346 break;
347 case REMOTE:
348 if (key == null) {
349 key = args[i];
350 } else if (host == null) {
351 host = args[i];
352 } else if (port == null) {
353 port = Integer.parseInt(args[i]);
354
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
363 lib = new CacheLibrary(
364 Instance.getInstance().getRemoteDir(host), lib,
365 Instance.getInstance().getUiConfig());
366
367 Instance.getInstance().setLibrary(lib);
368
369 action = MainAction.START;
370 } else {
371 exitCode = 255;
372 }
373 break;
374 }
375 }
376
377 final Progress mainProgress = new Progress(0, 80);
378 mainProgress.addProgressListener(new Progress.ProgressListener() {
379 private int current = mainProgress.getMin();
380
381 @Override
382 public void progress(Progress progress, String name) {
383 int diff = progress.getProgress() - current;
384 current += diff;
385
386 if (diff <= 0)
387 return;
388
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
404 VersionCheck updates = checkUpdates();
405
406 if (exitCode == 0) {
407 switch (action) {
408 case IMPORT:
409 if (updates != null) {
410 // we consider it read
411 Instance.getInstance().setVersionChecked();
412 }
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
421 break;
422 case EXPORT:
423 if (updates != null) {
424 // we consider it read
425 Instance.getInstance().setVersionChecked();
426 }
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
437 break;
438 case CONVERT:
439 if (updates != null) {
440 // we consider it read
441 Instance.getInstance().setVersionChecked();
442 }
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,
454 plusInfo == null ? false : plusInfo, pg);
455
456 break;
457 case LIST:
458 exitCode = list(sourceString);
459 break;
460 case SET_SOURCE:
461 try {
462 Instance.getInstance().getLibrary().changeSource(luid, sourceString, pg);
463 } catch (IOException e1) {
464 Instance.getInstance().getTraceHandler().error(e1);
465 exitCode = 21;
466 }
467 break;
468 case SET_TITLE:
469 try {
470 Instance.getInstance().getLibrary().changeTitle(luid, titleString, pg);
471 } catch (IOException e1) {
472 Instance.getInstance().getTraceHandler().error(e1);
473 exitCode = 22;
474 }
475 break;
476 case SET_AUTHOR:
477 try {
478 Instance.getInstance().getLibrary().changeAuthor(luid, authorString, pg);
479 } catch (IOException e1) {
480 Instance.getInstance().getTraceHandler().error(e1);
481 exitCode = 23;
482 }
483 break;
484 case READ:
485 if (luid == null || luid.isEmpty()) {
486 syntax(false);
487 exitCode = 255;
488 break;
489 }
490
491 try {
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
504 BasicLibrary lib = Instance.getInstance().getLibrary();
505 exitCode = read(lib.getStory(luid, null), chap);
506 } catch (IOException e) {
507 Instance.getInstance().getTraceHandler()
508 .error(new IOException("Failed to read book", e));
509 exitCode = 2;
510 }
511
512 break;
513 case READ_URL:
514 if (urlString == null || urlString.isEmpty()) {
515 syntax(false);
516 exitCode = 255;
517 break;
518 }
519
520 try {
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
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
542 exitCode = read(support.process(null), chap);
543 } catch (IOException e) {
544 Instance.getInstance().getTraceHandler()
545 .error(new IOException("Failed to read book", e));
546 exitCode = 2;
547 }
548
549 break;
550 case SEARCH:
551 page = page == null ? 1 : page;
552 if (page < 0) {
553 Instance.getInstance().getTraceHandler().error("Incorrect page number");
554 exitCode = 255;
555 break;
556 }
557
558 item = item == null ? 0 : item;
559 if (item < 0) {
560 Instance.getInstance().getTraceHandler().error("Incorrect item number");
561 exitCode = 255;
562 break;
563 }
564
565 if (searchOn == null) {
566 try {
567 search();
568 } catch (IOException e) {
569 Instance.getInstance().getTraceHandler().error(e);
570 exitCode = 1;
571 }
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;
581 }
582
583 break;
584 case SEARCH_TAG:
585 if (searchOn == null) {
586 exitCode = 255;
587 break;
588 }
589
590 page = page == null ? 1 : page;
591 if (page < 0) {
592 Instance.getInstance().getTraceHandler().error("Incorrect page number");
593 exitCode = 255;
594 break;
595 }
596
597 item = item == null ? 0 : item;
598 if (item < 0) {
599 Instance.getInstance().getTraceHandler().error("Incorrect item number");
600 exitCode = 255;
601 break;
602 }
603
604 try {
605 searchTags(searchOn, page, item,
606 tags.toArray(new Integer[] {}));
607 } catch (IOException e) {
608 Instance.getInstance().getTraceHandler().error(e);
609 }
610
611 break;
612 case HELP:
613 syntax(true);
614 exitCode = 0;
615 break;
616 case VERSION:
617 if (updates != null) {
618 // we consider it read
619 Instance.getInstance().setVersionChecked();
620 }
621
622 System.out
623 .println(String.format("Fanfix version %s"
624 + "%nhttps://github.com/nikiroo/fanfix/"
625 + "%n\tWritten by Nikiroo",
626 Version.getCurrentVersion()));
627 break;
628 case START:
629 try {
630 start();
631 } catch (IOException e) {
632 Instance.getInstance().getTraceHandler().error(e);
633 exitCode = 66;
634 }
635 break;
636 case SERVER:
637 try {
638 startServer();
639 } catch (IOException e) {
640 Instance.getInstance().getTraceHandler().error(e);
641 }
642
643 break;
644 case STOP_SERVER:
645 // Can be given via "--remote XX XX XX"
646 if (key == null)
647 key = Instance.getInstance().getConfig().getString(Config.SERVER_KEY);
648 if (port == null)
649 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
650
651 if (host == null) {
652 String mode = Instance.getInstance().getConfig()
653 .getString(Config.SERVER_MODE, "fanfix");
654 if ("http".equals(mode)) {
655 host = "http://localhost";
656 } else if ("https".equals(mode)) {
657 host = "https://localhost";
658 } else if ("fanfix".equals(mode)) {
659 host = "fanfix://localhost";
660 }
661 }
662
663 if (port == null) {
664 System.err.println("No port given nor configured in the config file");
665 exitCode = 15;
666 break;
667 }
668 try {
669 stopServer(key, host, port);
670 } catch (SSLException e) {
671 Instance.getInstance().getTraceHandler().error(
672 "Bad access key for remote library");
673 exitCode = 43;
674 } catch (IOException e) {
675 Instance.getInstance().getTraceHandler().error(e);
676 exitCode = 44;
677 }
678
679 break;
680 case REMOTE:
681 exitCode = 255; // should not be reachable (REMOTE -> START)
682 break;
683 }
684 }
685
686 try {
687 Instance.getInstance().getTempFiles().close();
688 } catch (IOException e) {
689 Instance.getInstance().getTraceHandler().error(new IOException(
690 "Cannot dispose of the temporary files", e));
691 }
692
693 if (exitCode == 255) {
694 syntax(false);
695 }
696
697 exit(exitCode);
698 }
699
700 /**
701 * A normal invocation of the program (without parameters or at least
702 * without "action" parameters).
703 * <p>
704 * You will probably want to override that one if you offer a user
705 * interface.
706 *
707 * @throws IOException
708 * in case of I/O error
709 */
710 protected void start() throws IOException {
711 new CliReader().listBooks(null);
712 }
713
714 /**
715 * Will check if updates are available, synchronously.
716 * <p>
717 * For this, it will simply forward the call to
718 * {@link Main#checkUpdates(String)} with a value of "nikiroo/fanfix".
719 * <p>
720 * You may want to override it so you call the forward method with the right
721 * parameters (or also if you want it to be asynchronous).
722 *
723 * @return the newer version information or NULL if nothing new
724 */
725 protected VersionCheck checkUpdates() {
726 return checkUpdates("nikiroo/fanfix");
727 }
728
729 /**
730 * Will check if updates are available on a specific GitHub project.
731 * <p>
732 * Will be called by {@link Main#checkUpdates()}, but if you override that
733 * one you mall call it with another project.
734 *
735 * @param githubProject
736 * the GitHub project, for instance "nikiroo/fanfix"
737 *
738 * @return the newer version information or NULL if nothing new
739 */
740 protected VersionCheck checkUpdates(String githubProject) {
741 try {
742 VersionCheck updates = VersionCheck.check(githubProject,
743 Instance.getInstance().getTrans().getLocale());
744 if (updates.isNewVersionAvailable()) {
745 notifyUpdates(updates);
746 return updates;
747 }
748 } catch (IOException e) {
749 // Maybe no internet. Do not report any update.
750 }
751
752 return null;
753 }
754
755 /**
756 * Notify the user about available updates.
757 * <p>
758 * Will only be called when a version is available.
759 * <p>
760 * Note that you can call {@link Instance#setVersionChecked()} on it if the
761 * user has read the information (by default, it is marked read only on
762 * certain other actions).
763 *
764 * @param updates
765 * the new version information
766 */
767 protected void notifyUpdates(VersionCheck updates) {
768 // Sent to syserr so not to cause problem if one tries to capture a
769 // story content in text mode
770 System.err.println(
771 "A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
772 System.err.println("");
773 for (Version v : updates.getNewer()) {
774 System.err.println("\tVersion " + v);
775 System.err.println("\t-------------");
776 System.err.println("");
777 for (String it : updates.getChanges().get(v)) {
778 System.err.println("\t- " + it);
779 }
780 System.err.println("");
781 }
782 }
783
784 /**
785 * Import the given resource into the {@link LocalLibrary}.
786 *
787 * @param url
788 * the resource to import
789 * @param pg
790 * the optional progress reporter
791 *
792 * @return the exit return code (0 = success)
793 */
794 protected static int imprt(URL url, Progress pg) {
795 try {
796 MetaData meta = Instance.getInstance().getLibrary().imprt(url, pg);
797 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
798 } catch (IOException e) {
799 Instance.getInstance().getTraceHandler().error(e);
800 return 1;
801 }
802
803 return 0;
804 }
805
806 /**
807 * Export the {@link Story} from the {@link LocalLibrary} to the given
808 * target.
809 *
810 * @param luid
811 * the story LUID
812 * @param type
813 * the {@link OutputType} to use
814 * @param target
815 * the target
816 * @param pg
817 * the optional progress reporter
818 *
819 * @return the exit return code (0 = success)
820 */
821 protected static int export(String luid, OutputType type, String target,
822 Progress pg) {
823 try {
824 Instance.getInstance().getLibrary().export(luid, type, target, pg);
825 } catch (IOException e) {
826 Instance.getInstance().getTraceHandler().error(e);
827 return 4;
828 }
829
830 return 0;
831 }
832
833 /**
834 * List the stories of the given source from the {@link LocalLibrary}
835 * (unless NULL is passed, in which case all stories will be listed).
836 *
837 * @param source
838 * the source to list the known stories of, or NULL to list all
839 * stories
840 *
841 * @return the exit return code (0 = success)
842 */
843 protected int list(String source) {
844 try {
845 new CliReader().listBooks(source);
846 } catch (IOException e) {
847 Instance.getInstance().getTraceHandler().error(e);
848 return 66;
849 }
850
851 return 0;
852 }
853
854 /**
855 * Start the current reader for this {@link Story}.
856 *
857 * @param story
858 * the story to read
859 * @param chap
860 * which {@link Chapter} to read (starting at 1), or NULL to get
861 * the {@link Story} description
862 *
863 * @return the exit return code (0 = success)
864 */
865 protected int read(Story story, Integer chap) {
866 if (story != null) {
867 try {
868 if (chap == null) {
869 new CliReader().listChapters(story);
870 } else {
871 new CliReader().printChapter(story, chap);
872 }
873 } catch (IOException e) {
874 Instance.getInstance().getTraceHandler()
875 .error(new IOException("Failed to read book", e));
876 return 2;
877 }
878 } else {
879 Instance.getInstance().getTraceHandler()
880 .error("Cannot find book: " + story);
881 return 2;
882 }
883
884 return 0;
885 }
886
887 /**
888 * Convert the {@link Story} into another format.
889 *
890 * @param urlString
891 * the source {@link Story} to convert
892 * @param type
893 * the {@link OutputType} to convert to
894 * @param target
895 * the target file
896 * @param infoCover
897 * TRUE to also export the cover and info file, even if the given
898 * {@link OutputType} does not usually save them
899 * @param pg
900 * the optional progress reporter
901 *
902 * @return the exit return code (0 = success)
903 */
904 protected int convert(String urlString, OutputType type,
905 String target, boolean infoCover, Progress pg) {
906 int exitCode = 0;
907
908 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
909 String sourceName = urlString;
910 try {
911 URL source = BasicReader.getUrl(urlString);
912 sourceName = source.toString();
913 if (sourceName.startsWith("file://")) {
914 sourceName = sourceName.substring("file://".length());
915 }
916
917 try {
918 BasicSupport support = BasicSupport.getSupport(source);
919
920 if (support != null) {
921 Instance.getInstance().getTraceHandler()
922 .trace("Support found: " + support.getClass());
923 Progress pgIn = new Progress();
924 Progress pgOut = new Progress();
925 if (pg != null) {
926 pg.setMax(2);
927 pg.addProgress(pgIn, 1);
928 pg.addProgress(pgOut, 1);
929 }
930
931 Story story = support.process(pgIn);
932 try {
933 target = new File(target).getAbsolutePath();
934 BasicOutput.getOutput(type, infoCover, infoCover)
935 .process(story, target, pgOut);
936 } catch (IOException e) {
937 Instance.getInstance().getTraceHandler()
938 .error(new IOException(
939 trans(StringId.ERR_SAVING, target), e));
940 exitCode = 5;
941 }
942 } else {
943 Instance.getInstance().getTraceHandler()
944 .error(new IOException(
945 trans(StringId.ERR_NOT_SUPPORTED, source)));
946
947 exitCode = 4;
948 }
949 } catch (IOException e) {
950 Instance.getInstance().getTraceHandler().error(new IOException(
951 trans(StringId.ERR_LOADING, sourceName), e));
952 exitCode = 3;
953 }
954 } catch (MalformedURLException e) {
955 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
956 exitCode = 1;
957 }
958
959 return exitCode;
960 }
961
962 /**
963 * Display the correct syntax of the program to the user to stdout, or an
964 * error message if the syntax used was wrong on stderr.
965 *
966 * @param showHelp
967 * TRUE to show the syntax help, FALSE to show "syntax error"
968 */
969 protected void syntax(boolean showHelp) {
970 if (showHelp) {
971 StringBuilder builder = new StringBuilder();
972 for (SupportType type : SupportType.values()) {
973 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
974 type.getDesc()));
975 builder.append('\n');
976 }
977
978 String typesIn = builder.toString();
979 builder.setLength(0);
980
981 for (OutputType type : OutputType.values()) {
982 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
983 type.getDesc(true)));
984 builder.append('\n');
985 }
986
987 String typesOut = builder.toString();
988
989 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
990 } else {
991 System.err.println(trans(StringId.ERR_SYNTAX));
992 }
993 }
994
995 /**
996 * Starts a search operation (i.e., list the available web sites we can
997 * search on).
998 *
999 * @throws IOException
1000 * in case of I/O errors
1001 */
1002 protected void search() throws IOException {
1003 new CliReader().listSearchables();
1004 }
1005
1006 /**
1007 * Search for books by keywords on the given supported web site.
1008 *
1009 * @param searchOn
1010 * the web site to search on
1011 * @param search
1012 * the keyword to look for
1013 * @param page
1014 * the page of results to get, or 0 to inquire about the number
1015 * of pages
1016 * @param item
1017 * the index of the book we are interested by, or 0 to query
1018 * about how many books are in that page of results
1019 *
1020 * @throws IOException
1021 * in case of I/O error
1022 */
1023 protected void searchKeywords(SupportType searchOn, String search,
1024 int page, Integer item) throws IOException {
1025 new CliReader().searchBooksByKeyword(searchOn, search, page, item);
1026 }
1027
1028 /**
1029 * Search for books by tags on the given supported web site.
1030 *
1031 * @param searchOn
1032 * the web site to search on
1033 * @param page
1034 * the page of results to get, or 0 to inquire about the number
1035 * of pages
1036 * @param item
1037 * the index of the book we are interested by, or 0 to query
1038 * about how many books are in that page of results
1039 * @param tags
1040 * the tags to look for
1041 *
1042 * @throws IOException
1043 * in case of I/O error
1044 */
1045 protected void searchTags(SupportType searchOn, Integer page, Integer item,
1046 Integer[] tags) throws IOException {
1047 new CliReader().searchBooksByTag(searchOn, page, item, tags);
1048 }
1049
1050 /**
1051 * Start a Fanfix server.
1052 *
1053 * @throws IOException
1054 * in case of I/O errors
1055 * @throws SSLException
1056 * when the key was not accepted
1057 */
1058 private void startServer() throws IOException {
1059 String mode = Instance.getInstance().getConfig()
1060 .getString(Config.SERVER_MODE, "fanfix");
1061 if (mode.equals("fanfix")) {
1062 RemoteLibraryServer server = new RemoteLibraryServer();
1063 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1064 server.run();
1065 } else if (mode.equals("http")) {
1066 WebLibraryServer server = new WebLibraryServer(false);
1067 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1068 server.run();
1069 } else if (mode.equals("https")) {
1070 WebLibraryServer server = new WebLibraryServer(true);
1071 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1072 server.run();
1073 } else {
1074 throw new IOException("Unknown server mode: " + mode);
1075 }
1076 }
1077
1078 /**
1079 * Stop a running Fanfix server.
1080 *
1081 * @param key
1082 * the key to contact the Fanfix server
1083 * @param host
1084 * the host on which it runs
1085 * @param port
1086 * the port on which it runs
1087 *
1088 * @throws IOException
1089 * in case of I/O errors
1090 * @throws SSLException
1091 * when the key was not accepted
1092 */
1093 private void stopServer(String key, String host, int port)
1094 throws IOException, SSLException {
1095 if (host.startsWith("http://") || host.startsWith("https://")) {
1096 new WebLibrary(key, host, port).stop();
1097 } else {
1098 new RemoteLibrary(key, host, port).stop();
1099 }
1100 }
1101
1102 /**
1103 * We are done and ready to exit.
1104 * <p>
1105 * By default, it will call {@link System#exit(int)} if the status is not 0.
1106 *
1107 * @param status
1108 * the exit status
1109 */
1110 protected void exit(int status) {
1111 if (status != 0) {
1112 System.exit(status);
1113 }
1114 }
1115
1116 /**
1117 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
1118 *
1119 * @param id
1120 * the ID to translate
1121 *
1122 * @return the translated result
1123 */
1124 static private String trans(StringId id, Object... params) {
1125 return Instance.getInstance().getTrans().getString(id, params);
1126 }
1127 }