1 package be
.nikiroo
.fanfix
;
4 import java
.io
.IOException
;
5 import java
.net
.MalformedURLException
;
9 import be
.nikiroo
.fanfix
.bundles
.StringId
;
10 import be
.nikiroo
.fanfix
.data
.Chapter
;
11 import be
.nikiroo
.fanfix
.data
.MetaData
;
12 import be
.nikiroo
.fanfix
.data
.Story
;
13 import be
.nikiroo
.fanfix
.library
.BasicLibrary
;
14 import be
.nikiroo
.fanfix
.library
.CacheLibrary
;
15 import be
.nikiroo
.fanfix
.library
.LocalLibrary
;
16 import be
.nikiroo
.fanfix
.library
.RemoteLibrary
;
17 import be
.nikiroo
.fanfix
.library
.RemoteLibraryServer
;
18 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
19 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
20 import be
.nikiroo
.fanfix
.reader
.BasicReader
;
21 import be
.nikiroo
.fanfix
.reader
.Reader
;
22 import be
.nikiroo
.fanfix
.reader
.Reader
.ReaderType
;
23 import be
.nikiroo
.fanfix
.supported
.BasicSupport
;
24 import be
.nikiroo
.fanfix
.supported
.BasicSupport
.SupportType
;
25 import be
.nikiroo
.utils
.Progress
;
26 import be
.nikiroo
.utils
.Version
;
27 import be
.nikiroo
.utils
.serial
.server
.ConnectActionClientObject
;
28 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
31 * Main program entry point.
36 private enum MainAction
{
37 IMPORT
, EXPORT
, CONVERT
, READ
, READ_URL
, LIST
, HELP
, SET_READER
, START
, VERSION
, SERVER
, STOP_SERVER
, REMOTE
,
41 * Main program entry point.
43 * Known environment variables:
45 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
46 * {@link String}s when possible</li>
47 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
48 * before taking the usual ones; they will also be saved/updated into this
49 * path when the program starts</li>
50 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
51 * configuration value with 'true'</li>
55 * <li>--import [URL]: import into library</li>
56 * <li>--export [id] [output_type] [target]: export story to target</li>
57 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
59 * <li>--read [id] ([chapter number]): read the given story from the library
61 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
62 * story, without saving it</li>
63 * <li>--list ([type]): list the stories present in the library</li>
64 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
65 * for this command</li>
66 * <li>--version: get the version of the program</li>
67 * <li>--server [key] [port]: start a server on this port</li>
68 * <li>--stop-server [key] [port]: stop the running server on this port if
70 * <li>--remote [key] [host] [port]: use a the given remote library</li>
74 * see method description
76 public static void main(String
[] args
) {
77 String urlString
= null;
79 String sourceString
= null;
80 String chapString
= null;
83 MainAction action
= MainAction
.START
;
84 Boolean plusInfo
= null;
88 boolean noMoreActions
= false;
91 for (int i
= 0; exitCode
== 0 && i
< args
.length
; i
++) {
92 // Action (--) handling:
93 if (!noMoreActions
&& args
[i
].startsWith("--")) {
94 if (args
[i
].equals("--")) {
98 action
= MainAction
.valueOf(args
[i
].substring(2)
99 .toUpperCase().replace("-", "_"));
100 } catch (Exception e
) {
101 Instance
.getTraceHandler().error(
102 new IllegalArgumentException("Unknown action: "
113 if (urlString
== null) {
122 } else if (sourceString
== null) {
123 sourceString
= args
[i
];
124 } else if (target
== null) {
131 if (urlString
== null) {
133 } else if (sourceString
== null) {
134 sourceString
= args
[i
];
135 } else if (target
== null) {
137 } else if (plusInfo
== null) {
138 if ("+info".equals(args
[i
])) {
148 if (sourceString
== null) {
149 sourceString
= args
[i
];
157 } else if (chapString
== null) {
158 chapString
= args
[i
];
164 if (urlString
== null) {
166 } else if (chapString
== null) {
167 chapString
= args
[i
];
176 exitCode
= setReaderType(args
[i
]);
177 action
= MainAction
.START
;
180 exitCode
= 255; // not supposed to be selected by user
183 exitCode
= 255; // no arguments for this option
189 } else if (port
== null) {
190 port
= Integer
.parseInt(args
[i
]);
198 } else if (host
== null) {
200 } else if (port
== null) {
201 port
= Integer
.parseInt(args
[i
]);
203 File remoteCacheDir
= Instance
.getRemoteDir(host
);
204 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
205 lib
= new CacheLibrary(remoteCacheDir
, lib
);
207 BasicReader
.setDefaultLibrary(lib
);
209 action
= MainAction
.START
;
217 final Progress mainProgress
= new Progress(0, 80);
218 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
219 private int current
= mainProgress
.getMin();
222 public void progress(Progress progress
, String name
) {
223 int diff
= progress
.getProgress() - current
;
226 StringBuilder builder
= new StringBuilder();
227 for (int i
= 0; i
< diff
; i
++) {
231 System
.err
.print(builder
.toString());
233 if (progress
.isDone()) {
234 System
.err
.println("");
238 Progress pg
= new Progress();
239 mainProgress
.addProgress(pg
, mainProgress
.getMax());
241 VersionCheck updates
= VersionCheck
.check();
242 if (updates
.isNewVersionAvailable()) {
243 // Sent to syserr so not to cause problem if one tries to capture a
244 // story content in text mode
246 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
247 System
.err
.println("");
248 for (Version v
: updates
.getNewer()) {
249 System
.err
.println("\tVersion " + v
);
250 System
.err
.println("\t-------------");
251 System
.err
.println("");
252 for (String item
: updates
.getChanges().get(v
)) {
253 System
.err
.println("\t- " + item
);
255 System
.err
.println("");
259 if (exitCode
!= 255) {
262 exitCode
= imprt(urlString
, pg
);
263 updates
.ok(); // we consider it read
266 exitCode
= export(luid
, sourceString
, target
, pg
);
267 updates
.ok(); // we consider it read
270 exitCode
= convert(urlString
, sourceString
, target
,
271 plusInfo
== null ?
false : plusInfo
, pg
);
272 updates
.ok(); // we consider it read
275 if (BasicReader
.getReader() == null) {
276 Instance
.getTraceHandler()
277 .error(new Exception(
278 "No reader type has been configured"));
282 exitCode
= list(sourceString
);
285 if (BasicReader
.getReader() == null) {
286 Instance
.getTraceHandler()
287 .error(new Exception(
288 "No reader type has been configured"));
292 exitCode
= read(luid
, chapString
, true);
295 if (BasicReader
.getReader() == null) {
296 Instance
.getTraceHandler()
297 .error(new Exception(
298 "No reader type has been configured"));
302 exitCode
= read(urlString
, chapString
, false);
313 .println(String
.format("Fanfix version %s"
314 + "\nhttps://github.com/nikiroo/fanfix/"
315 + "\n\tWritten by Nikiroo",
316 Version
.getCurrentVersion()));
317 updates
.ok(); // we consider it read
320 if (BasicReader
.getReader() == null) {
321 Instance
.getTraceHandler()
322 .error(new Exception(
323 "No reader type has been configured"));
327 BasicReader
.getReader().browse(null);
335 ServerObject server
= new RemoteLibraryServer(key
, port
);
336 server
.setTraceHandler(Instance
.getTraceHandler());
338 } catch (IOException e
) {
339 Instance
.getTraceHandler().error(e
);
349 final String fkey
= key
;
350 new ConnectActionClientObject(host
, port
, true) {
352 public void action(Version serverVersion
)
355 send(new Object
[] { fkey
, "EXIT" });
356 } catch (Exception e
) {
357 Instance
.getTraceHandler().error(e
);
361 } catch (IOException e
) {
362 Instance
.getTraceHandler().error(e
);
366 exitCode
= 255; // should not be reachable (REMOTE -> START)
371 if (exitCode
== 255) {
376 System
.exit(exitCode
);
381 * Import the given resource into the {@link LocalLibrary}.
384 * the resource to import
386 * the optional progress reporter
388 * @return the exit return code (0 = success)
390 public static int imprt(String urlString
, Progress pg
) {
392 Story story
= Instance
.getLibrary().imprt(
393 BasicReader
.getUrl(urlString
), pg
);
394 System
.out
.println(story
.getMeta().getLuid() + ": \""
395 + story
.getMeta().getTitle() + "\" imported.");
396 } catch (IOException e
) {
397 Instance
.getTraceHandler().error(e
);
405 * Export the {@link Story} from the {@link LocalLibrary} to the given
411 * the {@link OutputType} to use
415 * the optional progress reporter
417 * @return the exit return code (0 = success)
419 public static int export(String luid
, String typeString
, String target
,
421 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
423 Instance
.getTraceHandler().error(
424 new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
429 Instance
.getLibrary().export(luid
, type
, target
, pg
);
430 } catch (IOException e
) {
431 Instance
.getTraceHandler().error(e
);
439 * List the stories of the given source from the {@link LocalLibrary}
440 * (unless NULL is passed, in which case all stories will be listed).
443 * the source to list the known stories of, or NULL to list all
446 * @return the exit return code (0 = success)
448 private static int list(String source
) {
449 List
<MetaData
> stories
;
450 stories
= BasicReader
.getReader().getLibrary().getListBySource(source
);
452 for (MetaData story
: stories
) {
454 if (story
.getAuthor() != null && !story
.getAuthor().isEmpty()) {
455 author
= " (" + story
.getAuthor() + ")";
458 System
.out
.println(story
.getLuid() + ": " + story
.getTitle()
465 * Start the CLI reader for this {@link Story}.
468 * the LUID of the {@link Story} in the {@link LocalLibrary}
469 * <b>or</b> the {@link Story} {@link URL}
471 * which {@link Chapter} to read (starting at 1), or NULL to get
472 * the {@link Story} description
474 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
477 * @return the exit return code (0 = success)
479 private static int read(String story
, String chapString
, boolean library
) {
481 Reader reader
= BasicReader
.getReader();
483 reader
.setMeta(story
);
485 reader
.setMeta(BasicReader
.getUrl(story
), null);
488 if (chapString
!= null) {
490 reader
.setChapter(Integer
.parseInt(chapString
));
492 } catch (NumberFormatException e
) {
493 Instance
.getTraceHandler().error(
494 new IOException("Chapter number cannot be parsed: "
501 } catch (IOException e
) {
502 Instance
.getTraceHandler().error(e
);
510 * Convert the {@link Story} into another format.
513 * the source {@link Story} to convert
515 * the {@link OutputType} to convert to
519 * TRUE to also export the cover and info file, even if the given
520 * {@link OutputType} does not usually save them
522 * the optional progress reporter
524 * @return the exit return code (0 = success)
526 private static int convert(String urlString
, String typeString
,
527 String target
, boolean infoCover
, Progress pg
) {
530 String sourceName
= urlString
;
532 URL source
= BasicReader
.getUrl(urlString
);
533 sourceName
= source
.toString();
534 if (source
.toString().startsWith("file://")) {
535 sourceName
= sourceName
.substring("file://".length());
538 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
540 Instance
.getTraceHandler().error(
541 new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
,
547 BasicSupport support
= BasicSupport
.getSupport(source
);
549 if (support
!= null) {
550 Progress pgIn
= new Progress();
551 Progress pgOut
= new Progress();
554 pg
.addProgress(pgIn
, 1);
555 pg
.addProgress(pgOut
, 1);
558 Story story
= support
.process(source
, pgIn
);
560 target
= new File(target
).getAbsolutePath();
561 BasicOutput
.getOutput(type
, infoCover
).process(
562 story
, target
, pgOut
);
563 } catch (IOException e
) {
564 Instance
.getTraceHandler().error(
565 new IOException(trans(StringId
.ERR_SAVING
,
570 Instance
.getTraceHandler().error(
571 new IOException(trans(
572 StringId
.ERR_NOT_SUPPORTED
, source
)));
576 } catch (IOException e
) {
577 Instance
.getTraceHandler().error(
578 new IOException(trans(StringId
.ERR_LOADING
,
583 } catch (MalformedURLException e
) {
584 Instance
.getTraceHandler()
585 .error(new IOException(trans(StringId
.ERR_BAD_URL
,
594 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
597 * the ID to translate
599 * @return the translated result
601 private static String
trans(StringId id
, Object
... params
) {
602 return Instance
.getTrans().getString(id
, params
);
606 * Display the correct syntax of the program to the user to stdout, or an
607 * error message if the syntax used was wrong on stderr.
610 * TRUE to show the syntax help, FALSE to show "syntax error"
612 private static void syntax(boolean showHelp
) {
614 StringBuilder builder
= new StringBuilder();
615 for (SupportType type
: SupportType
.values()) {
616 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
618 builder
.append('\n');
621 String typesIn
= builder
.toString();
622 builder
.setLength(0);
624 for (OutputType type
: OutputType
.values()) {
625 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
626 type
.getDesc(true)));
627 builder
.append('\n');
630 String typesOut
= builder
.toString();
632 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
634 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
639 * Set the default reader type for this session only (it can be changed in
640 * the configuration file, too, but this value will override it).
642 * @param readerTypeString
645 private static int setReaderType(String readerTypeString
) {
647 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
649 BasicReader
.setDefaultReaderType(readerType
);
651 } catch (IllegalArgumentException e
) {
652 Instance
.getTraceHandler().error(
653 new IOException("Unknown reader type: " + readerTypeString
,