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