Update to latest version of nikiroo-utils
[nikiroo-utils.git] / src / be / nikiroo / fanfix / Main.java
CommitLineData
08fe2e33
NR
1package be.nikiroo.fanfix;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import java.net.URL;
7
8import be.nikiroo.fanfix.bundles.StringId;
9import be.nikiroo.fanfix.data.Chapter;
10import be.nikiroo.fanfix.data.Story;
e42573a0
NR
11import be.nikiroo.fanfix.library.LocalLibrary;
12import be.nikiroo.fanfix.library.RemoteLibrary;
13import be.nikiroo.fanfix.library.RemoteLibraryServer;
08fe2e33
NR
14import be.nikiroo.fanfix.output.BasicOutput;
15import be.nikiroo.fanfix.output.BasicOutput.OutputType;
3727aae2 16import be.nikiroo.fanfix.reader.BasicReader;
e42573a0
NR
17import be.nikiroo.fanfix.reader.Reader;
18import be.nikiroo.fanfix.reader.Reader.ReaderType;
08fe2e33
NR
19import be.nikiroo.fanfix.supported.BasicSupport;
20import be.nikiroo.fanfix.supported.BasicSupport.SupportType;
3b2b638f 21import be.nikiroo.utils.Progress;
39c3c689 22import be.nikiroo.utils.Version;
b0e88ebd 23import be.nikiroo.utils.serial.Server;
08fe2e33
NR
24
25/**
26 * Main program entry point.
27 *
28 * @author niki
29 */
30public class Main {
d0114000 31 private enum MainAction {
b0e88ebd 32 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, SET_READER, START, VERSION, SERVER, REMOTE,
d0114000
NR
33 }
34
08fe2e33
NR
35 /**
36 * Main program entry point.
37 * <p>
38 * Known environment variables:
39 * <ul>
d0114000 40 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
08fe2e33
NR
41 * {@link String}s when possible</li>
42 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
edd46289
NR
43 * before taking the usual ones; they will also be saved/updated into this
44 * path when the program starts</li>
d0114000
NR
45 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
46 * configuration value with 'true'</li>
47 * </ul>
48 * <p>
49 * <ul>
50 * <li>--import [URL]: import into library</li>
51 * <li>--export [id] [output_type] [target]: export story to target</li>
52 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
53 * target</li>
54 * <li>--read [id] ([chapter number]): read the given story from the library
55 * </li>
333f0e7b 56 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
d0114000 57 * story, without saving it</li>
333f0e7b 58 * <li>--list ([type]): list the stories present in the library</li>
c1873e56
NR
59 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
60 * for this command</li>
39c3c689 61 * <li>--version: get the version of the program</li>
b0e88ebd
NR
62 * <li>--server [port]: start a server on this port</li>
63 * <li>--remote [host] [port]: use a the given remote library</li>
08fe2e33
NR
64 * </ul>
65 *
66 * @param args
d0114000 67 * see method description
08fe2e33
NR
68 */
69 public static void main(String[] args) {
d0114000
NR
70 String urlString = null;
71 String luid = null;
b0e88ebd 72 String sourceString = null;
d0114000
NR
73 String chapString = null;
74 String target = null;
333f0e7b 75 MainAction action = MainAction.START;
d0114000 76 Boolean plusInfo = null;
b0e88ebd
NR
77 String host = null;
78 Integer port = null;
73ce17ef 79
d0114000
NR
80 boolean noMoreActions = false;
81
82 int exitCode = 0;
83 for (int i = 0; exitCode == 0 && i < args.length; i++) {
84 // Action (--) handling:
85 if (!noMoreActions && args[i].startsWith("--")) {
86 if (args[i].equals("--")) {
87 noMoreActions = true;
88 } else {
89 try {
90 action = MainAction.valueOf(args[i].substring(2)
91 .toUpperCase().replace("-", "_"));
92 } catch (Exception e) {
93 Instance.syserr(new IllegalArgumentException(
94 "Unknown action: " + args[i], e));
95 exitCode = 255;
96 }
97 }
08fe2e33 98
d0114000
NR
99 continue;
100 }
101
102 switch (action) {
103 case IMPORT:
104 if (urlString == null) {
105 urlString = args[i];
106 } else {
107 exitCode = 255;
108 }
109 break;
110 case EXPORT:
111 if (luid == null) {
112 luid = args[i];
b0e88ebd
NR
113 } else if (sourceString == null) {
114 sourceString = args[i];
d0114000
NR
115 } else if (target == null) {
116 target = args[i];
117 } else {
118 exitCode = 255;
119 }
120 break;
121 case CONVERT:
122 if (urlString == null) {
123 urlString = args[i];
b0e88ebd
NR
124 } else if (sourceString == null) {
125 sourceString = args[i];
d0114000
NR
126 } else if (target == null) {
127 target = args[i];
128 } else if (plusInfo == null) {
129 if ("+info".equals(args[i])) {
130 plusInfo = true;
131 } else {
132 exitCode = 255;
133 }
134 } else {
135 exitCode = 255;
08fe2e33 136 }
d0114000
NR
137 break;
138 case LIST:
b0e88ebd
NR
139 if (sourceString == null) {
140 sourceString = args[i];
d0114000
NR
141 } else {
142 exitCode = 255;
08fe2e33 143 }
d0114000
NR
144 break;
145 case READ:
146 if (luid == null) {
147 luid = args[i];
148 } else if (chapString == null) {
149 chapString = args[i];
150 } else {
151 exitCode = 255;
08fe2e33 152 }
d0114000
NR
153 break;
154 case READ_URL:
155 if (urlString == null) {
156 urlString = args[i];
157 } else if (chapString == null) {
158 chapString = args[i];
159 } else {
160 exitCode = 255;
08fe2e33 161 }
d0114000
NR
162 break;
163 case HELP:
164 exitCode = 255;
165 break;
166 case SET_READER:
7de079f1 167 exitCode = setReaderType(args[i]);
c1873e56 168 action = MainAction.START;
d0114000 169 break;
333f0e7b
NR
170 case START:
171 exitCode = 255; // not supposed to be selected by user
172 break;
39c3c689
NR
173 case VERSION:
174 exitCode = 255; // no arguments for this option
b0e88ebd
NR
175 break;
176 case SERVER:
177 if (port == null) {
178 port = Integer.parseInt(args[i]);
179 } else {
180 exitCode = 255;
181 }
182 break;
183 case REMOTE:
184 if (host == null) {
185 host = args[i];
186 } else if (port == null) {
187 port = Integer.parseInt(args[i]);
68e2c6d2
NR
188 BasicReader
189 .setDefaultLibrary(new RemoteLibrary(host, port));
b0e88ebd
NR
190 action = MainAction.START;
191 } else {
192 exitCode = 255;
193 }
194 break;
d0114000
NR
195 }
196 }
197
92fb0719
NR
198 final Progress mainProgress = new Progress(0, 80);
199 mainProgress.addProgressListener(new Progress.ProgressListener() {
200 private int current = mainProgress.getMin();
201
202 public void progress(Progress progress, String name) {
203 int diff = progress.getProgress() - current;
204 current += diff;
205
206 StringBuilder builder = new StringBuilder();
207 for (int i = 0; i < diff; i++) {
208 builder.append('.');
209 }
210
211 System.err.print(builder.toString());
212
213 if (progress.isDone()) {
214 System.err.println("");
215 }
216 }
217 });
218 Progress pg = new Progress();
219 mainProgress.addProgress(pg, mainProgress.getMax());
220
b42117f1
NR
221 VersionCheck updates = VersionCheck.check();
222 if (updates.isNewVersionAvailable()) {
223 // Sent to syserr so not to cause problem if one tries to capture a
224 // story content in text mode
225 System.err
226 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
227 System.err.println("");
228 for (Version v : updates.getNewer()) {
229 System.err.println("\tVersion " + v);
230 System.err.println("\t-------------");
231 System.err.println("");
232 for (String item : updates.getChanges().get(v)) {
233 System.err.println("\t- " + item);
234 }
235 System.err.println("");
236 }
237 }
238
d0114000
NR
239 if (exitCode != 255) {
240 switch (action) {
241 case IMPORT:
92fb0719 242 exitCode = imprt(urlString, pg);
b42117f1 243 updates.ok(); // we consider it read
d0114000
NR
244 break;
245 case EXPORT:
b0e88ebd 246 exitCode = export(luid, sourceString, target, pg);
b42117f1 247 updates.ok(); // we consider it read
d0114000
NR
248 break;
249 case CONVERT:
b0e88ebd 250 exitCode = convert(urlString, sourceString, target,
92fb0719 251 plusInfo == null ? false : plusInfo, pg);
b42117f1 252 updates.ok(); // we consider it read
d0114000
NR
253 break;
254 case LIST:
b0e88ebd 255 exitCode = list(sourceString);
d0114000
NR
256 break;
257 case READ:
258 exitCode = read(luid, chapString, true);
259 break;
260 case READ_URL:
261 exitCode = read(urlString, chapString, false);
262 break;
263 case HELP:
264 syntax(true);
265 exitCode = 0;
266 break;
267 case SET_READER:
b0e88ebd 268 exitCode = 255;
d0114000 269 break;
39c3c689
NR
270 case VERSION:
271 System.out
272 .println(String.format("Fanfix version %s"
273 + "\nhttps://github.com/nikiroo/fanfix/"
274 + "\n\tWritten by Nikiroo",
275 Version.getCurrentVersion()));
b42117f1 276 updates.ok(); // we consider it read
39c3c689 277 break;
333f0e7b 278 case START:
b0e88ebd
NR
279 BasicReader.getReader().browse(null);
280 break;
281 case SERVER:
282 if (port == null) {
283 exitCode = 255;
284 break;
285 }
286 try {
287 Server server = new RemoteLibraryServer(port);
288 server.start();
289 System.out.println("Remote server started on: " + port);
290 } catch (IOException e) {
291 Instance.syserr(e);
292 }
293 return;
294 case REMOTE:
295 exitCode = 255;
333f0e7b 296 break;
08fe2e33
NR
297 }
298 }
299
300 if (exitCode == 255) {
d0114000 301 syntax(false);
08fe2e33
NR
302 }
303
304 if (exitCode != 0) {
305 System.exit(exitCode);
306 }
307 }
308
08fe2e33 309 /**
68e2c6d2 310 * Import the given resource into the {@link LocalLibrary}.
08fe2e33 311 *
d0114000 312 * @param urlString
08fe2e33 313 * the resource to import
92fb0719
NR
314 * @param pg
315 * the optional progress reporter
08fe2e33
NR
316 *
317 * @return the exit return code (0 = success)
318 */
92fb0719 319 public static int imprt(String urlString, Progress pg) {
08fe2e33 320 try {
3b2b638f
NR
321 Story story = Instance.getLibrary().imprt(
322 BasicReader.getUrl(urlString), pg);
08fe2e33
NR
323 System.out.println(story.getMeta().getLuid() + ": \""
324 + story.getMeta().getTitle() + "\" imported.");
325 } catch (IOException e) {
326 Instance.syserr(e);
327 return 1;
328 }
329
330 return 0;
331 }
332
333 /**
68e2c6d2
NR
334 * Export the {@link Story} from the {@link LocalLibrary} to the given
335 * target.
08fe2e33 336 *
73ce17ef 337 * @param luid
08fe2e33
NR
338 * the story LUID
339 * @param typeString
340 * the {@link OutputType} to use
341 * @param target
342 * the target
92fb0719
NR
343 * @param pg
344 * the optional progress reporter
08fe2e33
NR
345 *
346 * @return the exit return code (0 = success)
347 */
92fb0719
NR
348 public static int export(String luid, String typeString, String target,
349 Progress pg) {
08fe2e33
NR
350 OutputType type = OutputType.valueOfNullOkUC(typeString);
351 if (type == null) {
352 Instance.syserr(new Exception(trans(StringId.OUTPUT_DESC,
353 typeString)));
354 return 1;
355 }
356
357 try {
92fb0719 358 Instance.getLibrary().export(luid, type, target, pg);
08fe2e33
NR
359 } catch (IOException e) {
360 Instance.syserr(e);
361 return 4;
362 }
363
364 return 0;
365 }
366
367 /**
68e2c6d2
NR
368 * List the stories of the given source from the {@link LocalLibrary}
369 * (unless NULL is passed, in which case all stories will be listed).
08fe2e33 370 *
b0e88ebd
NR
371 * @param source
372 * the source to list the known stories of, or NULL to list all
333f0e7b 373 * stories
08fe2e33
NR
374 *
375 * @return the exit return code (0 = success)
376 */
b0e88ebd
NR
377 private static int list(String source) {
378 BasicReader.getReader().browse(source);
08fe2e33
NR
379 return 0;
380 }
381
382 /**
383 * Start the CLI reader for this {@link Story}.
384 *
385 * @param story
68e2c6d2
NR
386 * the LUID of the {@link Story} in the {@link LocalLibrary}
387 * <b>or</b> the {@link Story} {@link URL}
d0114000 388 * @param chapString
08fe2e33
NR
389 * which {@link Chapter} to read (starting at 1), or NULL to get
390 * the {@link Story} description
391 * @param library
392 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
393 * {@link URL}
394 *
395 * @return the exit return code (0 = success)
396 */
d0114000 397 private static int read(String story, String chapString, boolean library) {
08fe2e33 398 try {
e42573a0 399 Reader reader = BasicReader.getReader();
08fe2e33 400 if (library) {
bc2ea776 401 reader.setMeta(story);
08fe2e33 402 } else {
bc2ea776 403 reader.setMeta(BasicReader.getUrl(story), null);
08fe2e33
NR
404 }
405
d0114000
NR
406 if (chapString != null) {
407 try {
bc2ea776
NR
408 reader.setChapter(Integer.parseInt(chapString));
409 reader.read();
d0114000
NR
410 } catch (NumberFormatException e) {
411 Instance.syserr(new IOException(
412 "Chapter number cannot be parsed: " + chapString, e));
413 return 2;
414 }
08fe2e33
NR
415 } else {
416 reader.read();
417 }
418 } catch (IOException e) {
419 Instance.syserr(e);
420 return 1;
421 }
422
423 return 0;
424 }
425
426 /**
427 * Convert the {@link Story} into another format.
428 *
d0114000 429 * @param urlString
08fe2e33
NR
430 * the source {@link Story} to convert
431 * @param typeString
432 * the {@link OutputType} to convert to
d0114000 433 * @param target
08fe2e33
NR
434 * the target file
435 * @param infoCover
436 * TRUE to also export the cover and info file, even if the given
437 * {@link OutputType} does not usually save them
92fb0719
NR
438 * @param pg
439 * the optional progress reporter
08fe2e33
NR
440 *
441 * @return the exit return code (0 = success)
442 */
d0114000 443 private static int convert(String urlString, String typeString,
92fb0719 444 String target, boolean infoCover, Progress pg) {
08fe2e33
NR
445 int exitCode = 0;
446
d0114000 447 String sourceName = urlString;
08fe2e33 448 try {
3b2b638f 449 URL source = BasicReader.getUrl(urlString);
08fe2e33
NR
450 sourceName = source.toString();
451 if (source.toString().startsWith("file://")) {
452 sourceName = sourceName.substring("file://".length());
453 }
454
455 OutputType type = OutputType.valueOfAllOkUC(typeString);
456 if (type == null) {
457 Instance.syserr(new IOException(trans(
458 StringId.ERR_BAD_OUTPUT_TYPE, typeString)));
459
460 exitCode = 2;
461 } else {
462 try {
463 BasicSupport support = BasicSupport.getSupport(source);
333f0e7b 464
08fe2e33 465 if (support != null) {
bee7dffe
NR
466 Progress pgIn = new Progress();
467 Progress pgOut = new Progress();
468 if (pg != null) {
469 pg.setMax(2);
470 pg.addProgress(pgIn, 1);
471 pg.addProgress(pgOut, 1);
472 }
08fe2e33 473
bee7dffe 474 Story story = support.process(source, pgIn);
08fe2e33 475 try {
d0114000 476 target = new File(target).getAbsolutePath();
08fe2e33 477 BasicOutput.getOutput(type, infoCover).process(
bee7dffe 478 story, target, pgOut);
08fe2e33
NR
479 } catch (IOException e) {
480 Instance.syserr(new IOException(trans(
d0114000 481 StringId.ERR_SAVING, target), e));
08fe2e33
NR
482 exitCode = 5;
483 }
484 } else {
485 Instance.syserr(new IOException(trans(
486 StringId.ERR_NOT_SUPPORTED, source)));
487
488 exitCode = 4;
489 }
490 } catch (IOException e) {
491 Instance.syserr(new IOException(trans(StringId.ERR_LOADING,
492 sourceName), e));
493 exitCode = 3;
494 }
495 }
496 } catch (MalformedURLException e) {
497 Instance.syserr(new IOException(trans(StringId.ERR_BAD_URL,
498 sourceName), e));
499 exitCode = 1;
500 }
501
502 return exitCode;
503 }
504
505 /**
506 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
507 *
508 * @param id
509 * the ID to translate
510 *
511 * @return the translated result
512 */
513 private static String trans(StringId id, Object... params) {
514 return Instance.getTrans().getString(id, params);
515 }
516
517 /**
d0114000
NR
518 * Display the correct syntax of the program to the user to stdout, or an
519 * error message if the syntax used was wrong on stderr.
520 *
521 * @param showHelp
522 * TRUE to show the syntax help, FALSE to show "syntax error"
08fe2e33 523 */
d0114000
NR
524 private static void syntax(boolean showHelp) {
525 if (showHelp) {
526 StringBuilder builder = new StringBuilder();
527 for (SupportType type : SupportType.values()) {
528 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
529 type.getDesc()));
530 builder.append('\n');
531 }
08fe2e33 532
d0114000
NR
533 String typesIn = builder.toString();
534 builder.setLength(0);
08fe2e33 535
d0114000
NR
536 for (OutputType type : OutputType.values()) {
537 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
4d205683 538 type.getDesc(true)));
d0114000
NR
539 builder.append('\n');
540 }
08fe2e33 541
d0114000 542 String typesOut = builder.toString();
08fe2e33 543
d0114000
NR
544 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
545 } else {
546 System.err.println(trans(StringId.ERR_SYNTAX));
547 }
548 }
549
550 /**
551 * Set the default reader type for this session only (it can be changed in
552 * the configuration file, too, but this value will override it).
553 *
554 * @param readerTypeString
555 * the type
556 */
557 private static int setReaderType(String readerTypeString) {
558 try {
7de079f1
NR
559 ReaderType readerType = ReaderType.valueOf(readerTypeString
560 .toUpperCase());
d0114000
NR
561 BasicReader.setDefaultReaderType(readerType);
562 return 0;
563 } catch (IllegalArgumentException e) {
564 Instance.syserr(new IOException("Unknown reader type: "
565 + readerTypeString, e));
566 return 1;
567 }
08fe2e33
NR
568 }
569}