Merge branch 'master' into subtree
[nikiroo-utils.git] / 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()
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) {
662 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
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 }
676
677 if (port == null) {
678 System.err.println("No port given nor configured in the config file");
679 exitCode = 15;
680 break;
681 }
682 try {
683 stopServer(key, host, port);
684 } catch (SSLException e) {
685 Instance.getInstance().getTraceHandler().error(
686 "Bad access key for remote library");
687 exitCode = 43;
688 } catch (IOException e) {
689 Instance.getInstance().getTraceHandler().error(e);
690 exitCode = 44;
691 }
692
693 break;
694 case REMOTE:
695 exitCode = 255; // should not be reachable (REMOTE -> START)
696 break;
697 }
698 }
699
700 try {
701 Instance.getInstance().getTempFiles().close();
702 } catch (IOException e) {
703 Instance.getInstance().getTraceHandler().error(new IOException(
704 "Cannot dispose of the temporary files", e));
705 }
706
707 if (exitCode == 255) {
708 syntax(false);
709 }
710
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 /**
729 * Will check if updates are available, synchronously.
730 * <p>
731 * For this, it will simply forward the call to
732 * {@link Main#checkUpdates(String)} with a value of "nikiroo/fanfix".
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).
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) {
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.
764 }
765
766 return null;
767 }
768
769 /**
770 * Notify the user about available updates.
771 * <p>
772 * Will only be called when a version is available.
773 * <p>
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).
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
798 /**
799 * Import the given resource into the {@link LocalLibrary}.
800 *
801 * @param url
802 * the resource to import
803 * @param pg
804 * the optional progress reporter
805 *
806 * @return the exit return code (0 = success)
807 */
808 protected static int imprt(URL url, Progress pg) {
809 try {
810 MetaData meta = Instance.getInstance().getLibrary().imprt(url, pg);
811 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
812 } catch (IOException e) {
813 Instance.getInstance().getTraceHandler().error(e);
814 return 1;
815 }
816
817 return 0;
818 }
819
820 /**
821 * Export the {@link Story} from the {@link LocalLibrary} to the given
822 * target.
823 *
824 * @param luid
825 * the story LUID
826 * @param type
827 * the {@link OutputType} to use
828 * @param target
829 * the target
830 * @param pg
831 * the optional progress reporter
832 *
833 * @return the exit return code (0 = success)
834 */
835 protected static int export(String luid, OutputType type, String target,
836 Progress pg) {
837 try {
838 Instance.getInstance().getLibrary().export(luid, type, target, pg);
839 } catch (IOException e) {
840 Instance.getInstance().getTraceHandler().error(e);
841 return 4;
842 }
843
844 return 0;
845 }
846
847 /**
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).
850 *
851 * @param source
852 * the source to list the known stories of, or NULL to list all
853 * stories
854 *
855 * @return the exit return code (0 = success)
856 */
857 protected int list(String source) {
858 try {
859 new CliReader().listBooks(source);
860 } catch (IOException e) {
861 Instance.getInstance().getTraceHandler().error(e);
862 return 66;
863 }
864
865 return 0;
866 }
867
868 /**
869 * Start the current reader for this {@link Story}.
870 *
871 * @param story
872 * the story to read
873 * @param chap
874 * which {@link Chapter} to read (starting at 1), or NULL to get
875 * the {@link Story} description
876 *
877 * @return the exit return code (0 = success)
878 */
879 protected int read(Story story, Integer chap) {
880 if (story != null) {
881 try {
882 if (chap == null) {
883 new CliReader().listChapters(story);
884 } else {
885 new CliReader().printChapter(story, chap);
886 }
887 } catch (IOException e) {
888 Instance.getInstance().getTraceHandler()
889 .error(new IOException("Failed to read book", e));
890 return 2;
891 }
892 } else {
893 Instance.getInstance().getTraceHandler()
894 .error("Cannot find book: " + story);
895 return 2;
896 }
897
898 return 0;
899 }
900
901 /**
902 * Convert the {@link Story} into another format.
903 *
904 * @param urlString
905 * the source {@link Story} to convert
906 * @param type
907 * the {@link OutputType} to convert to
908 * @param target
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
913 * @param pg
914 * the optional progress reporter
915 *
916 * @return the exit return code (0 = success)
917 */
918 protected int convert(String urlString, OutputType type,
919 String target, boolean infoCover, Progress pg) {
920 int exitCode = 0;
921
922 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
923 String sourceName = urlString;
924 try {
925 URL source = BasicReader.getUrl(urlString);
926 sourceName = source.toString();
927 if (sourceName.startsWith("file://")) {
928 sourceName = sourceName.substring("file://".length());
929 }
930
931 try {
932 BasicSupport support = BasicSupport.getSupport(source);
933
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 }
944
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) {
951 Instance.getInstance().getTraceHandler()
952 .error(new IOException(
953 trans(StringId.ERR_SAVING, target), e));
954 exitCode = 5;
955 }
956 } else {
957 Instance.getInstance().getTraceHandler()
958 .error(new IOException(
959 trans(StringId.ERR_NOT_SUPPORTED, source)));
960
961 exitCode = 4;
962 }
963 } catch (IOException e) {
964 Instance.getInstance().getTraceHandler().error(new IOException(
965 trans(StringId.ERR_LOADING, sourceName), e));
966 exitCode = 3;
967 }
968 } catch (MalformedURLException e) {
969 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
970 exitCode = 1;
971 }
972
973 return exitCode;
974 }
975
976 /**
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"
982 */
983 protected void syntax(boolean showHelp) {
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 }
991
992 String typesIn = builder.toString();
993 builder.setLength(0);
994
995 for (OutputType type : OutputType.values()) {
996 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
997 type.getDesc(true)));
998 builder.append('\n');
999 }
1000
1001 String typesOut = builder.toString();
1002
1003 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
1004 } else {
1005 System.err.println(trans(StringId.ERR_SYNTAX));
1006 }
1007 }
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 *
1067 * @throws IOException
1068 * in case of I/O errors
1069 * @throws SSLException
1070 * when the key was not accepted
1071 */
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 }
1090 }
1091
1092 /**
1093 * Stop a running Fanfix server.
1094 *
1095 * @param key
1096 * the key to contact the Fanfix server
1097 * @param host
1098 * the host on which it runs
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 */
1107 private void stopServer(String key, String host, int port)
1108 throws IOException, SSLException {
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 }
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 }
1141 }