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
.SupportType
;
25 import be
.nikiroo
.utils
.Progress
;
26 import be
.nikiroo
.utils
.Version
;
27 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
30 * Main program entry point.
35 private enum MainAction
{
36 IMPORT
, EXPORT
, CONVERT
, READ
, READ_URL
, LIST
, HELP
, SET_READER
, START
, VERSION
, SERVER
, STOP_SERVER
, REMOTE
,
40 * Main program entry point.
42 * Known environment variables:
44 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
45 * {@link String}s when possible</li>
46 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
47 * before taking the usual ones; they will also be saved/updated into this
48 * path when the program starts</li>
49 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
50 * configuration value with 'true'</li>
54 * <li>--import [URL]: import into library</li>
55 * <li>--export [id] [output_type] [target]: export story to target</li>
56 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
58 * <li>--read [id] ([chapter number]): read the given story from the library
60 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
61 * story, without saving it</li>
62 * <li>--list ([type]): list the stories present in the library</li>
63 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
64 * for this command</li>
65 * <li>--version: get the version of the program</li>
66 * <li>--server [key] [port]: start a server on this port</li>
67 * <li>--stop-server [key] [port]: stop the running server on this port if
69 * <li>--remote [key] [host] [port]: use a the given remote library</li>
73 * see method description
75 public static void main(String
[] args
) {
76 String urlString
= null;
78 String sourceString
= null;
79 String chapString
= null;
82 MainAction action
= MainAction
.START
;
83 Boolean plusInfo
= null;
87 boolean noMoreActions
= false;
90 for (int i
= 0; exitCode
== 0 && i
< args
.length
; i
++) {
91 // Action (--) handling:
92 if (!noMoreActions
&& args
[i
].startsWith("--")) {
93 if (args
[i
].equals("--")) {
97 action
= MainAction
.valueOf(args
[i
].substring(2)
98 .toUpperCase().replace("-", "_"));
99 } catch (Exception e
) {
100 Instance
.getTraceHandler().error(
101 new IllegalArgumentException("Unknown action: "
112 if (urlString
== null) {
121 } else if (sourceString
== null) {
122 sourceString
= args
[i
];
123 } else if (target
== null) {
130 if (urlString
== null) {
132 } else if (sourceString
== null) {
133 sourceString
= args
[i
];
134 } else if (target
== null) {
136 } else if (plusInfo
== null) {
137 if ("+info".equals(args
[i
])) {
147 if (sourceString
== null) {
148 sourceString
= args
[i
];
156 } else if (chapString
== null) {
157 chapString
= args
[i
];
163 if (urlString
== null) {
165 } else if (chapString
== null) {
166 chapString
= args
[i
];
175 exitCode
= setReaderType(args
[i
]);
176 action
= MainAction
.START
;
179 exitCode
= 255; // not supposed to be selected by user
182 exitCode
= 255; // no arguments for this option
188 } else if (port
== null) {
189 port
= Integer
.parseInt(args
[i
]);
197 } else if (host
== null) {
199 } else if (port
== null) {
200 port
= Integer
.parseInt(args
[i
]);
202 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
203 lib
= new CacheLibrary(Instance
.getRemoteDir(host
), lib
);
205 BasicReader
.setDefaultLibrary(lib
);
207 action
= MainAction
.START
;
215 final Progress mainProgress
= new Progress(0, 80);
216 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
217 private int current
= mainProgress
.getMin();
220 public void progress(Progress progress
, String name
) {
221 int diff
= progress
.getProgress() - current
;
224 StringBuilder builder
= new StringBuilder();
225 for (int i
= 0; i
< diff
; i
++) {
229 System
.err
.print(builder
.toString());
231 if (progress
.isDone()) {
232 System
.err
.println("");
236 Progress pg
= new Progress();
237 mainProgress
.addProgress(pg
, mainProgress
.getMax());
239 VersionCheck updates
= VersionCheck
.check();
240 if (updates
.isNewVersionAvailable()) {
241 // Sent to syserr so not to cause problem if one tries to capture a
242 // story content in text mode
244 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
245 System
.err
.println("");
246 for (Version v
: updates
.getNewer()) {
247 System
.err
.println("\tVersion " + v
);
248 System
.err
.println("\t-------------");
249 System
.err
.println("");
250 for (String item
: updates
.getChanges().get(v
)) {
251 System
.err
.println("\t- " + item
);
253 System
.err
.println("");
257 if (exitCode
!= 255) {
260 exitCode
= imprt(urlString
, pg
);
261 updates
.ok(); // we consider it read
264 exitCode
= export(luid
, sourceString
, target
, pg
);
265 updates
.ok(); // we consider it read
268 exitCode
= convert(urlString
, sourceString
, target
,
269 plusInfo
== null ?
false : plusInfo
, pg
);
270 updates
.ok(); // we consider it read
273 if (BasicReader
.getReader() == null) {
274 Instance
.getTraceHandler()
275 .error(new Exception(
276 "No reader type has been configured"));
280 exitCode
= list(sourceString
);
283 if (BasicReader
.getReader() == null) {
284 Instance
.getTraceHandler()
285 .error(new Exception(
286 "No reader type has been configured"));
290 exitCode
= read(luid
, chapString
, true);
293 if (BasicReader
.getReader() == null) {
294 Instance
.getTraceHandler()
295 .error(new Exception(
296 "No reader type has been configured"));
300 exitCode
= read(urlString
, chapString
, false);
311 .println(String
.format("Fanfix version %s"
312 + "%nhttps://github.com/nikiroo/fanfix/"
313 + "%n\tWritten by Nikiroo",
314 Version
.getCurrentVersion()));
315 updates
.ok(); // we consider it read
318 if (BasicReader
.getReader() == null) {
319 Instance
.getTraceHandler()
320 .error(new Exception(
321 "No reader type has been configured"));
325 BasicReader
.getReader().browse(null);
333 ServerObject server
= new RemoteLibraryServer(key
, port
);
334 server
.setTraceHandler(Instance
.getTraceHandler());
336 } catch (IOException e
) {
337 Instance
.getTraceHandler().error(e
);
346 new RemoteLibrary(key
, host
, port
).exit();
349 exitCode
= 255; // should not be reachable (REMOTE -> START)
354 // We cannot do it when in GUI mode, because it is async...
355 // So if we close the temp files before it is actually used,
356 // we have a problem...
357 // TODO: close it at the correct time (for now, finalize try to do it)
360 Instance
.getTempFiles().close();
361 } catch (IOException e
) {
362 Instance
.getTraceHandler().error(
364 "Cannot dispose of the temporary files", e
));
368 if (exitCode
== 255) {
373 System
.exit(exitCode
);
378 * Import the given resource into the {@link LocalLibrary}.
381 * the resource to import
383 * the optional progress reporter
385 * @return the exit return code (0 = success)
387 public static int imprt(String urlString
, Progress pg
) {
389 Story story
= Instance
.getLibrary().imprt(
390 BasicReader
.getUrl(urlString
), pg
);
391 System
.out
.println(story
.getMeta().getLuid() + ": \""
392 + story
.getMeta().getTitle() + "\" imported.");
393 } catch (IOException e
) {
394 Instance
.getTraceHandler().error(e
);
402 * Export the {@link Story} from the {@link LocalLibrary} to the given
408 * the {@link OutputType} to use
412 * the optional progress reporter
414 * @return the exit return code (0 = success)
416 public static int export(String luid
, String typeString
, String target
,
418 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
420 Instance
.getTraceHandler().error(
421 new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
426 Instance
.getLibrary().export(luid
, type
, target
, pg
);
427 } catch (IOException e
) {
428 Instance
.getTraceHandler().error(e
);
436 * List the stories of the given source from the {@link LocalLibrary}
437 * (unless NULL is passed, in which case all stories will be listed).
440 * the source to list the known stories of, or NULL to list all
443 * @return the exit return code (0 = success)
445 private static int list(String source
) {
446 List
<MetaData
> stories
;
447 stories
= BasicReader
.getReader().getLibrary().getListBySource(source
);
449 for (MetaData story
: stories
) {
451 if (story
.getAuthor() != null && !story
.getAuthor().isEmpty()) {
452 author
= " (" + story
.getAuthor() + ")";
455 System
.out
.println(story
.getLuid() + ": " + story
.getTitle()
462 * Start the CLI reader for this {@link Story}.
465 * the LUID of the {@link Story} in the {@link LocalLibrary}
466 * <b>or</b> the {@link Story} {@link URL}
468 * which {@link Chapter} to read (starting at 1), or NULL to get
469 * the {@link Story} description
471 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
474 * @return the exit return code (0 = success)
476 private static int read(String story
, String chapString
, boolean library
) {
478 Reader reader
= BasicReader
.getReader();
480 reader
.setMeta(story
);
482 reader
.setMeta(BasicReader
.getUrl(story
), null);
485 if (chapString
!= null) {
487 reader
.setChapter(Integer
.parseInt(chapString
));
489 } catch (NumberFormatException e
) {
490 Instance
.getTraceHandler().error(
491 new IOException("Chapter number cannot be parsed: "
498 } catch (IOException e
) {
499 Instance
.getTraceHandler().error(e
);
507 * Convert the {@link Story} into another format.
510 * the source {@link Story} to convert
512 * the {@link OutputType} to convert to
516 * TRUE to also export the cover and info file, even if the given
517 * {@link OutputType} does not usually save them
519 * the optional progress reporter
521 * @return the exit return code (0 = success)
523 public static int convert(String urlString
, String typeString
,
524 String target
, boolean infoCover
, Progress pg
) {
527 String sourceName
= urlString
;
529 URL source
= BasicReader
.getUrl(urlString
);
530 sourceName
= source
.toString();
531 if (source
.toString().startsWith("file://")) {
532 sourceName
= sourceName
.substring("file://".length());
535 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
537 Instance
.getTraceHandler().error(
538 new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
,
544 BasicSupport support
= BasicSupport
.getSupport(source
);
546 if (support
!= null) {
547 Progress pgIn
= new Progress();
548 Progress pgOut
= new Progress();
551 pg
.addProgress(pgIn
, 1);
552 pg
.addProgress(pgOut
, 1);
555 Story story
= support
.process(pgIn
);
557 target
= new File(target
).getAbsolutePath();
558 BasicOutput
.getOutput(type
, infoCover
, infoCover
)
559 .process(story
, target
, pgOut
);
560 } catch (IOException e
) {
561 Instance
.getTraceHandler().error(
562 new IOException(trans(StringId
.ERR_SAVING
,
567 Instance
.getTraceHandler().error(
568 new IOException(trans(
569 StringId
.ERR_NOT_SUPPORTED
, source
)));
573 } catch (IOException e
) {
574 Instance
.getTraceHandler().error(
575 new IOException(trans(StringId
.ERR_LOADING
,
580 } catch (MalformedURLException e
) {
581 Instance
.getTraceHandler()
582 .error(new IOException(trans(StringId
.ERR_BAD_URL
,
591 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
594 * the ID to translate
596 * @return the translated result
598 private static String
trans(StringId id
, Object
... params
) {
599 return Instance
.getTrans().getString(id
, params
);
603 * Display the correct syntax of the program to the user to stdout, or an
604 * error message if the syntax used was wrong on stderr.
607 * TRUE to show the syntax help, FALSE to show "syntax error"
609 private static void syntax(boolean showHelp
) {
611 StringBuilder builder
= new StringBuilder();
612 for (SupportType type
: SupportType
.values()) {
613 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
615 builder
.append('\n');
618 String typesIn
= builder
.toString();
619 builder
.setLength(0);
621 for (OutputType type
: OutputType
.values()) {
622 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
623 type
.getDesc(true)));
624 builder
.append('\n');
627 String typesOut
= builder
.toString();
629 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
631 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
636 * Set the default reader type for this session only (it can be changed in
637 * the configuration file, too, but this value will override it).
639 * @param readerTypeString
642 private static int setReaderType(String readerTypeString
) {
644 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
646 BasicReader
.setDefaultReaderType(readerType
);
648 } catch (IllegalArgumentException e
) {
649 Instance
.getTraceHandler().error(
650 new IOException("Unknown reader type: " + readerTypeString
,