merge 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.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 (port == null) {
652 System.err.println("No port given nor configured in the config file");
653 exitCode = 15;
654 break;
655 }
656 try {
657 stopServer(key, host, port);
658 } catch (SSLException e) {
659 Instance.getInstance().getTraceHandler().error(
660 "Bad access key for remote library");
661 exitCode = 43;
662 } catch (IOException e) {
663 Instance.getInstance().getTraceHandler().error(e);
664 exitCode = 44;
665 }
666
667 break;
668 case REMOTE:
669 exitCode = 255; // should not be reachable (REMOTE -> START)
670 break;
671 }
672 }
673
674 try {
675 Instance.getInstance().getTempFiles().close();
676 } catch (IOException e) {
677 Instance.getInstance().getTraceHandler().error(new IOException(
678 "Cannot dispose of the temporary files", e));
679 }
680
681 if (exitCode == 255) {
682 syntax(false);
683 }
684
685 exit(exitCode);
686 }
687
688 /**
689 * A normal invocation of the program (without parameters or at least
690 * without "action" parameters).
691 * <p>
692 * You will probably want to override that one if you offer a user
693 * interface.
694 *
695 * @throws IOException
696 * in case of I/O error
697 */
698 protected void start() throws IOException {
699 new CliReader().listBooks(null);
700 }
701
702 /**
703 * Will check if updates are available, synchronously.
704 * <p>
705 * For this, it will simply forward the call to
706 * {@link Main#checkUpdates(String)} with a value of "nikiroo/fanfix".
707 * <p>
708 * You may want to override it so you call the forward method with the right
709 * parameters (or also if you want it to be asynchronous).
710 *
711 * @return the newer version information or NULL if nothing new
712 */
713 protected VersionCheck checkUpdates() {
714 return checkUpdates("nikiroo/fanfix");
715 }
716
717 /**
718 * Will check if updates are available on a specific GitHub project.
719 * <p>
720 * Will be called by {@link Main#checkUpdates()}, but if you override that
721 * one you mall call it with another project.
722 *
723 * @param githubProject
724 * the GitHub project, for instance "nikiroo/fanfix"
725 *
726 * @return the newer version information or NULL if nothing new
727 */
728 protected VersionCheck checkUpdates(String githubProject) {
729 try {
730 VersionCheck updates = VersionCheck.check(githubProject,
731 Instance.getInstance().getTrans().getLocale());
732 if (updates.isNewVersionAvailable()) {
733 notifyUpdates(updates);
734 return updates;
735 }
736 } catch (IOException e) {
737 // Maybe no internet. Do not report any update.
738 }
739
740 return null;
741 }
742
743 /**
744 * Notify the user about available updates.
745 * <p>
746 * Will only be called when a version is available.
747 * <p>
748 * Note that you can call {@link Instance#setVersionChecked()} on it if the
749 * user has read the information (by default, it is marked read only on
750 * certain other actions).
751 *
752 * @param updates
753 * the new version information
754 */
755 protected void notifyUpdates(VersionCheck updates) {
756 // Sent to syserr so not to cause problem if one tries to capture a
757 // story content in text mode
758 System.err.println(
759 "A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
760 System.err.println("");
761 for (Version v : updates.getNewer()) {
762 System.err.println("\tVersion " + v);
763 System.err.println("\t-------------");
764 System.err.println("");
765 for (String it : updates.getChanges().get(v)) {
766 System.err.println("\t- " + it);
767 }
768 System.err.println("");
769 }
770 }
771
772 /**
773 * Import the given resource into the {@link LocalLibrary}.
774 *
775 * @param url
776 * the resource to import
777 * @param pg
778 * the optional progress reporter
779 *
780 * @return the exit return code (0 = success)
781 */
782 protected static int imprt(URL url, Progress pg) {
783 try {
784 MetaData meta = Instance.getInstance().getLibrary().imprt(url, pg);
785 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
786 } catch (IOException e) {
787 Instance.getInstance().getTraceHandler().error(e);
788 return 1;
789 }
790
791 return 0;
792 }
793
794 /**
795 * Export the {@link Story} from the {@link LocalLibrary} to the given
796 * target.
797 *
798 * @param luid
799 * the story LUID
800 * @param type
801 * the {@link OutputType} to use
802 * @param target
803 * the target
804 * @param pg
805 * the optional progress reporter
806 *
807 * @return the exit return code (0 = success)
808 */
809 protected static int export(String luid, OutputType type, String target,
810 Progress pg) {
811 try {
812 Instance.getInstance().getLibrary().export(luid, type, target, pg);
813 } catch (IOException e) {
814 Instance.getInstance().getTraceHandler().error(e);
815 return 4;
816 }
817
818 return 0;
819 }
820
821 /**
822 * List the stories of the given source from the {@link LocalLibrary}
823 * (unless NULL is passed, in which case all stories will be listed).
824 *
825 * @param source
826 * the source to list the known stories of, or NULL to list all
827 * stories
828 *
829 * @return the exit return code (0 = success)
830 */
831 protected int list(String source) {
832 try {
833 new CliReader().listBooks(source);
834 } catch (IOException e) {
835 Instance.getInstance().getTraceHandler().error(e);
836 return 66;
837 }
838
839 return 0;
840 }
841
842 /**
843 * Start the current reader for this {@link Story}.
844 *
845 * @param story
846 * the story to read
847 * @param chap
848 * which {@link Chapter} to read (starting at 1), or NULL to get
849 * the {@link Story} description
850 *
851 * @return the exit return code (0 = success)
852 */
853 protected int read(Story story, Integer chap) {
854 if (story != null) {
855 try {
856 if (chap == null) {
857 new CliReader().listChapters(story);
858 } else {
859 new CliReader().printChapter(story, chap);
860 }
861 } catch (IOException e) {
862 Instance.getInstance().getTraceHandler()
863 .error(new IOException("Failed to read book", e));
864 return 2;
865 }
866 } else {
867 Instance.getInstance().getTraceHandler()
868 .error("Cannot find book: " + story);
869 return 2;
870 }
871
872 return 0;
873 }
874
875 /**
876 * Convert the {@link Story} into another format.
877 *
878 * @param urlString
879 * the source {@link Story} to convert
880 * @param type
881 * the {@link OutputType} to convert to
882 * @param target
883 * the target file
884 * @param infoCover
885 * TRUE to also export the cover and info file, even if the given
886 * {@link OutputType} does not usually save them
887 * @param pg
888 * the optional progress reporter
889 *
890 * @return the exit return code (0 = success)
891 */
892 protected int convert(String urlString, OutputType type,
893 String target, boolean infoCover, Progress pg) {
894 int exitCode = 0;
895
896 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
897 String sourceName = urlString;
898 try {
899 URL source = BasicReader.getUrl(urlString);
900 sourceName = source.toString();
901 if (sourceName.startsWith("file://")) {
902 sourceName = sourceName.substring("file://".length());
903 }
904
905 try {
906 BasicSupport support = BasicSupport.getSupport(source);
907
908 if (support != null) {
909 Instance.getInstance().getTraceHandler()
910 .trace("Support found: " + support.getClass());
911 Progress pgIn = new Progress();
912 Progress pgOut = new Progress();
913 if (pg != null) {
914 pg.setMax(2);
915 pg.addProgress(pgIn, 1);
916 pg.addProgress(pgOut, 1);
917 }
918
919 Story story = support.process(pgIn);
920 try {
921 target = new File(target).getAbsolutePath();
922 BasicOutput.getOutput(type, infoCover, infoCover)
923 .process(story, target, pgOut);
924 } catch (IOException e) {
925 Instance.getInstance().getTraceHandler()
926 .error(new IOException(
927 trans(StringId.ERR_SAVING, target), e));
928 exitCode = 5;
929 }
930 } else {
931 Instance.getInstance().getTraceHandler()
932 .error(new IOException(
933 trans(StringId.ERR_NOT_SUPPORTED, source)));
934
935 exitCode = 4;
936 }
937 } catch (IOException e) {
938 Instance.getInstance().getTraceHandler().error(new IOException(
939 trans(StringId.ERR_LOADING, sourceName), e));
940 exitCode = 3;
941 }
942 } catch (MalformedURLException e) {
943 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
944 exitCode = 1;
945 }
946
947 return exitCode;
948 }
949
950 /**
951 * Display the correct syntax of the program to the user to stdout, or an
952 * error message if the syntax used was wrong on stderr.
953 *
954 * @param showHelp
955 * TRUE to show the syntax help, FALSE to show "syntax error"
956 */
957 protected void syntax(boolean showHelp) {
958 if (showHelp) {
959 StringBuilder builder = new StringBuilder();
960 for (SupportType type : SupportType.values()) {
961 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
962 type.getDesc()));
963 builder.append('\n');
964 }
965
966 String typesIn = builder.toString();
967 builder.setLength(0);
968
969 for (OutputType type : OutputType.values()) {
970 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
971 type.getDesc(true)));
972 builder.append('\n');
973 }
974
975 String typesOut = builder.toString();
976
977 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
978 } else {
979 System.err.println(trans(StringId.ERR_SYNTAX));
980 }
981 }
982
983 /**
984 * Starts a search operation (i.e., list the available web sites we can
985 * search on).
986 *
987 * @throws IOException
988 * in case of I/O errors
989 */
990 protected void search() throws IOException {
991 new CliReader().listSearchables();
992 }
993
994 /**
995 * Search for books by keywords on the given supported web site.
996 *
997 * @param searchOn
998 * the web site to search on
999 * @param search
1000 * the keyword to look for
1001 * @param page
1002 * the page of results to get, or 0 to inquire about the number
1003 * of pages
1004 * @param item
1005 * the index of the book we are interested by, or 0 to query
1006 * about how many books are in that page of results
1007 *
1008 * @throws IOException
1009 * in case of I/O error
1010 */
1011 protected void searchKeywords(SupportType searchOn, String search,
1012 int page, Integer item) throws IOException {
1013 new CliReader().searchBooksByKeyword(searchOn, search, page, item);
1014 }
1015
1016 /**
1017 * Search for books by tags on the given supported web site.
1018 *
1019 * @param searchOn
1020 * the web site to search on
1021 * @param page
1022 * the page of results to get, or 0 to inquire about the number
1023 * of pages
1024 * @param item
1025 * the index of the book we are interested by, or 0 to query
1026 * about how many books are in that page of results
1027 * @param tags
1028 * the tags to look for
1029 *
1030 * @throws IOException
1031 * in case of I/O error
1032 */
1033 protected void searchTags(SupportType searchOn, Integer page, Integer item,
1034 Integer[] tags) throws IOException {
1035 new CliReader().searchBooksByTag(searchOn, page, item, tags);
1036 }
1037
1038 /**
1039 * Start a Fanfix server.
1040 *
1041 * @throws IOException
1042 * in case of I/O errors
1043 * @throws SSLException
1044 * when the key was not accepted
1045 */
1046 private void startServer() throws IOException {
1047 String mode = Instance.getInstance().getConfig()
1048 .getString(Config.SERVER_MODE, "fanfix");
1049 if (mode.equals("fanfix")) {
1050 RemoteLibraryServer server = new RemoteLibraryServer();
1051 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1052 server.run();
1053 } else if (mode.equals("http")) {
1054 WebLibraryServer server = new WebLibraryServer(false);
1055 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1056 server.run();
1057 } else if (mode.equals("https")) {
1058 WebLibraryServer server = new WebLibraryServer(true);
1059 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1060 server.run();
1061 } else {
1062 throw new IOException("Unknown server mode: " + mode);
1063 }
1064 }
1065
1066 /**
1067 * Stop a running Fanfix server.
1068 *
1069 * @param key
1070 * the key to contact the Fanfix server
1071 * @param host
1072 * the host on which it runs (NULL means localhost)
1073 * @param port
1074 * the port on which it runs
1075 *
1076 * @throws IOException
1077 * in case of I/O errors
1078 * @throws SSLException
1079 * when the key was not accepted
1080 */
1081 private void stopServer(String key, String host, Integer port)
1082 throws IOException, SSLException {
1083 if (host.startsWith("http://") || host.startsWith("https://")) {
1084 new WebLibrary(key, host, port).stop();
1085 } else {
1086 new RemoteLibrary(key, host, port).stop();
1087 }
1088 }
1089
1090 /**
1091 * We are done and ready to exit.
1092 * <p>
1093 * By default, it will call {@link System#exit(int)} if the status is not 0.
1094 *
1095 * @param status
1096 * the exit status
1097 */
1098 protected void exit(int status) {
1099 if (status != 0) {
1100 System.exit(status);
1101 }
1102 }
1103
1104 /**
1105 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
1106 *
1107 * @param id
1108 * the ID to translate
1109 *
1110 * @return the translated result
1111 */
1112 static private String trans(StringId id, Object... params) {
1113 return Instance.getInstance().getTrans().getString(id, params);
1114 }
1115 }