Remote: now with a pin code
[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
8 import be.nikiroo.fanfix.bundles.StringId;
9 import be.nikiroo.fanfix.data.Chapter;
10 import be.nikiroo.fanfix.data.Story;
11 import be.nikiroo.fanfix.library.BasicLibrary;
12 import be.nikiroo.fanfix.library.CacheLibrary;
13 import be.nikiroo.fanfix.library.LocalLibrary;
14 import be.nikiroo.fanfix.library.RemoteLibrary;
15 import be.nikiroo.fanfix.library.RemoteLibraryServer;
16 import be.nikiroo.fanfix.output.BasicOutput;
17 import be.nikiroo.fanfix.output.BasicOutput.OutputType;
18 import be.nikiroo.fanfix.reader.BasicReader;
19 import be.nikiroo.fanfix.reader.Reader;
20 import be.nikiroo.fanfix.reader.Reader.ReaderType;
21 import be.nikiroo.fanfix.supported.BasicSupport;
22 import be.nikiroo.fanfix.supported.BasicSupport.SupportType;
23 import be.nikiroo.utils.Progress;
24 import be.nikiroo.utils.Version;
25 import be.nikiroo.utils.serial.ConnectActionClient;
26 import be.nikiroo.utils.serial.Server;
27
28 /**
29 * Main program entry point.
30 *
31 * @author niki
32 */
33 public class Main {
34 private enum MainAction {
35 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, SET_READER, START, VERSION, SERVER, STOP_SERVER, REMOTE,
36 }
37
38 /**
39 * Main program entry point.
40 * <p>
41 * Known environment variables:
42 * <ul>
43 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
44 * {@link String}s when possible</li>
45 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
46 * before taking the usual ones; they will also be saved/updated into this
47 * path when the program starts</li>
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>
59 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
60 * story, without saving it</li>
61 * <li>--list ([type]): list the stories present in the library</li>
62 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
63 * for this command</li>
64 * <li>--version: get the version of the program</li>
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>
69 * </ul>
70 *
71 * @param args
72 * see method description
73 */
74 public static void main(String[] args) {
75 String urlString = null;
76 String luid = null;
77 String sourceString = null;
78 String chapString = null;
79 String target = null;
80 String key = null;
81 MainAction action = MainAction.START;
82 Boolean plusInfo = null;
83 String host = null;
84 Integer port = null;
85
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 }
104
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];
119 } else if (sourceString == null) {
120 sourceString = args[i];
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];
130 } else if (sourceString == null) {
131 sourceString = args[i];
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;
142 }
143 break;
144 case LIST:
145 if (sourceString == null) {
146 sourceString = args[i];
147 } else {
148 exitCode = 255;
149 }
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;
158 }
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;
167 }
168 break;
169 case HELP:
170 exitCode = 255;
171 break;
172 case SET_READER:
173 exitCode = setReaderType(args[i]);
174 action = MainAction.START;
175 break;
176 case START:
177 exitCode = 255; // not supposed to be selected by user
178 break;
179 case VERSION:
180 exitCode = 255; // no arguments for this option
181 break;
182 case SERVER:
183 case STOP_SERVER:
184 if (key == null) {
185 key = args[i];
186 } else if (port == null) {
187 port = Integer.parseInt(args[i]);
188 } else {
189 exitCode = 255;
190 }
191 break;
192 case REMOTE:
193 if (key == null) {
194 key = args[i];
195 } else if (host == null) {
196 host = args[i];
197 } else if (port == null) {
198 port = Integer.parseInt(args[i]);
199
200 File remoteCacheDir = Instance.getRemoteDir(host);
201 BasicLibrary lib = new RemoteLibrary(key, host, port);
202 lib = new CacheLibrary(remoteCacheDir, lib);
203
204 BasicReader.setDefaultLibrary(lib);
205
206 action = MainAction.START;
207 } else {
208 exitCode = 255;
209 }
210 break;
211 }
212 }
213
214 final Progress mainProgress = new Progress(0, 80);
215 mainProgress.addProgressListener(new Progress.ProgressListener() {
216 private int current = mainProgress.getMin();
217
218 @Override
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
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
256 if (exitCode != 255) {
257 switch (action) {
258 case IMPORT:
259 exitCode = imprt(urlString, pg);
260 updates.ok(); // we consider it read
261 break;
262 case EXPORT:
263 exitCode = export(luid, sourceString, target, pg);
264 updates.ok(); // we consider it read
265 break;
266 case CONVERT:
267 exitCode = convert(urlString, sourceString, target,
268 plusInfo == null ? false : plusInfo, pg);
269 updates.ok(); // we consider it read
270 break;
271 case LIST:
272 if (BasicReader.getReader() == null) {
273 Instance.syserr(new Exception(
274 "No reader type has been configured"));
275 exitCode = 10;
276 break;
277 }
278 exitCode = list(sourceString);
279 break;
280 case READ:
281 if (BasicReader.getReader() == null) {
282 Instance.syserr(new Exception(
283 "No reader type has been configured"));
284 exitCode = 10;
285 break;
286 }
287 exitCode = read(luid, chapString, true);
288 break;
289 case READ_URL:
290 if (BasicReader.getReader() == null) {
291 Instance.syserr(new Exception(
292 "No reader type has been configured"));
293 exitCode = 10;
294 break;
295 }
296 exitCode = read(urlString, chapString, false);
297 break;
298 case HELP:
299 syntax(true);
300 exitCode = 0;
301 break;
302 case SET_READER:
303 exitCode = 255;
304 break;
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()));
311 updates.ok(); // we consider it read
312 break;
313 case START:
314 if (BasicReader.getReader() == null) {
315 Instance.syserr(new Exception(
316 "No reader type has been configured"));
317 exitCode = 10;
318 break;
319 }
320 BasicReader.getReader().browse(null);
321 break;
322 case SERVER:
323 if (port == null) {
324 exitCode = 255;
325 break;
326 }
327 try {
328 Server server = new RemoteLibraryServer(key, port);
329 server.start();
330 System.out.println("Remote server started on: " + port);
331 } catch (IOException e) {
332 Instance.syserr(e);
333 }
334 return;
335 case STOP_SERVER:
336 if (port == null) {
337 exitCode = 255;
338 break;
339 }
340
341 try {
342 final String fkey = key;
343 new ConnectActionClient(host, port, true) {
344 @Override
345 public void action(Version serverVersion)
346 throws Exception {
347 try {
348 send(new Object[] { fkey, "EXIT" });
349 } catch (Exception e) {
350 Instance.syserr(e);
351 }
352 }
353 }.connect();
354 } catch (IOException e) {
355 Instance.syserr(e);
356 }
357 break;
358 case REMOTE:
359 exitCode = 255; // should not be reachable (REMOTE -> START)
360 break;
361 }
362 }
363
364 if (exitCode == 255) {
365 syntax(false);
366 }
367
368 if (exitCode != 0) {
369 System.exit(exitCode);
370 }
371 }
372
373 /**
374 * Import the given resource into the {@link LocalLibrary}.
375 *
376 * @param urlString
377 * the resource to import
378 * @param pg
379 * the optional progress reporter
380 *
381 * @return the exit return code (0 = success)
382 */
383 public static int imprt(String urlString, Progress pg) {
384 try {
385 Story story = Instance.getLibrary().imprt(
386 BasicReader.getUrl(urlString), pg);
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 /**
398 * Export the {@link Story} from the {@link LocalLibrary} to the given
399 * target.
400 *
401 * @param luid
402 * the story LUID
403 * @param typeString
404 * the {@link OutputType} to use
405 * @param target
406 * the target
407 * @param pg
408 * the optional progress reporter
409 *
410 * @return the exit return code (0 = success)
411 */
412 public static int export(String luid, String typeString, String target,
413 Progress pg) {
414 OutputType type = OutputType.valueOfNullOkUC(typeString, null);
415 if (type == null) {
416 Instance.syserr(new Exception(trans(StringId.OUTPUT_DESC,
417 typeString)));
418 return 1;
419 }
420
421 try {
422 Instance.getLibrary().export(luid, type, target, pg);
423 } catch (IOException e) {
424 Instance.syserr(e);
425 return 4;
426 }
427
428 return 0;
429 }
430
431 /**
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).
434 *
435 * @param source
436 * the source to list the known stories of, or NULL to list all
437 * stories
438 *
439 * @return the exit return code (0 = success)
440 */
441 private static int list(String source) {
442 BasicReader.getReader().browse(source);
443 return 0;
444 }
445
446 /**
447 * Start the CLI reader for this {@link Story}.
448 *
449 * @param story
450 * the LUID of the {@link Story} in the {@link LocalLibrary}
451 * <b>or</b> the {@link Story} {@link URL}
452 * @param chapString
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 */
461 private static int read(String story, String chapString, boolean library) {
462 try {
463 Reader reader = BasicReader.getReader();
464 if (library) {
465 reader.setMeta(story);
466 } else {
467 reader.setMeta(BasicReader.getUrl(story), null);
468 }
469
470 if (chapString != null) {
471 try {
472 reader.setChapter(Integer.parseInt(chapString));
473 reader.read();
474 } catch (NumberFormatException e) {
475 Instance.syserr(new IOException(
476 "Chapter number cannot be parsed: " + chapString, e));
477 return 2;
478 }
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 *
493 * @param urlString
494 * the source {@link Story} to convert
495 * @param typeString
496 * the {@link OutputType} to convert to
497 * @param target
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
502 * @param pg
503 * the optional progress reporter
504 *
505 * @return the exit return code (0 = success)
506 */
507 private static int convert(String urlString, String typeString,
508 String target, boolean infoCover, Progress pg) {
509 int exitCode = 0;
510
511 String sourceName = urlString;
512 try {
513 URL source = BasicReader.getUrl(urlString);
514 sourceName = source.toString();
515 if (source.toString().startsWith("file://")) {
516 sourceName = sourceName.substring("file://".length());
517 }
518
519 OutputType type = OutputType.valueOfAllOkUC(typeString, null);
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);
528
529 if (support != null) {
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 }
537
538 Story story = support.process(source, pgIn);
539 try {
540 target = new File(target).getAbsolutePath();
541 BasicOutput.getOutput(type, infoCover).process(
542 story, target, pgOut);
543 } catch (IOException e) {
544 Instance.syserr(new IOException(trans(
545 StringId.ERR_SAVING, target), e));
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 /**
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"
587 */
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 }
596
597 String typesIn = builder.toString();
598 builder.setLength(0);
599
600 for (OutputType type : OutputType.values()) {
601 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
602 type.getDesc(true)));
603 builder.append('\n');
604 }
605
606 String typesOut = builder.toString();
607
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 {
623 ReaderType readerType = ReaderType.valueOf(readerTypeString
624 .toUpperCase());
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 }
632 }
633 }