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
.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
.Reader
;
26 import be
.nikiroo
.fanfix
.reader
.Reader
.ReaderType
;
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
.serial
.server
.ServerObject
;
35 * Main program entry point.
40 private enum MainAction
{
41 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
45 * Main program entry point.
47 * Known environment variables:
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>
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
63 * <li>--read [id] ([chapter number]): read the given story from the library
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>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
80 * for this command</li>
81 * <li>--version: get the version of the program</li>
82 * <li>--server: start the server mode (see config file for parameters)</li>
83 * <li>--stop-server: stop the running server on this port if any</li>
84 * <li>--remote [key] [host] [port]: use a the given remote library</li>
88 * see method description
90 public static void main(String
[] args
) {
91 // Only one line, but very important:
94 String urlString
= null;
96 String sourceString
= null;
97 String titleString
= null;
98 String authorString
= null;
99 String chapString
= null;
100 String target
= null;
102 MainAction action
= MainAction
.START
;
103 Boolean plusInfo
= null;
106 SupportType searchOn
= null;
107 String search
= null;
108 List
<Integer
> tags
= new ArrayList
<Integer
>();
112 boolean noMoreActions
= false;
115 for (int i
= 0; exitCode
== 0 && i
< args
.length
; i
++) {
116 // Action (--) handling:
117 if (!noMoreActions
&& args
[i
].startsWith("--")) {
118 if (args
[i
].equals("--")) {
119 noMoreActions
= true;
122 action
= MainAction
.valueOf(args
[i
].substring(2)
123 .toUpperCase().replace("-", "_"));
124 } catch (Exception e
) {
125 Instance
.getTraceHandler().error(
126 new IllegalArgumentException("Unknown action: "
137 if (urlString
== null) {
146 } else if (sourceString
== null) {
147 sourceString
= args
[i
];
148 } else if (target
== null) {
155 if (urlString
== null) {
157 } else if (sourceString
== null) {
158 sourceString
= args
[i
];
159 } else if (target
== null) {
161 } else if (plusInfo
== null) {
162 if ("+info".equals(args
[i
])) {
172 if (sourceString
== null) {
173 sourceString
= args
[i
];
181 } else if (sourceString
== null) {
182 sourceString
= args
[i
];
190 } else if (sourceString
== null) {
191 titleString
= args
[i
];
199 } else if (sourceString
== null) {
200 authorString
= args
[i
];
208 } else if (chapString
== null) {
209 chapString
= args
[i
];
215 if (urlString
== null) {
217 } else if (chapString
== null) {
218 chapString
= args
[i
];
224 if (searchOn
== null) {
225 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
227 if (searchOn
== null) {
228 Instance
.getTraceHandler().error(
229 "Website not known: <" + args
[i
] + ">");
234 if (BasicSearchable
.getSearchable(searchOn
) == null) {
235 Instance
.getTraceHandler().error(
236 "Website not supported: " + searchOn
);
240 } else if (search
== null) {
242 } else if (page
!= null && page
== -1) {
244 page
= Integer
.parseInt(args
[i
]);
245 } catch (Exception e
) {
248 } else if (item
!= null && item
== -1) {
250 item
= Integer
.parseInt(args
[i
]);
251 } catch (Exception e
) {
254 } else if (page
== null || item
== null) {
255 if (page
== null && "page".equals(args
[i
])) {
257 } else if (item
== null && "item".equals(args
[i
])) {
267 if (searchOn
== null) {
268 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
270 if (searchOn
== null) {
271 Instance
.getTraceHandler().error(
272 "Website not known: <" + args
[i
] + ">");
276 if (BasicSearchable
.getSearchable(searchOn
) == null) {
277 Instance
.getTraceHandler().error(
278 "Website not supported: " + searchOn
);
281 } else if (page
== null && item
== null) {
282 if ("page".equals(args
[i
])) {
284 } else if ("item".equals(args
[i
])) {
288 int index
= Integer
.parseInt(args
[i
]);
290 } catch (NumberFormatException e
) {
291 Instance
.getTraceHandler().error(
292 "Invalid tag index: " + args
[i
]);
296 } else if (page
!= null && page
== -1) {
298 page
= Integer
.parseInt(args
[i
]);
299 } catch (Exception e
) {
302 } else if (item
!= null && item
== -1) {
304 item
= Integer
.parseInt(args
[i
]);
305 } catch (Exception e
) {
308 } else if (page
== null || item
== null) {
309 if (page
== null && "page".equals(args
[i
])) {
311 } else if (item
== null && "item".equals(args
[i
])) {
324 exitCode
= setReaderType(args
[i
]);
325 action
= MainAction
.START
;
328 exitCode
= 255; // not supposed to be selected by user
331 exitCode
= 255; // no arguments for this option
334 exitCode
= 255; // no arguments for this option
337 exitCode
= 255; // no arguments for this option
342 } else if (host
== null) {
344 } else if (port
== null) {
345 port
= Integer
.parseInt(args
[i
]);
347 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
348 lib
= new CacheLibrary(Instance
.getRemoteDir(host
), lib
);
350 BasicReader
.setDefaultLibrary(lib
);
352 action
= MainAction
.START
;
360 final Progress mainProgress
= new Progress(0, 80);
361 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
362 private int current
= mainProgress
.getMin();
365 public void progress(Progress progress
, String name
) {
366 int diff
= progress
.getProgress() - current
;
372 StringBuilder builder
= new StringBuilder();
373 for (int i
= 0; i
< diff
; i
++) {
377 System
.err
.print(builder
.toString());
379 if (progress
.isDone()) {
380 System
.err
.println("");
384 Progress pg
= new Progress();
385 mainProgress
.addProgress(pg
, mainProgress
.getMax());
387 VersionCheck updates
= VersionCheck
.check();
388 if (updates
.isNewVersionAvailable()) {
389 // Sent to syserr so not to cause problem if one tries to capture a
390 // story content in text mode
392 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
393 System
.err
.println("");
394 for (Version v
: updates
.getNewer()) {
395 System
.err
.println("\tVersion " + v
);
396 System
.err
.println("\t-------------");
397 System
.err
.println("");
398 for (String it
: updates
.getChanges().get(v
)) {
399 System
.err
.println("\t- " + it
);
401 System
.err
.println("");
408 exitCode
= imprt(urlString
, pg
);
409 updates
.ok(); // we consider it read
412 exitCode
= export(luid
, sourceString
, target
, pg
);
413 updates
.ok(); // we consider it read
416 exitCode
= convert(urlString
, sourceString
, target
,
417 plusInfo
== null ?
false : plusInfo
, pg
);
418 updates
.ok(); // we consider it read
421 if (BasicReader
.getReader() == null) {
422 Instance
.getTraceHandler()
423 .error(new Exception(
424 "No reader type has been configured"));
428 exitCode
= list(sourceString
);
432 Instance
.getLibrary().changeSource(luid
, sourceString
, pg
);
433 } catch (IOException e1
) {
434 Instance
.getTraceHandler().error(e1
);
440 Instance
.getLibrary().changeTitle(luid
, titleString
, pg
);
441 } catch (IOException e1
) {
442 Instance
.getTraceHandler().error(e1
);
448 Instance
.getLibrary().changeAuthor(luid
, authorString
, pg
);
449 } catch (IOException e1
) {
450 Instance
.getTraceHandler().error(e1
);
455 if (BasicReader
.getReader() == null) {
456 Instance
.getTraceHandler()
457 .error(new Exception(
458 "No reader type has been configured"));
462 exitCode
= read(luid
, chapString
, true);
465 if (BasicReader
.getReader() == null) {
466 Instance
.getTraceHandler()
467 .error(new Exception(
468 "No reader type has been configured"));
472 exitCode
= read(urlString
, chapString
, false);
475 page
= page
== null ?
1 : page
;
477 Instance
.getTraceHandler().error("Incorrect page number");
482 item
= item
== null ?
0 : item
;
484 Instance
.getTraceHandler().error("Incorrect item number");
489 if (BasicReader
.getReader() == null) {
490 Instance
.getTraceHandler()
491 .error(new Exception(
492 "No reader type has been configured"));
498 if (searchOn
== null) {
499 BasicReader
.getReader().search(true);
500 } else if (search
!= null) {
502 BasicReader
.getReader().search(searchOn
, search
, page
,
507 } catch (IOException e1
) {
508 Instance
.getTraceHandler().error(e1
);
514 if (searchOn
== null) {
519 page
= page
== null ?
1 : page
;
521 Instance
.getTraceHandler().error("Incorrect page number");
526 item
= item
== null ?
0 : item
;
528 Instance
.getTraceHandler().error("Incorrect item number");
533 if (BasicReader
.getReader() == null) {
534 Instance
.getTraceHandler()
535 .error(new Exception(
536 "No reader type has been configured"));
542 BasicReader
.getReader().searchTag(searchOn
, page
, item
,
543 true, tags
.toArray(new Integer
[] {}));
544 } catch (IOException e1
) {
545 Instance
.getTraceHandler().error(e1
);
558 .println(String
.format("Fanfix version %s"
559 + "%nhttps://github.com/nikiroo/fanfix/"
560 + "%n\tWritten by Nikiroo",
561 Version
.getCurrentVersion()));
562 updates
.ok(); // we consider it read
565 if (BasicReader
.getReader() == null) {
566 Instance
.getTraceHandler()
567 .error(new Exception(
568 "No reader type has been configured"));
573 BasicReader
.getReader().browse(null);
574 } catch (IOException e
) {
575 Instance
.getTraceHandler().error(e
);
580 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
581 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
583 System
.err
.println("No port configured in the config file");
588 ServerObject server
= new RemoteLibraryServer(key
, port
);
589 server
.setTraceHandler(Instance
.getTraceHandler());
591 } catch (IOException e
) {
592 Instance
.getTraceHandler().error(e
);
596 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
597 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
599 System
.err
.println("No port configured in the config file");
604 new RemoteLibrary(key
, host
, port
).exit();
605 } catch (SSLException e
) {
606 Instance
.getTraceHandler().error(
607 "Bad access key for remote library");
609 } catch (IOException e
) {
610 Instance
.getTraceHandler().error(e
);
616 exitCode
= 255; // should not be reachable (REMOTE -> START)
622 Instance
.getTempFiles().close();
623 } catch (IOException e
) {
624 Instance
.getTraceHandler()
625 .error(new IOException(
626 "Cannot dispose of the temporary files", e
));
629 if (exitCode
== 255) {
633 System
.exit(exitCode
);
637 * Import the given resource into the {@link LocalLibrary}.
640 * the resource to import
642 * the optional progress reporter
644 * @return the exit return code (0 = success)
646 public static int imprt(String urlString
, Progress pg
) {
648 MetaData meta
= Instance
.getLibrary().imprt(
649 BasicReader
.getUrl(urlString
), pg
);
650 System
.out
.println(meta
.getLuid() + ": \"" + meta
.getTitle()
652 } catch (IOException e
) {
653 Instance
.getTraceHandler().error(e
);
661 * Export the {@link Story} from the {@link LocalLibrary} to the given
667 * the {@link OutputType} to use
671 * the optional progress reporter
673 * @return the exit return code (0 = success)
675 public static int export(String luid
, String typeString
, String target
,
677 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
679 Instance
.getTraceHandler().error(
680 new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
685 Instance
.getLibrary().export(luid
, type
, target
, pg
);
686 } catch (IOException e
) {
687 Instance
.getTraceHandler().error(e
);
695 * List the stories of the given source from the {@link LocalLibrary}
696 * (unless NULL is passed, in which case all stories will be listed).
699 * the source to list the known stories of, or NULL to list all
702 * @return the exit return code (0 = success)
704 private static int list(String source
) {
705 BasicReader
.setDefaultReaderType(ReaderType
.CLI
);
707 BasicReader
.getReader().browse(source
);
708 } catch (IOException e
) {
709 Instance
.getTraceHandler().error(e
);
717 * Start the current reader for this {@link Story}.
720 * the LUID of the {@link Story} in the {@link LocalLibrary}
721 * <b>or</b> the {@link Story} {@link URL}
723 * which {@link Chapter} to read (starting at 1), or NULL to get
724 * the {@link Story} description
726 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
729 * @return the exit return code (0 = success)
731 private static int read(String story
, String chapString
, boolean library
) {
733 Reader reader
= BasicReader
.getReader();
735 reader
.setMeta(story
);
737 reader
.setMeta(BasicReader
.getUrl(story
), null);
740 if (chapString
!= null) {
742 reader
.setChapter(Integer
.parseInt(chapString
));
744 } catch (NumberFormatException e
) {
745 Instance
.getTraceHandler().error(
746 new IOException("Chapter number cannot be parsed: "
753 } catch (IOException e
) {
754 Instance
.getTraceHandler().error(e
);
762 * Convert the {@link Story} into another format.
765 * the source {@link Story} to convert
767 * the {@link OutputType} to convert to
771 * TRUE to also export the cover and info file, even if the given
772 * {@link OutputType} does not usually save them
774 * the optional progress reporter
776 * @return the exit return code (0 = success)
778 public static int convert(String urlString
, String typeString
,
779 String target
, boolean infoCover
, Progress pg
) {
782 Instance
.getTraceHandler().trace("Convert: " + urlString
);
783 String sourceName
= urlString
;
785 URL source
= BasicReader
.getUrl(urlString
);
786 sourceName
= source
.toString();
787 if (source
.toString().startsWith("file://")) {
788 sourceName
= sourceName
.substring("file://".length());
791 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
793 Instance
.getTraceHandler().error(
794 new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
,
800 BasicSupport support
= BasicSupport
.getSupport(source
);
802 if (support
!= null) {
803 Instance
.getTraceHandler().trace(
804 "Support found: " + support
.getClass());
805 Progress pgIn
= new Progress();
806 Progress pgOut
= new Progress();
809 pg
.addProgress(pgIn
, 1);
810 pg
.addProgress(pgOut
, 1);
813 Story story
= support
.process(pgIn
);
815 target
= new File(target
).getAbsolutePath();
816 BasicOutput
.getOutput(type
, infoCover
, infoCover
)
817 .process(story
, target
, pgOut
);
818 } catch (IOException e
) {
819 Instance
.getTraceHandler().error(
820 new IOException(trans(StringId
.ERR_SAVING
,
825 Instance
.getTraceHandler().error(
826 new IOException(trans(
827 StringId
.ERR_NOT_SUPPORTED
, source
)));
831 } catch (IOException e
) {
832 Instance
.getTraceHandler().error(
833 new IOException(trans(StringId
.ERR_LOADING
,
838 } catch (MalformedURLException e
) {
839 Instance
.getTraceHandler()
840 .error(new IOException(trans(StringId
.ERR_BAD_URL
,
849 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
852 * the ID to translate
854 * @return the translated result
856 private static String
trans(StringId id
, Object
... params
) {
857 return Instance
.getTrans().getString(id
, params
);
861 * Display the correct syntax of the program to the user to stdout, or an
862 * error message if the syntax used was wrong on stderr.
865 * TRUE to show the syntax help, FALSE to show "syntax error"
867 private static void syntax(boolean showHelp
) {
869 StringBuilder builder
= new StringBuilder();
870 for (SupportType type
: SupportType
.values()) {
871 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
873 builder
.append('\n');
876 String typesIn
= builder
.toString();
877 builder
.setLength(0);
879 for (OutputType type
: OutputType
.values()) {
880 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
881 type
.getDesc(true)));
882 builder
.append('\n');
885 String typesOut
= builder
.toString();
887 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
889 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
894 * Set the default reader type for this session only (it can be changed in
895 * the configuration file, too, but this value will override it).
897 * @param readerTypeString
900 private static int setReaderType(String readerTypeString
) {
902 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
904 BasicReader
.setDefaultReaderType(readerType
);
906 } catch (IllegalArgumentException e
) {
907 Instance
.getTraceHandler().error(
908 new IOException("Unknown reader type: " + readerTypeString
,