1 package be
.nikiroo
.fanfix
;
4 import java
.io
.IOException
;
5 import java
.net
.MalformedURLException
;
7 import java
.util
.ArrayList
;
10 import javax
.net
.ssl
.SSLException
;
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
.Story
;
16 import be
.nikiroo
.fanfix
.library
.BasicLibrary
;
17 import be
.nikiroo
.fanfix
.library
.CacheLibrary
;
18 import be
.nikiroo
.fanfix
.library
.LocalLibrary
;
19 import be
.nikiroo
.fanfix
.library
.RemoteLibrary
;
20 import be
.nikiroo
.fanfix
.library
.RemoteLibraryServer
;
21 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
22 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
23 import be
.nikiroo
.fanfix
.reader
.BasicReader
;
24 import be
.nikiroo
.fanfix
.reader
.Reader
;
25 import be
.nikiroo
.fanfix
.reader
.Reader
.ReaderType
;
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
.serial
.server
.ServerObject
;
34 * Main program entry point.
39 private enum MainAction
{
40 IMPORT
, EXPORT
, CONVERT
, READ
, READ_URL
, LIST
, HELP
, SET_READER
, START
, VERSION
, SERVER
, STOP_SERVER
, REMOTE
, SET_SOURCE
, SET_TITLE
, SET_AUTHOR
, SEARCH
, SEARCH_TAG
44 * Main program entry point.
46 * Known environment variables:
48 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
49 * {@link String}s when possible</li>
50 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
51 * before taking the usual ones; they will also be saved/updated into this
52 * path when the program starts</li>
53 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
54 * configuration value with 'true'</li>
58 * <li>--import [URL]: import into library</li>
59 * <li>--export [id] [output_type] [target]: export story to target</li>
60 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
62 * <li>--read [id] ([chapter number]): read the given story from the library
64 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
65 * story, without saving it</li>
66 * <li>--search: list the supported websites (where)</li>
67 * <li>--search [where] [keywords] (page [page]) (item [item]): search on
68 * the supported website and display the given results page of stories it
69 * found, or the story details if asked</li>
70 * <li>--search-tag [where]: list all the tags supported by this website</li>
71 * <li>--search-tag [index 1]... (page [page]) (item [item]): search for the
72 * given stories or subtags, tag by tag, and display information about a
73 * specific page of results or about a specific item if requested</li>
74 * <li>--list ([type]): list the stories present in the library</li>
75 * <li>--set-source [id] [new source]: change the source of the given story</li>
76 * <li>--set-title [id] [new title]: change the title of the given story</li>
77 * <li>--set-author [id] [new author]: change the author of the given story</li>
78 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
79 * for this command</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 a the given remote library</li>
87 * see method description
89 public static void main(String
[] args
) {
90 // Only one line, but very important:
93 String urlString
= null;
95 String sourceString
= null;
96 String titleString
= null;
97 String authorString
= null;
98 String chapString
= null;
101 MainAction action
= MainAction
.START
;
102 Boolean plusInfo
= null;
105 SupportType searchOn
= null;
106 String search
= null;
107 List
<Integer
> tags
= new ArrayList
<Integer
>();
111 boolean noMoreActions
= false;
114 for (int i
= 0; exitCode
== 0 && i
< args
.length
; i
++) {
115 // Action (--) handling:
116 if (!noMoreActions
&& args
[i
].startsWith("--")) {
117 if (args
[i
].equals("--")) {
118 noMoreActions
= true;
121 action
= MainAction
.valueOf(args
[i
].substring(2)
122 .toUpperCase().replace("-", "_"));
123 } catch (Exception e
) {
124 Instance
.getTraceHandler().error(
125 new IllegalArgumentException("Unknown action: "
136 if (urlString
== null) {
145 } else if (sourceString
== null) {
146 sourceString
= args
[i
];
147 } else if (target
== null) {
154 if (urlString
== null) {
156 } else if (sourceString
== null) {
157 sourceString
= args
[i
];
158 } else if (target
== null) {
160 } else if (plusInfo
== null) {
161 if ("+info".equals(args
[i
])) {
171 if (sourceString
== null) {
172 sourceString
= args
[i
];
180 } else if (sourceString
== null) {
181 sourceString
= args
[i
];
189 } else if (sourceString
== null) {
190 titleString
= args
[i
];
198 } else if (sourceString
== null) {
199 authorString
= args
[i
];
207 } else if (chapString
== null) {
208 chapString
= args
[i
];
214 if (urlString
== null) {
216 } else if (chapString
== null) {
217 chapString
= args
[i
];
223 if (searchOn
== null) {
224 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
226 if (searchOn
== null) {
227 Instance
.getTraceHandler().error(
228 "Website not known: <" + args
[i
] + ">");
233 if (BasicSearchable
.getSearchable(searchOn
) == null) {
234 Instance
.getTraceHandler().error(
235 "Website not supported: " + searchOn
);
239 } else if (search
== null) {
241 } else if (page
!= null && page
== -1) {
243 page
= Integer
.parseInt(args
[i
]);
244 } catch (Exception e
) {
247 } else if (item
!= null && item
== -1) {
249 item
= Integer
.parseInt(args
[i
]);
250 } catch (Exception e
) {
253 } else if (page
== null || item
== null) {
254 if (page
== null && "page".equals(args
[i
])) {
256 } else if (item
== null && "item".equals(args
[i
])) {
266 if (searchOn
== null) {
267 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
269 if (searchOn
== null) {
270 Instance
.getTraceHandler().error(
271 "Website not known: <" + args
[i
] + ">");
275 if (BasicSearchable
.getSearchable(searchOn
) == null) {
276 Instance
.getTraceHandler().error(
277 "Website not supported: " + searchOn
);
280 } else if (page
== null && item
== null) {
281 if ("page".equals(args
[i
])) {
283 } else if ("item".equals(args
[i
])) {
287 int index
= Integer
.parseInt(args
[i
]);
289 } catch (NumberFormatException e
) {
290 Instance
.getTraceHandler().error(
291 "Invalid tag index: " + args
[i
]);
295 } else if (page
!= null && page
== -1) {
297 page
= Integer
.parseInt(args
[i
]);
298 } catch (Exception e
) {
301 } else if (item
!= null && item
== -1) {
303 item
= Integer
.parseInt(args
[i
]);
304 } catch (Exception e
) {
307 } else if (page
== null || item
== null) {
308 if (page
== null && "page".equals(args
[i
])) {
310 } else if (item
== null && "item".equals(args
[i
])) {
323 exitCode
= setReaderType(args
[i
]);
324 action
= MainAction
.START
;
327 exitCode
= 255; // not supposed to be selected by user
330 exitCode
= 255; // no arguments for this option
333 exitCode
= 255; // no arguments for this option
336 exitCode
= 255; // no arguments for this option
341 } else if (host
== null) {
343 } else if (port
== null) {
344 port
= Integer
.parseInt(args
[i
]);
346 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
347 lib
= new CacheLibrary(Instance
.getRemoteDir(host
), lib
);
349 BasicReader
.setDefaultLibrary(lib
);
351 action
= MainAction
.START
;
359 final Progress mainProgress
= new Progress(0, 80);
360 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
361 private int current
= mainProgress
.getMin();
364 public void progress(Progress progress
, String name
) {
365 int diff
= progress
.getProgress() - current
;
371 StringBuilder builder
= new StringBuilder();
372 for (int i
= 0; i
< diff
; i
++) {
376 System
.err
.print(builder
.toString());
378 if (progress
.isDone()) {
379 System
.err
.println("");
383 Progress pg
= new Progress();
384 mainProgress
.addProgress(pg
, mainProgress
.getMax());
386 VersionCheck updates
= VersionCheck
.check();
387 if (updates
.isNewVersionAvailable()) {
388 // Sent to syserr so not to cause problem if one tries to capture a
389 // story content in text mode
391 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
392 System
.err
.println("");
393 for (Version v
: updates
.getNewer()) {
394 System
.err
.println("\tVersion " + v
);
395 System
.err
.println("\t-------------");
396 System
.err
.println("");
397 for (String it
: updates
.getChanges().get(v
)) {
398 System
.err
.println("\t- " + it
);
400 System
.err
.println("");
407 exitCode
= imprt(urlString
, pg
);
408 updates
.ok(); // we consider it read
411 exitCode
= export(luid
, sourceString
, target
, pg
);
412 updates
.ok(); // we consider it read
415 exitCode
= convert(urlString
, sourceString
, target
,
416 plusInfo
== null ?
false : plusInfo
, pg
);
417 updates
.ok(); // we consider it read
420 if (BasicReader
.getReader() == null) {
421 Instance
.getTraceHandler()
422 .error(new Exception(
423 "No reader type has been configured"));
427 exitCode
= list(sourceString
);
431 Instance
.getLibrary().changeSource(luid
, sourceString
, pg
);
432 } catch (IOException e1
) {
433 Instance
.getTraceHandler().error(e1
);
439 Instance
.getLibrary().changeTitle(luid
, titleString
, pg
);
440 } catch (IOException e1
) {
441 Instance
.getTraceHandler().error(e1
);
447 Instance
.getLibrary().changeAuthor(luid
, authorString
, pg
);
448 } catch (IOException e1
) {
449 Instance
.getTraceHandler().error(e1
);
454 if (BasicReader
.getReader() == null) {
455 Instance
.getTraceHandler()
456 .error(new Exception(
457 "No reader type has been configured"));
461 exitCode
= read(luid
, chapString
, true);
464 if (BasicReader
.getReader() == null) {
465 Instance
.getTraceHandler()
466 .error(new Exception(
467 "No reader type has been configured"));
471 exitCode
= read(urlString
, chapString
, false);
474 page
= page
== null ?
1 : page
;
476 Instance
.getTraceHandler().error("Incorrect page number");
481 item
= item
== null ?
0 : item
;
483 Instance
.getTraceHandler().error("Incorrect item number");
488 if (BasicReader
.getReader() == null) {
489 Instance
.getTraceHandler()
490 .error(new Exception(
491 "No reader type has been configured"));
497 if (searchOn
== null) {
498 BasicReader
.getReader().search(true);
499 } else if (search
!= null) {
501 BasicReader
.getReader().search(searchOn
, search
, page
,
506 } catch (IOException e1
) {
507 Instance
.getTraceHandler().error(e1
);
513 if (searchOn
== null) {
518 page
= page
== null ?
1 : page
;
520 Instance
.getTraceHandler().error("Incorrect page number");
525 item
= item
== null ?
0 : item
;
527 Instance
.getTraceHandler().error("Incorrect item number");
532 if (BasicReader
.getReader() == null) {
533 Instance
.getTraceHandler()
534 .error(new Exception(
535 "No reader type has been configured"));
541 BasicReader
.getReader().searchTag(searchOn
, page
, item
,
542 true, tags
.toArray(new Integer
[] {}));
543 } catch (IOException e1
) {
544 Instance
.getTraceHandler().error(e1
);
557 .println(String
.format("Fanfix version %s"
558 + "%nhttps://github.com/nikiroo/fanfix/"
559 + "%n\tWritten by Nikiroo",
560 Version
.getCurrentVersion()));
561 updates
.ok(); // we consider it read
564 if (BasicReader
.getReader() == null) {
565 Instance
.getTraceHandler()
566 .error(new Exception(
567 "No reader type has been configured"));
572 BasicReader
.getReader().browse(null);
573 } catch (IOException e
) {
574 Instance
.getTraceHandler().error(e
);
579 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
580 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
582 System
.err
.println("No port configured in the config file");
587 ServerObject server
= new RemoteLibraryServer(key
, port
);
588 server
.setTraceHandler(Instance
.getTraceHandler());
590 } catch (IOException e
) {
591 Instance
.getTraceHandler().error(e
);
595 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
596 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
598 System
.err
.println("No port configured in the config file");
603 new RemoteLibrary(key
, host
, port
).exit();
604 } catch (SSLException e
) {
605 Instance
.getTraceHandler().error(
606 "Bad access key for remote library");
608 } catch (IOException e
) {
609 Instance
.getTraceHandler().error(e
);
615 exitCode
= 255; // should not be reachable (REMOTE -> START)
621 Instance
.getTempFiles().close();
622 } catch (IOException e
) {
623 Instance
.getTraceHandler()
624 .error(new IOException(
625 "Cannot dispose of the temporary files", e
));
628 if (exitCode
== 255) {
632 System
.exit(exitCode
);
636 * Import the given resource into the {@link LocalLibrary}.
639 * the resource to import
641 * the optional progress reporter
643 * @return the exit return code (0 = success)
645 public static int imprt(String urlString
, Progress pg
) {
647 Story story
= Instance
.getLibrary().imprt(
648 BasicReader
.getUrl(urlString
), pg
);
649 System
.out
.println(story
.getMeta().getLuid() + ": \""
650 + story
.getMeta().getTitle() + "\" imported.");
651 } catch (IOException e
) {
652 Instance
.getTraceHandler().error(e
);
660 * Export the {@link Story} from the {@link LocalLibrary} to the given
666 * the {@link OutputType} to use
670 * the optional progress reporter
672 * @return the exit return code (0 = success)
674 public static int export(String luid
, String typeString
, String target
,
676 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
678 Instance
.getTraceHandler().error(
679 new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
684 Instance
.getLibrary().export(luid
, type
, target
, pg
);
685 } catch (IOException e
) {
686 Instance
.getTraceHandler().error(e
);
694 * List the stories of the given source from the {@link LocalLibrary}
695 * (unless NULL is passed, in which case all stories will be listed).
698 * the source to list the known stories of, or NULL to list all
701 * @return the exit return code (0 = success)
703 private static int list(String source
) {
704 BasicReader
.setDefaultReaderType(ReaderType
.CLI
);
706 BasicReader
.getReader().browse(source
);
707 } catch (IOException e
) {
708 Instance
.getTraceHandler().error(e
);
716 * Start the current reader for this {@link Story}.
719 * the LUID of the {@link Story} in the {@link LocalLibrary}
720 * <b>or</b> the {@link Story} {@link URL}
722 * which {@link Chapter} to read (starting at 1), or NULL to get
723 * the {@link Story} description
725 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
728 * @return the exit return code (0 = success)
730 private static int read(String story
, String chapString
, boolean library
) {
732 Reader reader
= BasicReader
.getReader();
734 reader
.setMeta(story
);
736 reader
.setMeta(BasicReader
.getUrl(story
), null);
739 if (chapString
!= null) {
741 reader
.setChapter(Integer
.parseInt(chapString
));
743 } catch (NumberFormatException e
) {
744 Instance
.getTraceHandler().error(
745 new IOException("Chapter number cannot be parsed: "
752 } catch (IOException e
) {
753 Instance
.getTraceHandler().error(e
);
761 * Convert the {@link Story} into another format.
764 * the source {@link Story} to convert
766 * the {@link OutputType} to convert to
770 * TRUE to also export the cover and info file, even if the given
771 * {@link OutputType} does not usually save them
773 * the optional progress reporter
775 * @return the exit return code (0 = success)
777 public static int convert(String urlString
, String typeString
,
778 String target
, boolean infoCover
, Progress pg
) {
781 Instance
.getTraceHandler().trace("Convert: " + urlString
);
782 String sourceName
= urlString
;
784 URL source
= BasicReader
.getUrl(urlString
);
785 sourceName
= source
.toString();
786 if (source
.toString().startsWith("file://")) {
787 sourceName
= sourceName
.substring("file://".length());
790 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
792 Instance
.getTraceHandler().error(
793 new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
,
799 BasicSupport support
= BasicSupport
.getSupport(source
);
801 if (support
!= null) {
802 Instance
.getTraceHandler().trace(
803 "Support found: " + support
.getClass());
804 Progress pgIn
= new Progress();
805 Progress pgOut
= new Progress();
808 pg
.addProgress(pgIn
, 1);
809 pg
.addProgress(pgOut
, 1);
812 Story story
= support
.process(pgIn
);
814 target
= new File(target
).getAbsolutePath();
815 BasicOutput
.getOutput(type
, infoCover
, infoCover
)
816 .process(story
, target
, pgOut
);
817 } catch (IOException e
) {
818 Instance
.getTraceHandler().error(
819 new IOException(trans(StringId
.ERR_SAVING
,
824 Instance
.getTraceHandler().error(
825 new IOException(trans(
826 StringId
.ERR_NOT_SUPPORTED
, source
)));
830 } catch (IOException e
) {
831 Instance
.getTraceHandler().error(
832 new IOException(trans(StringId
.ERR_LOADING
,
837 } catch (MalformedURLException e
) {
838 Instance
.getTraceHandler()
839 .error(new IOException(trans(StringId
.ERR_BAD_URL
,
848 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
851 * the ID to translate
853 * @return the translated result
855 private static String
trans(StringId id
, Object
... params
) {
856 return Instance
.getTrans().getString(id
, params
);
860 * Display the correct syntax of the program to the user to stdout, or an
861 * error message if the syntax used was wrong on stderr.
864 * TRUE to show the syntax help, FALSE to show "syntax error"
866 private static void syntax(boolean showHelp
) {
868 StringBuilder builder
= new StringBuilder();
869 for (SupportType type
: SupportType
.values()) {
870 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
872 builder
.append('\n');
875 String typesIn
= builder
.toString();
876 builder
.setLength(0);
878 for (OutputType type
: OutputType
.values()) {
879 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
880 type
.getDesc(true)));
881 builder
.append('\n');
884 String typesOut
= builder
.toString();
886 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
888 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
893 * Set the default reader type for this session only (it can be changed in
894 * the configuration file, too, but this value will override it).
896 * @param readerTypeString
899 private static int setReaderType(String readerTypeString
) {
901 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
903 BasicReader
.setDefaultReaderType(readerType
);
905 } catch (IllegalArgumentException e
) {
906 Instance
.getTraceHandler().error(
907 new IOException("Unknown reader type: " + readerTypeString
,