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