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
.ConnectActionClient
;
28 import be
.nikiroo
.utils
.serial
.Server
;
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
.syserr(new IllegalArgumentException(
102 "Unknown action: " + args
[i
], e
));
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 File remoteCacheDir
= Instance
.getRemoteDir(host
);
203 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
204 lib
= new CacheLibrary(remoteCacheDir
, lib
);
206 BasicReader
.setDefaultLibrary(lib
);
208 action
= MainAction
.START
;
216 final Progress mainProgress
= new Progress(0, 80);
217 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
218 private int current
= mainProgress
.getMin();
221 public void progress(Progress progress
, String name
) {
222 int diff
= progress
.getProgress() - current
;
225 StringBuilder builder
= new StringBuilder();
226 for (int i
= 0; i
< diff
; i
++) {
230 System
.err
.print(builder
.toString());
232 if (progress
.isDone()) {
233 System
.err
.println("");
237 Progress pg
= new Progress();
238 mainProgress
.addProgress(pg
, mainProgress
.getMax());
240 VersionCheck updates
= VersionCheck
.check();
241 if (updates
.isNewVersionAvailable()) {
242 // Sent to syserr so not to cause problem if one tries to capture a
243 // story content in text mode
245 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
246 System
.err
.println("");
247 for (Version v
: updates
.getNewer()) {
248 System
.err
.println("\tVersion " + v
);
249 System
.err
.println("\t-------------");
250 System
.err
.println("");
251 for (String item
: updates
.getChanges().get(v
)) {
252 System
.err
.println("\t- " + item
);
254 System
.err
.println("");
258 if (exitCode
!= 255) {
261 exitCode
= imprt(urlString
, pg
);
262 updates
.ok(); // we consider it read
265 exitCode
= export(luid
, sourceString
, target
, pg
);
266 updates
.ok(); // we consider it read
269 exitCode
= convert(urlString
, sourceString
, target
,
270 plusInfo
== null ?
false : plusInfo
, pg
);
271 updates
.ok(); // we consider it read
274 if (BasicReader
.getReader() == null) {
275 Instance
.syserr(new Exception(
276 "No reader type has been configured"));
280 exitCode
= list(sourceString
);
283 if (BasicReader
.getReader() == null) {
284 Instance
.syserr(new Exception(
285 "No reader type has been configured"));
289 exitCode
= read(luid
, chapString
, true);
292 if (BasicReader
.getReader() == null) {
293 Instance
.syserr(new Exception(
294 "No reader type has been configured"));
298 exitCode
= read(urlString
, chapString
, false);
309 .println(String
.format("Fanfix version %s"
310 + "\nhttps://github.com/nikiroo/fanfix/"
311 + "\n\tWritten by Nikiroo",
312 Version
.getCurrentVersion()));
313 updates
.ok(); // we consider it read
316 if (BasicReader
.getReader() == null) {
317 Instance
.syserr(new Exception(
318 "No reader type has been configured"));
322 BasicReader
.getReader().browse(null);
330 Server server
= new RemoteLibraryServer(key
, port
);
332 System
.out
.println("Remote server started on: " + port
);
333 } catch (IOException e
) {
344 final String fkey
= key
;
345 new ConnectActionClient(host
, port
, true) {
347 public void action(Version serverVersion
)
350 send(new Object
[] { fkey
, "EXIT" });
351 } catch (Exception e
) {
356 } catch (IOException e
) {
361 exitCode
= 255; // should not be reachable (REMOTE -> START)
366 if (exitCode
== 255) {
371 System
.exit(exitCode
);
376 * Import the given resource into the {@link LocalLibrary}.
379 * the resource to import
381 * the optional progress reporter
383 * @return the exit return code (0 = success)
385 public static int imprt(String urlString
, Progress pg
) {
387 Story story
= Instance
.getLibrary().imprt(
388 BasicReader
.getUrl(urlString
), pg
);
389 System
.out
.println(story
.getMeta().getLuid() + ": \""
390 + story
.getMeta().getTitle() + "\" imported.");
391 } catch (IOException e
) {
400 * Export the {@link Story} from the {@link LocalLibrary} to the given
406 * the {@link OutputType} to use
410 * the optional progress reporter
412 * @return the exit return code (0 = success)
414 public static int export(String luid
, String typeString
, String target
,
416 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
418 Instance
.syserr(new Exception(trans(StringId
.OUTPUT_DESC
,
424 Instance
.getLibrary().export(luid
, type
, target
, pg
);
425 } catch (IOException e
) {
434 * List the stories of the given source from the {@link LocalLibrary}
435 * (unless NULL is passed, in which case all stories will be listed).
438 * the source to list the known stories of, or NULL to list all
441 * @return the exit return code (0 = success)
443 private static int list(String source
) {
444 List
<MetaData
> stories
;
445 stories
= BasicReader
.getReader().getLibrary().getListBySource(source
);
447 for (MetaData story
: stories
) {
449 if (story
.getAuthor() != null && !story
.getAuthor().isEmpty()) {
450 author
= " (" + story
.getAuthor() + ")";
453 System
.out
.println(story
.getLuid() + ": " + story
.getTitle()
460 * Start the CLI reader for this {@link Story}.
463 * the LUID of the {@link Story} in the {@link LocalLibrary}
464 * <b>or</b> the {@link Story} {@link URL}
466 * which {@link Chapter} to read (starting at 1), or NULL to get
467 * the {@link Story} description
469 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
472 * @return the exit return code (0 = success)
474 private static int read(String story
, String chapString
, boolean library
) {
476 Reader reader
= BasicReader
.getReader();
478 reader
.setMeta(story
);
480 reader
.setMeta(BasicReader
.getUrl(story
), null);
483 if (chapString
!= null) {
485 reader
.setChapter(Integer
.parseInt(chapString
));
487 } catch (NumberFormatException e
) {
488 Instance
.syserr(new IOException(
489 "Chapter number cannot be parsed: " + chapString
, e
));
495 } catch (IOException e
) {
504 * Convert the {@link Story} into another format.
507 * the source {@link Story} to convert
509 * the {@link OutputType} to convert to
513 * TRUE to also export the cover and info file, even if the given
514 * {@link OutputType} does not usually save them
516 * the optional progress reporter
518 * @return the exit return code (0 = success)
520 private static int convert(String urlString
, String typeString
,
521 String target
, boolean infoCover
, Progress pg
) {
524 String sourceName
= urlString
;
526 URL source
= BasicReader
.getUrl(urlString
);
527 sourceName
= source
.toString();
528 if (source
.toString().startsWith("file://")) {
529 sourceName
= sourceName
.substring("file://".length());
532 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
534 Instance
.syserr(new IOException(trans(
535 StringId
.ERR_BAD_OUTPUT_TYPE
, typeString
)));
540 BasicSupport support
= BasicSupport
.getSupport(source
);
542 if (support
!= null) {
543 Progress pgIn
= new Progress();
544 Progress pgOut
= new Progress();
547 pg
.addProgress(pgIn
, 1);
548 pg
.addProgress(pgOut
, 1);
551 Story story
= support
.process(source
, pgIn
);
553 target
= new File(target
).getAbsolutePath();
554 BasicOutput
.getOutput(type
, infoCover
).process(
555 story
, target
, pgOut
);
556 } catch (IOException e
) {
557 Instance
.syserr(new IOException(trans(
558 StringId
.ERR_SAVING
, target
), e
));
562 Instance
.syserr(new IOException(trans(
563 StringId
.ERR_NOT_SUPPORTED
, source
)));
567 } catch (IOException e
) {
568 Instance
.syserr(new IOException(trans(StringId
.ERR_LOADING
,
573 } catch (MalformedURLException e
) {
574 Instance
.syserr(new IOException(trans(StringId
.ERR_BAD_URL
,
583 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
586 * the ID to translate
588 * @return the translated result
590 private static String
trans(StringId id
, Object
... params
) {
591 return Instance
.getTrans().getString(id
, params
);
595 * Display the correct syntax of the program to the user to stdout, or an
596 * error message if the syntax used was wrong on stderr.
599 * TRUE to show the syntax help, FALSE to show "syntax error"
601 private static void syntax(boolean showHelp
) {
603 StringBuilder builder
= new StringBuilder();
604 for (SupportType type
: SupportType
.values()) {
605 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
607 builder
.append('\n');
610 String typesIn
= builder
.toString();
611 builder
.setLength(0);
613 for (OutputType type
: OutputType
.values()) {
614 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
615 type
.getDesc(true)));
616 builder
.append('\n');
619 String typesOut
= builder
.toString();
621 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
623 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
628 * Set the default reader type for this session only (it can be changed in
629 * the configuration file, too, but this value will override it).
631 * @param readerTypeString
634 private static int setReaderType(String readerTypeString
) {
636 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
638 BasicReader
.setDefaultReaderType(readerType
);
640 } catch (IllegalArgumentException e
) {
641 Instance
.syserr(new IOException("Unknown reader type: "
642 + readerTypeString
, e
));