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