Update to latest version of nikiroo-utils
[nikiroo-utils.git] / src / be / nikiroo / fanfix / Main.java
... / ...
CommitLineData
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;
11import be.nikiroo.fanfix.library.LocalLibrary;
12import be.nikiroo.fanfix.library.RemoteLibrary;
13import be.nikiroo.fanfix.library.RemoteLibraryServer;
14import be.nikiroo.fanfix.output.BasicOutput;
15import be.nikiroo.fanfix.output.BasicOutput.OutputType;
16import be.nikiroo.fanfix.reader.BasicReader;
17import be.nikiroo.fanfix.reader.Reader;
18import be.nikiroo.fanfix.reader.Reader.ReaderType;
19import be.nikiroo.fanfix.supported.BasicSupport;
20import be.nikiroo.fanfix.supported.BasicSupport.SupportType;
21import be.nikiroo.utils.Progress;
22import be.nikiroo.utils.Version;
23import be.nikiroo.utils.serial.Server;
24
25/**
26 * Main program entry point.
27 *
28 * @author niki
29 */
30public class Main {
31 private enum MainAction {
32 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, SET_READER, START, VERSION, SERVER, REMOTE,
33 }
34
35 /**
36 * Main program entry point.
37 * <p>
38 * Known environment variables:
39 * <ul>
40 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
41 * {@link String}s when possible</li>
42 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
43 * before taking the usual ones; they will also be saved/updated into this
44 * path when the program starts</li>
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>
56 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
57 * story, without saving it</li>
58 * <li>--list ([type]): list the stories present in the library</li>
59 * <li>--set-reader [reader type]: set the reader type to CLI, TUI or LOCAL
60 * for this command</li>
61 * <li>--version: get the version of the program</li>
62 * <li>--server [port]: start a server on this port</li>
63 * <li>--remote [host] [port]: use a the given remote library</li>
64 * </ul>
65 *
66 * @param args
67 * see method description
68 */
69 public static void main(String[] args) {
70 String urlString = null;
71 String luid = null;
72 String sourceString = null;
73 String chapString = null;
74 String target = null;
75 MainAction action = MainAction.START;
76 Boolean plusInfo = null;
77 String host = null;
78 Integer port = null;
79
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 }
98
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];
113 } else if (sourceString == null) {
114 sourceString = args[i];
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];
124 } else if (sourceString == null) {
125 sourceString = args[i];
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;
136 }
137 break;
138 case LIST:
139 if (sourceString == null) {
140 sourceString = args[i];
141 } else {
142 exitCode = 255;
143 }
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;
152 }
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;
161 }
162 break;
163 case HELP:
164 exitCode = 255;
165 break;
166 case SET_READER:
167 exitCode = setReaderType(args[i]);
168 action = MainAction.START;
169 break;
170 case START:
171 exitCode = 255; // not supposed to be selected by user
172 break;
173 case VERSION:
174 exitCode = 255; // no arguments for this option
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]);
188 BasicReader
189 .setDefaultLibrary(new RemoteLibrary(host, port));
190 action = MainAction.START;
191 } else {
192 exitCode = 255;
193 }
194 break;
195 }
196 }
197
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
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
239 if (exitCode != 255) {
240 switch (action) {
241 case IMPORT:
242 exitCode = imprt(urlString, pg);
243 updates.ok(); // we consider it read
244 break;
245 case EXPORT:
246 exitCode = export(luid, sourceString, target, pg);
247 updates.ok(); // we consider it read
248 break;
249 case CONVERT:
250 exitCode = convert(urlString, sourceString, target,
251 plusInfo == null ? false : plusInfo, pg);
252 updates.ok(); // we consider it read
253 break;
254 case LIST:
255 exitCode = list(sourceString);
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:
268 exitCode = 255;
269 break;
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()));
276 updates.ok(); // we consider it read
277 break;
278 case START:
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;
296 break;
297 }
298 }
299
300 if (exitCode == 255) {
301 syntax(false);
302 }
303
304 if (exitCode != 0) {
305 System.exit(exitCode);
306 }
307 }
308
309 /**
310 * Import the given resource into the {@link LocalLibrary}.
311 *
312 * @param urlString
313 * the resource to import
314 * @param pg
315 * the optional progress reporter
316 *
317 * @return the exit return code (0 = success)
318 */
319 public static int imprt(String urlString, Progress pg) {
320 try {
321 Story story = Instance.getLibrary().imprt(
322 BasicReader.getUrl(urlString), pg);
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 /**
334 * Export the {@link Story} from the {@link LocalLibrary} to the given
335 * target.
336 *
337 * @param luid
338 * the story LUID
339 * @param typeString
340 * the {@link OutputType} to use
341 * @param target
342 * the target
343 * @param pg
344 * the optional progress reporter
345 *
346 * @return the exit return code (0 = success)
347 */
348 public static int export(String luid, String typeString, String target,
349 Progress pg) {
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 {
358 Instance.getLibrary().export(luid, type, target, pg);
359 } catch (IOException e) {
360 Instance.syserr(e);
361 return 4;
362 }
363
364 return 0;
365 }
366
367 /**
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).
370 *
371 * @param source
372 * the source to list the known stories of, or NULL to list all
373 * stories
374 *
375 * @return the exit return code (0 = success)
376 */
377 private static int list(String source) {
378 BasicReader.getReader().browse(source);
379 return 0;
380 }
381
382 /**
383 * Start the CLI reader for this {@link Story}.
384 *
385 * @param story
386 * the LUID of the {@link Story} in the {@link LocalLibrary}
387 * <b>or</b> the {@link Story} {@link URL}
388 * @param chapString
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 */
397 private static int read(String story, String chapString, boolean library) {
398 try {
399 Reader reader = BasicReader.getReader();
400 if (library) {
401 reader.setMeta(story);
402 } else {
403 reader.setMeta(BasicReader.getUrl(story), null);
404 }
405
406 if (chapString != null) {
407 try {
408 reader.setChapter(Integer.parseInt(chapString));
409 reader.read();
410 } catch (NumberFormatException e) {
411 Instance.syserr(new IOException(
412 "Chapter number cannot be parsed: " + chapString, e));
413 return 2;
414 }
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 *
429 * @param urlString
430 * the source {@link Story} to convert
431 * @param typeString
432 * the {@link OutputType} to convert to
433 * @param target
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
438 * @param pg
439 * the optional progress reporter
440 *
441 * @return the exit return code (0 = success)
442 */
443 private static int convert(String urlString, String typeString,
444 String target, boolean infoCover, Progress pg) {
445 int exitCode = 0;
446
447 String sourceName = urlString;
448 try {
449 URL source = BasicReader.getUrl(urlString);
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);
464
465 if (support != null) {
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 }
473
474 Story story = support.process(source, pgIn);
475 try {
476 target = new File(target).getAbsolutePath();
477 BasicOutput.getOutput(type, infoCover).process(
478 story, target, pgOut);
479 } catch (IOException e) {
480 Instance.syserr(new IOException(trans(
481 StringId.ERR_SAVING, target), e));
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 /**
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"
523 */
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 }
532
533 String typesIn = builder.toString();
534 builder.setLength(0);
535
536 for (OutputType type : OutputType.values()) {
537 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
538 type.getDesc(true)));
539 builder.append('\n');
540 }
541
542 String typesOut = builder.toString();
543
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 {
559 ReaderType readerType = ReaderType.valueOf(readerTypeString
560 .toUpperCase());
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 }
568 }
569}