1 package be
.nikiroo
.fanfix
;
4 import java
.io
.IOException
;
5 import java
.net
.MalformedURLException
;
7 import java
.util
.ArrayList
;
10 import be
.nikiroo
.fanfix
.bundles
.Config
;
11 import be
.nikiroo
.fanfix
.bundles
.StringId
;
12 import be
.nikiroo
.fanfix
.data
.Chapter
;
13 import be
.nikiroo
.fanfix
.data
.MetaData
;
14 import be
.nikiroo
.fanfix
.data
.Story
;
15 import be
.nikiroo
.fanfix
.library
.BasicLibrary
;
16 import be
.nikiroo
.fanfix
.library
.CacheLibrary
;
17 import be
.nikiroo
.fanfix
.library
.LocalLibrary
;
18 import be
.nikiroo
.fanfix
.library
.RemoteLibrary
;
19 import be
.nikiroo
.fanfix
.library
.RemoteLibraryServer
;
20 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
21 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
22 import be
.nikiroo
.fanfix
.reader
.BasicReader
;
23 import be
.nikiroo
.fanfix
.reader
.Reader
;
24 import be
.nikiroo
.fanfix
.reader
.Reader
.ReaderType
;
25 import be
.nikiroo
.fanfix
.searchable
.BasicSearchable
;
26 import be
.nikiroo
.fanfix
.supported
.BasicSupport
;
27 import be
.nikiroo
.fanfix
.supported
.SupportType
;
28 import be
.nikiroo
.utils
.Progress
;
29 import be
.nikiroo
.utils
.Version
;
30 import be
.nikiroo
.utils
.serial
.server
.ServerObject
;
33 * Main program entry point.
38 private enum MainAction
{
39 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
43 * Main program entry point.
45 * Known environment variables:
47 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
48 * {@link String}s when possible</li>
49 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
50 * before taking the usual ones; they will also be saved/updated into this
51 * path when the program starts</li>
52 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
53 * configuration value with 'true'</li>
57 * <li>--import [URL]: import into library</li>
58 * <li>--export [id] [output_type] [target]: export story to target</li>
59 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
61 * <li>--read [id] ([chapter number]): read the given story from the library
63 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
64 * story, without saving it</li>
65 * <li>--search: list the supported websites (where)</li>
66 * <li>--search [where] [keywords] (page [page]) (item [item]): search on
67 * the supported website and display the given results page of stories it
68 * found, or the story details if asked</li>
69 * <li>--search-tag [where]: list all the tags supported by this website</li>
70 * <li>--search-tag [index 1]... (page [page]) (item [item]): search for the
71 * given stories or subtags, tag by tag, and display information about a
72 * specific page of results or about a specific item if requested</li>
73 * <li>--list ([type]): list the stories present in the library</li>
74 * <li>--set-source [id] [new source]: change the source of the given story</li>
75 * <li>--set-title [id] [new title]: change the title of the given story</li>
76 * <li>--set-author [id] [new author]: change the author of the given story</li>
77 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
78 * for this command</li>
79 * <li>--version: get the version of the program</li>
80 * <li>--server: start the server mode (see config file for parameters)</li>
81 * <li>--stop-server: stop the running server on this port if any</li>
82 * <li>--remote [key] [host] [port]: use a the given remote library</li>
86 * see method description
88 public static void main(String
[] args
) {
89 String urlString
= null;
91 String sourceString
= null;
92 String titleString
= null;
93 String authorString
= null;
94 String chapString
= null;
97 MainAction action
= MainAction
.START
;
98 Boolean plusInfo
= null;
101 SupportType searchOn
= null;
102 String search
= null;
103 List
<Integer
> tags
= new ArrayList
<Integer
>();
107 boolean noMoreActions
= false;
110 for (int i
= 0; exitCode
== 0 && i
< args
.length
; i
++) {
111 // Action (--) handling:
112 if (!noMoreActions
&& args
[i
].startsWith("--")) {
113 if (args
[i
].equals("--")) {
114 noMoreActions
= true;
117 action
= MainAction
.valueOf(args
[i
].substring(2)
118 .toUpperCase().replace("-", "_"));
119 } catch (Exception e
) {
120 Instance
.getTraceHandler().error(
121 new IllegalArgumentException("Unknown action: "
132 if (urlString
== null) {
141 } else if (sourceString
== null) {
142 sourceString
= args
[i
];
143 } else if (target
== null) {
150 if (urlString
== null) {
152 } else if (sourceString
== null) {
153 sourceString
= args
[i
];
154 } else if (target
== null) {
156 } else if (plusInfo
== null) {
157 if ("+info".equals(args
[i
])) {
167 if (sourceString
== null) {
168 sourceString
= args
[i
];
176 } else if (sourceString
== null) {
177 sourceString
= args
[i
];
185 } else if (sourceString
== null) {
186 titleString
= args
[i
];
194 } else if (sourceString
== null) {
195 authorString
= args
[i
];
203 } else if (chapString
== null) {
204 chapString
= args
[i
];
210 if (urlString
== null) {
212 } else if (chapString
== null) {
213 chapString
= args
[i
];
219 if (searchOn
== null) {
220 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
222 if (searchOn
== null) {
223 Instance
.getTraceHandler().error(
224 "Website not known: <" + args
[i
] + ">");
229 if (BasicSearchable
.getSearchable(searchOn
) == null) {
230 Instance
.getTraceHandler().error(
231 "Website not supported: " + searchOn
);
235 } else if (search
== null) {
237 } else if (page
!= null && page
== -1) {
239 page
= Integer
.parseInt(args
[i
]);
240 } catch (Exception e
) {
243 } else if (item
!= null && item
== -1) {
245 item
= Integer
.parseInt(args
[i
]);
246 } catch (Exception e
) {
249 } else if (page
== null || item
== null) {
250 if (page
== null && "page".equals(args
[i
])) {
252 } else if (item
== null && "item".equals(args
[i
])) {
262 if (searchOn
== null) {
263 searchOn
= SupportType
.valueOfAllOkUC(args
[i
]);
265 if (searchOn
== null) {
266 Instance
.getTraceHandler().error(
267 "Website not known: <" + args
[i
] + ">");
271 if (BasicSearchable
.getSearchable(searchOn
) == null) {
272 Instance
.getTraceHandler().error(
273 "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
.getTraceHandler().error(
287 "Invalid tag index: " + args
[i
]);
291 } else if (page
!= null && page
== -1) {
293 page
= Integer
.parseInt(args
[i
]);
294 } catch (Exception e
) {
297 } else if (item
!= null && item
== -1) {
299 item
= Integer
.parseInt(args
[i
]);
300 } catch (Exception e
) {
303 } else if (page
== null || item
== null) {
304 if (page
== null && "page".equals(args
[i
])) {
306 } else if (item
== null && "item".equals(args
[i
])) {
319 exitCode
= setReaderType(args
[i
]);
320 action
= MainAction
.START
;
323 exitCode
= 255; // not supposed to be selected by user
326 exitCode
= 255; // no arguments for this option
329 exitCode
= 255; // no arguments for this option
332 exitCode
= 255; // no arguments for this option
337 } else if (host
== null) {
339 } else if (port
== null) {
340 port
= Integer
.parseInt(args
[i
]);
342 BasicLibrary lib
= new RemoteLibrary(key
, host
, port
);
343 lib
= new CacheLibrary(Instance
.getRemoteDir(host
), lib
);
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
.getTraceHandler()
418 .error(new Exception(
419 "No reader type has been configured"));
423 exitCode
= list(sourceString
);
427 Instance
.getLibrary().changeSource(luid
, sourceString
, pg
);
428 } catch (IOException e1
) {
429 Instance
.getTraceHandler().error(e1
);
435 Instance
.getLibrary().changeTitle(luid
, titleString
, pg
);
436 } catch (IOException e1
) {
437 Instance
.getTraceHandler().error(e1
);
443 Instance
.getLibrary().changeAuthor(luid
, authorString
, pg
);
444 } catch (IOException e1
) {
445 Instance
.getTraceHandler().error(e1
);
450 if (BasicReader
.getReader() == null) {
451 Instance
.getTraceHandler()
452 .error(new Exception(
453 "No reader type has been configured"));
457 exitCode
= read(luid
, chapString
, true);
460 if (BasicReader
.getReader() == null) {
461 Instance
.getTraceHandler()
462 .error(new Exception(
463 "No reader type has been configured"));
467 exitCode
= read(urlString
, chapString
, false);
470 page
= page
== null ?
1 : page
;
472 Instance
.getTraceHandler().error("Incorrect page number");
477 item
= item
== null ?
0 : item
;
479 Instance
.getTraceHandler().error("Incorrect item number");
484 if (BasicReader
.getReader() == null) {
485 Instance
.getTraceHandler()
486 .error(new Exception(
487 "No reader type has been configured"));
493 if (searchOn
== null) {
494 BasicReader
.getReader().search(true);
495 } else if (search
!= null) {
497 BasicReader
.getReader().search(searchOn
, search
, page
,
502 } catch (IOException e1
) {
503 Instance
.getTraceHandler().error(e1
);
509 if (searchOn
== null) {
514 page
= page
== null ?
1 : page
;
516 Instance
.getTraceHandler().error("Incorrect page number");
521 item
= item
== null ?
0 : item
;
523 Instance
.getTraceHandler().error("Incorrect item number");
528 if (BasicReader
.getReader() == null) {
529 Instance
.getTraceHandler()
530 .error(new Exception(
531 "No reader type has been configured"));
537 BasicReader
.getReader().searchTag(searchOn
, page
, item
,
538 true, tags
.toArray(new Integer
[] {}));
539 } catch (IOException e1
) {
540 Instance
.getTraceHandler().error(e1
);
553 .println(String
.format("Fanfix version %s"
554 + "%nhttps://github.com/nikiroo/fanfix/"
555 + "%n\tWritten by Nikiroo",
556 Version
.getCurrentVersion()));
557 updates
.ok(); // we consider it read
560 if (BasicReader
.getReader() == null) {
561 Instance
.getTraceHandler()
562 .error(new Exception(
563 "No reader type has been configured"));
567 BasicReader
.getReader().browse(null);
570 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
571 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
573 System
.err
.println("No port configured in the config file");
578 ServerObject server
= new RemoteLibraryServer(key
, port
);
579 server
.setTraceHandler(Instance
.getTraceHandler());
581 } catch (IOException e
) {
582 Instance
.getTraceHandler().error(e
);
586 key
= Instance
.getConfig().getString(Config
.SERVER_KEY
);
587 port
= Instance
.getConfig().getInteger(Config
.SERVER_PORT
);
589 System
.err
.println("No port configured in the config file");
594 new RemoteLibrary(key
, host
, port
).exit();
597 exitCode
= 255; // should not be reachable (REMOTE -> START)
603 Instance
.getTempFiles().close();
604 } catch (IOException e
) {
605 Instance
.getTraceHandler()
606 .error(new IOException(
607 "Cannot dispose of the temporary files", e
));
610 if (exitCode
== 255) {
614 System
.exit(exitCode
);
618 * Import the given resource into the {@link LocalLibrary}.
621 * the resource to import
623 * the optional progress reporter
625 * @return the exit return code (0 = success)
627 public static int imprt(String urlString
, Progress pg
) {
629 Story story
= Instance
.getLibrary().imprt(
630 BasicReader
.getUrl(urlString
), pg
);
631 System
.out
.println(story
.getMeta().getLuid() + ": \""
632 + story
.getMeta().getTitle() + "\" imported.");
633 } catch (IOException e
) {
634 Instance
.getTraceHandler().error(e
);
642 * Export the {@link Story} from the {@link LocalLibrary} to the given
648 * the {@link OutputType} to use
652 * the optional progress reporter
654 * @return the exit return code (0 = success)
656 public static int export(String luid
, String typeString
, String target
,
658 OutputType type
= OutputType
.valueOfNullOkUC(typeString
, null);
660 Instance
.getTraceHandler().error(
661 new Exception(trans(StringId
.OUTPUT_DESC
, typeString
)));
666 Instance
.getLibrary().export(luid
, type
, target
, pg
);
667 } catch (IOException e
) {
668 Instance
.getTraceHandler().error(e
);
676 * List the stories of the given source from the {@link LocalLibrary}
677 * (unless NULL is passed, in which case all stories will be listed).
680 * the source to list the known stories of, or NULL to list all
683 * @return the exit return code (0 = success)
685 private static int list(String source
) {
686 List
<MetaData
> stories
;
687 stories
= BasicReader
.getReader().getLibrary().getListBySource(source
);
689 for (MetaData story
: stories
) {
691 if (story
.getAuthor() != null && !story
.getAuthor().isEmpty()) {
692 author
= " (" + story
.getAuthor() + ")";
695 System
.out
.println(story
.getLuid() + ": " + story
.getTitle()
702 * Start the current reader for this {@link Story}.
705 * the LUID of the {@link Story} in the {@link LocalLibrary}
706 * <b>or</b> the {@link Story} {@link URL}
708 * which {@link Chapter} to read (starting at 1), or NULL to get
709 * the {@link Story} description
711 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
714 * @return the exit return code (0 = success)
716 private static int read(String story
, String chapString
, boolean library
) {
718 Reader reader
= BasicReader
.getReader();
720 reader
.setMeta(story
);
722 reader
.setMeta(BasicReader
.getUrl(story
), null);
725 if (chapString
!= null) {
727 reader
.setChapter(Integer
.parseInt(chapString
));
729 } catch (NumberFormatException e
) {
730 Instance
.getTraceHandler().error(
731 new IOException("Chapter number cannot be parsed: "
738 } catch (IOException e
) {
739 Instance
.getTraceHandler().error(e
);
747 * Convert the {@link Story} into another format.
750 * the source {@link Story} to convert
752 * the {@link OutputType} to convert to
756 * TRUE to also export the cover and info file, even if the given
757 * {@link OutputType} does not usually save them
759 * the optional progress reporter
761 * @return the exit return code (0 = success)
763 public static int convert(String urlString
, String typeString
,
764 String target
, boolean infoCover
, Progress pg
) {
767 Instance
.getTraceHandler().trace("Convert: " + urlString
);
768 String sourceName
= urlString
;
770 URL source
= BasicReader
.getUrl(urlString
);
771 sourceName
= source
.toString();
772 if (source
.toString().startsWith("file://")) {
773 sourceName
= sourceName
.substring("file://".length());
776 OutputType type
= OutputType
.valueOfAllOkUC(typeString
, null);
778 Instance
.getTraceHandler().error(
779 new IOException(trans(StringId
.ERR_BAD_OUTPUT_TYPE
,
785 BasicSupport support
= BasicSupport
.getSupport(source
);
787 if (support
!= null) {
788 Instance
.getTraceHandler().trace(
789 "Support found: " + support
.getClass());
790 Progress pgIn
= new Progress();
791 Progress pgOut
= new Progress();
794 pg
.addProgress(pgIn
, 1);
795 pg
.addProgress(pgOut
, 1);
798 Story story
= support
.process(pgIn
);
800 target
= new File(target
).getAbsolutePath();
801 BasicOutput
.getOutput(type
, infoCover
, infoCover
)
802 .process(story
, target
, pgOut
);
803 } catch (IOException e
) {
804 Instance
.getTraceHandler().error(
805 new IOException(trans(StringId
.ERR_SAVING
,
810 Instance
.getTraceHandler().error(
811 new IOException(trans(
812 StringId
.ERR_NOT_SUPPORTED
, source
)));
816 } catch (IOException e
) {
817 Instance
.getTraceHandler().error(
818 new IOException(trans(StringId
.ERR_LOADING
,
823 } catch (MalformedURLException e
) {
824 Instance
.getTraceHandler()
825 .error(new IOException(trans(StringId
.ERR_BAD_URL
,
834 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
837 * the ID to translate
839 * @return the translated result
841 private static String
trans(StringId id
, Object
... params
) {
842 return Instance
.getTrans().getString(id
, params
);
846 * Display the correct syntax of the program to the user to stdout, or an
847 * error message if the syntax used was wrong on stderr.
850 * TRUE to show the syntax help, FALSE to show "syntax error"
852 private static void syntax(boolean showHelp
) {
854 StringBuilder builder
= new StringBuilder();
855 for (SupportType type
: SupportType
.values()) {
856 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
858 builder
.append('\n');
861 String typesIn
= builder
.toString();
862 builder
.setLength(0);
864 for (OutputType type
: OutputType
.values()) {
865 builder
.append(trans(StringId
.ERR_SYNTAX_TYPE
, type
.toString(),
866 type
.getDesc(true)));
867 builder
.append('\n');
870 String typesOut
= builder
.toString();
872 System
.out
.println(trans(StringId
.HELP_SYNTAX
, typesIn
, typesOut
));
874 System
.err
.println(trans(StringId
.ERR_SYNTAX
));
879 * Set the default reader type for this session only (it can be changed in
880 * the configuration file, too, but this value will override it).
882 * @param readerTypeString
885 private static int setReaderType(String readerTypeString
) {
887 ReaderType readerType
= ReaderType
.valueOf(readerTypeString
889 BasicReader
.setDefaultReaderType(readerType
);
891 } catch (IllegalArgumentException e
) {
892 Instance
.getTraceHandler().error(
893 new IOException("Unknown reader type: " + readerTypeString
,