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
.getInstance().getTraceHandler()
126 .error(new IllegalArgumentException("Unknown action: " + args
[i
], e
));
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
.getInstance().getTraceHandler().error("Website not known: <" + args
[i
] + ">");
232 if (BasicSearchable
.getSearchable(searchOn
) == null) {
233 Instance
.getInstance().getTraceHandler().error("Website not supported: " + searchOn
);
237 } else if (search
== null) {
239 } else if (page
!= null && page
== -1) {
241 page
= Integer
.parseInt(args
[i
]);
242 } catch (Exception e
) {
245 } else if (item
!= null && item
== -1) {
247 item
= Integer
.parseInt(args
[i
]);
248 } catch (Exception e
) {
251 } else if (page
== null || item
== null) {
252 if (page
== null && "page".equals(args
[i
])) {
254 } else if (item
== null && "item".equals(args
[i
])) {
264 if (searchOn
== null) {
265 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
267 if (searchOn
== null) {
268 Instance
.getInstance().getTraceHandler().error("Website not known: <" + args
[i
] + ">");
272 if (BasicSearchable
.getSearchable(searchOn
) == null) {
273 Instance
.getInstance().getTraceHandler().error("Website not supported: " + searchOn
);
276 } else if (page
== null && item
== null) {
277 if ("page".equals(args
[i
])) {
279 } else if ("item".equals(args
[i
])) {
283 int index
= Integer
.parseInt(args
[i
]);
285 } catch (NumberFormatException e
) {
286 Instance
.getInstance().getTraceHandler().error("Invalid tag index: " + args
[i
]);
290 } else if (page
!= null && page
== -1) {
292 page
= Integer
.parseInt(args
[i
]);
293 } catch (Exception e
) {
296 } else if (item
!= null && item
== -1) {
298 item
= Integer
.parseInt(args
[i
]);
299 } catch (Exception e
) {
302 } else if (page
== null || item
== null) {
303 if (page
== null && "page".equals(args
[i
])) {
305 } else if (item
== null && "item".equals(args
[i
])) {
318 exitCode
= setReaderType(args
[i
]);
319 action
= MainAction
.START
;
322 exitCode
= 255; // not supposed to be selected by user
325 exitCode
= 255; // no arguments for this option
328 exitCode
= 255; // no arguments for this option
331 exitCode
= 255; // no arguments for this option
336 } else if (host
== null) {
338 } else if (port
== null) {
339 port
= Integer
.parseInt(args
[i
]);
341 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
342 lib
= new CacheLibrary(Instance
.getInstance().getRemoteDir(host
), lib
,
343 Instance
.getInstance().getUiConfig());
345 BasicReader
.setDefaultLibrary(lib
);
347 action
= MainAction
.START
;
355 final Progress mainProgress
= new Progress(0, 80);
356 mainProgress
.addProgressListener(new Progress
.ProgressListener() {
357 private int current
= mainProgress
.getMin();
360 public void progress(Progress progress
, String name
) {
361 int diff
= progress
.getProgress() - current
;
367 StringBuilder builder
= new StringBuilder();
368 for (int i
= 0; i
< diff
; i
++) {
372 System
.err
.print(builder
.toString());
374 if (progress
.isDone()) {
375 System
.err
.println("");
379 Progress pg
= new Progress();
380 mainProgress
.addProgress(pg
, mainProgress
.getMax());
382 VersionCheck updates
= VersionCheck
.check();
383 if (updates
.isNewVersionAvailable()) {
384 // Sent to syserr so not to cause problem if one tries to capture a
385 // story content in text mode
387 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
388 System
.err
.println("");
389 for (Version v
: updates
.getNewer()) {
390 System
.err
.println("\tVersion " + v
);
391 System
.err
.println("\t-------------");
392 System
.err
.println("");
393 for (String it
: updates
.getChanges().get(v
)) {
394 System
.err
.println("\t- " + it
);
396 System
.err
.println("");
403 exitCode
= imprt(urlString
, pg
);
404 updates
.ok(); // we consider it read
407 exitCode
= export(luid
, sourceString
, target
, pg
);
408 updates
.ok(); // we consider it read
411 exitCode
= convert(urlString
, sourceString
, target
,
412 plusInfo
== null ?
false : plusInfo
, pg
);
413 updates
.ok(); // we consider it read
416 if (BasicReader
.getReader() == null) {
417 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
421 exitCode
= list(sourceString
);
425 Instance
.getInstance().getLibrary().changeSource(luid
, sourceString
, pg
);
426 } catch (IOException e1
) {
427 Instance
.getInstance().getTraceHandler().error(e1
);
433 Instance
.getInstance().getLibrary().changeTitle(luid
, titleString
, pg
);
434 } catch (IOException e1
) {
435 Instance
.getInstance().getTraceHandler().error(e1
);
441 Instance
.getInstance().getLibrary().changeAuthor(luid
, authorString
, pg
);
442 } catch (IOException e1
) {
443 Instance
.getInstance().getTraceHandler().error(e1
);
448 if (BasicReader
.getReader() == null) {
449 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
453 exitCode
= read(luid
, chapString
, true);
456 if (BasicReader
.getReader() == null) {
457 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
461 exitCode
= read(urlString
, chapString
, false);
464 page
= page
== null ?
1 : page
;
466 Instance
.getInstance().getTraceHandler().error("Incorrect page number");
471 item
= item
== null ?
0 : item
;
473 Instance
.getInstance().getTraceHandler().error("Incorrect item number");
478 if (BasicReader
.getReader() == null) {
479 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
485 if (searchOn
== null) {
486 BasicReader
.getReader().search(true);
487 } else if (search
!= null) {
489 BasicReader
.getReader().search(searchOn
, search
, page
,
494 } catch (IOException e1
) {
495 Instance
.getInstance().getTraceHandler().error(e1
);
501 if (searchOn
== null) {
506 page
= page
== null ?
1 : page
;
508 Instance
.getInstance().getTraceHandler().error("Incorrect page number");
513 item
= item
== null ?
0 : item
;
515 Instance
.getInstance().getTraceHandler().error("Incorrect item number");
520 if (BasicReader
.getReader() == null) {
521 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
527 BasicReader
.getReader().searchTag(searchOn
, page
, item
,
528 true, tags
.toArray(new Integer
[] {}));
529 } catch (IOException e1
) {
530 Instance
.getInstance().getTraceHandler().error(e1
);
543 .println(String
.format("Fanfix version %s"
544 + "%nhttps://github.com/nikiroo/fanfix/"
545 + "%n\tWritten by Nikiroo",
546 Version
.getCurrentVersion()));
547 updates
.ok(); // we consider it read
550 if (BasicReader
.getReader() == null) {
551 Instance
.getInstance().getTraceHandler().error(new Exception("No reader type has been configured"));
556 BasicReader
.getReader().browse(null);
557 } catch (IOException e
) {
558 Instance
.getInstance().getTraceHandler().error(e
);
563 key
= Instance
.getInstance().getConfig().getString(Config
.SERVER_KEY
);
564 port
= Instance
.getInstance().getConfig().getInteger(Config
.SERVER_PORT
);
566 System
.err
.println("No port configured in the config file");
571 ServerObject server
= new RemoteLibraryServer(key
, port
);
572 server
.setTraceHandler(Instance
.getInstance().getTraceHandler());
574 } catch (IOException e
) {
575 Instance
.getInstance().getTraceHandler().error(e
);
579 // Can be given via "--remote XX XX XX"
581 key
= Instance
.getInstance().getConfig().getString(Config
.SERVER_KEY
);
583 port
= Instance
.getInstance().getConfig().getInteger(Config
.SERVER_PORT
);
586 System
.err
.println("No port given nor configured in the config file");
591 new RemoteLibrary(key
, host
, port
).exit();
592 } catch (SSLException e
) {
593 Instance
.getInstance().getTraceHandler().error(
594 "Bad access key for remote library");
596 } catch (IOException e
) {
597 Instance
.getInstance().getTraceHandler().error(e
);
603 exitCode
= 255; // should not be reachable (REMOTE -> START)
609 Instance
.getInstance().getTempFiles().close();
610 } catch (IOException e
) {
611 Instance
.getInstance().getTraceHandler().error(new IOException("Cannot dispose of the temporary files", e
));
614 if (exitCode
== 255) {
618 System
.exit(exitCode
);
622 * Import the given resource into the {@link LocalLibrary}.
625 * the resource to import
627 * the optional progress reporter
629 * @return the exit return code (0 = success)
631 public static int imprt(String urlString
, Progress pg
) {
633 MetaData meta
= Instance
.getInstance().getLibrary().imprt(BasicReader
.getUrl(urlString
), pg
);
634 System
.out
.println(meta
.getLuid() + ": \"" + meta
.getTitle() + "\" imported.");
635 } catch (IOException e
) {
636 Instance
.getInstance().getTraceHandler().error(e
);
644 * Export the {@link Story} from the {@link LocalLibrary} to the given
650 * the {@link OutputType} to use
654 * the optional progress reporter
656 * @return the exit return code (0 = success)
658 public static int export(String luid
, String typeString
, String target
,
660 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
662 Instance
.getInstance().getTraceHandler().error(new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
667 Instance
.getInstance().getLibrary().export(luid
, type
, target
, pg
);
668 } catch (IOException e
) {
669 Instance
.getInstance().getTraceHandler().error(e
);
677 * List the stories of the given source from the {@link LocalLibrary}
678 * (unless NULL is passed, in which case all stories will be listed).
681 * the source to list the known stories of, or NULL to list all
684 * @return the exit return code (0 = success)
686 private static int list(String source
) {
687 BasicReader
.setDefaultReaderType(ReaderType
.CLI
);
689 BasicReader
.getReader().browse(source
);
690 } catch (IOException e
) {
691 Instance
.getInstance().getTraceHandler().error(e
);
699 * Start the current reader for this {@link Story}.
702 * the LUID of the {@link Story} in the {@link LocalLibrary}
703 * <b>or</b> the {@link Story} {@link URL}
705 * which {@link Chapter} to read (starting at 1), or NULL to get
706 * the {@link Story} description
708 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
711 * @return the exit return code (0 = success)
713 private static int read(String story
, String chapString
, boolean library
) {
715 Reader reader
= BasicReader
.getReader();
717 reader
.setMeta(story
);
719 reader
.setMeta(BasicReader
.getUrl(story
), null);
722 if (chapString
!= null) {
724 reader
.setChapter(Integer
.parseInt(chapString
));
726 } catch (NumberFormatException e
) {
727 Instance
.getInstance().getTraceHandler()
728 .error(new IOException("Chapter number cannot be parsed: " + chapString
, e
));
734 } catch (IOException e
) {
735 Instance
.getInstance().getTraceHandler().error(e
);
743 * Convert the {@link Story} into another format.
746 * the source {@link Story} to convert
748 * the {@link OutputType} to convert to
752 * TRUE to also export the cover and info file, even if the given
753 * {@link OutputType} does not usually save them
755 * the optional progress reporter
757 * @return the exit return code (0 = success)
759 public static int convert(String urlString
, String typeString
,
760 String target
, boolean infoCover
, Progress pg
) {
763 Instance
.getInstance().getTraceHandler().trace("Convert: " + urlString
);
764 String sourceName
= urlString
;
766 URL source
= BasicReader
.getUrl(urlString
);
767 sourceName
= source
.toString();
768 if (sourceName
.startsWith("file://")) {
769 sourceName
= sourceName
.substring("file://".length());
772 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
774 Instance
.getInstance().getTraceHandler()
775 .error(new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
, typeString
)));
780 BasicSupport support
= BasicSupport
.getSupport(source
);
782 if (support
!= null) {
783 Instance
.getInstance().getTraceHandler().trace("Support found: " + support
.getClass());
784 Progress pgIn
= new Progress();
785 Progress pgOut
= new Progress();
788 pg
.addProgress(pgIn
, 1);
789 pg
.addProgress(pgOut
, 1);
792 Story story
= support
.process(pgIn
);
794 target
= new File(target
).getAbsolutePath();
795 BasicOutput
.getOutput(type
, infoCover
, infoCover
).process(story
, target
, pgOut
);
796 } catch (IOException e
) {
797 Instance
.getInstance().getTraceHandler()
798 .error(new IOException(trans(StringId
.ERR_SAVING
, target
), e
));
802 Instance
.getInstance().getTraceHandler()
803 .error(new IOException(trans( StringId
.ERR_NOT_SUPPORTED
, source
)));
807 } catch (IOException e
) {
808 Instance
.getInstance().getTraceHandler()
809 .error(new IOException(trans(StringId
.ERR_LOADING
, sourceName
), e
));
813 } catch (MalformedURLException e
) {
814 Instance
.getInstance().getTraceHandler().error(new IOException(trans(StringId
.ERR_BAD_URL
, sourceName
), e
));
822 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
825 * the ID to translate
827 * @return the translated result
829 private static String
trans(StringId id
, Object
... params
) {
830 return Instance
.getInstance().getTrans().getString(id
, params
);
834 * Display the correct syntax of the program to the user to stdout, or an
835 * error message if the syntax used was wrong on stderr.
838 * TRUE to show the syntax help, FALSE to show "syntax error"
840 private static void syntax(boolean showHelp
) {
842 StringBuilder builder
= new StringBuilder();
843 for (SupportType type
: SupportType
.values()) {
844 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
846 builder
.append('\n');
849 String typesIn
= builder
.toString();
850 builder
.setLength(0);
852 for (OutputType type
: OutputType
.values()) {
853 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
854 type
.getDesc(true)));
855 builder
.append('\n');
858 String typesOut
= builder
.toString();
860 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
862 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
867 * Set the default reader type for this session only (it can be changed in
868 * the configuration file, too, but this value will override it).
870 * @param readerTypeString
873 private static int setReaderType(String readerTypeString
) {
875 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
877 BasicReader
.setDefaultReaderType(readerType
);
879 } catch (IllegalArgumentException e
) {
880 Instance
.getInstance().getTraceHandler()
881 .error(new IOException("Unknown reader type: " + readerTypeString
, e
));