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