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