woops, forgot half of them
[nikiroo-utils.git] / 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;
91b82a5c 7import java.util.ArrayList;
f569d249 8import java.util.List;
08fe2e33 9
0bb51c9c
NR
10import javax.net.ssl.SSLException;
11
fb25273c 12import be.nikiroo.fanfix.bundles.Config;
08fe2e33
NR
13import be.nikiroo.fanfix.bundles.StringId;
14import be.nikiroo.fanfix.data.Chapter;
b6b65795 15import be.nikiroo.fanfix.data.MetaData;
08fe2e33 16import be.nikiroo.fanfix.data.Story;
ff05b828
NR
17import be.nikiroo.fanfix.library.BasicLibrary;
18import be.nikiroo.fanfix.library.CacheLibrary;
e42573a0
NR
19import be.nikiroo.fanfix.library.LocalLibrary;
20import be.nikiroo.fanfix.library.RemoteLibrary;
21import be.nikiroo.fanfix.library.RemoteLibraryServer;
08fe2e33
NR
22import be.nikiroo.fanfix.output.BasicOutput;
23import be.nikiroo.fanfix.output.BasicOutput.OutputType;
3727aae2 24import be.nikiroo.fanfix.reader.BasicReader;
9b75402f 25import be.nikiroo.fanfix.reader.CliReader;
91b82a5c 26import be.nikiroo.fanfix.searchable.BasicSearchable;
08fe2e33 27import be.nikiroo.fanfix.supported.BasicSupport;
0ffa4754 28import be.nikiroo.fanfix.supported.SupportType;
3b2b638f 29import be.nikiroo.utils.Progress;
39c3c689 30import be.nikiroo.utils.Version;
62c63b07 31import be.nikiroo.utils.serial.server.ServerObject;
08fe2e33
NR
32
33/**
34 * Main program entry point.
35 *
36 * @author niki
37 */
38public class Main {
d0114000 39 private enum MainAction {
9b75402f 40 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, START, VERSION, SERVER, STOP_SERVER, REMOTE, SET_SOURCE, SET_TITLE, SET_AUTHOR, SEARCH, SEARCH_TAG
d0114000
NR
41 }
42
08fe2e33
NR
43 /**
44 * Main program entry point.
45 * <p>
46 * Known environment variables:
47 * <ul>
d0114000 48 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
08fe2e33
NR
49 * {@link String}s when possible</li>
50 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
edd46289
NR
51 * before taking the usual ones; they will also be saved/updated into this
52 * path when the program starts</li>
d0114000
NR
53 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
54 * configuration value with 'true'</li>
55 * </ul>
56 * <p>
57 * <ul>
58 * <li>--import [URL]: import into library</li>
59 * <li>--export [id] [output_type] [target]: export story to target</li>
60 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
61 * target</li>
62 * <li>--read [id] ([chapter number]): read the given story from the library
63 * </li>
333f0e7b 64 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
d0114000 65 * story, without saving it</li>
8b153400
NR
66 * <li>--search: list the supported websites (where)</li>
67 * <li>--search [where] [keywords] (page [page]) (item [item]): search on
68 * the supported website and display the given results page of stories it
69 * found, or the story details if asked</li>
8141d7ac
NR
70 * <li>--search-tag [where]: list all the tags supported by this website</li>
71 * <li>--search-tag [index 1]... (page [page]) (item [item]): search for the
72 * given stories or subtags, tag by tag, and display information about a
73 * specific page of results or about a specific item if requested</li>
333f0e7b 74 * <li>--list ([type]): list the stories present in the library</li>
e10b51a2
NR
75 * <li>--set-source [id] [new source]: change the source of the given story</li>
76 * <li>--set-title [id] [new title]: change the title of the given story</li>
77 * <li>--set-author [id] [new author]: change the author of the given story</li>
39c3c689 78 * <li>--version: get the version of the program</li>
fb25273c
NR
79 * <li>--server: start the server mode (see config file for parameters)</li>
80 * <li>--stop-server: stop the running server on this port if any</li>
2070ced5 81 * <li>--remote [key] [host] [port]: use a the given remote library</li>
08fe2e33
NR
82 * </ul>
83 *
84 * @param args
d0114000 85 * see method description
08fe2e33
NR
86 */
87 public static void main(String[] args) {
ee9b7083
NR
88 // Only one line, but very important:
89 Instance.init();
90
d0114000
NR
91 String urlString = null;
92 String luid = null;
b0e88ebd 93 String sourceString = null;
e10b51a2
NR
94 String titleString = null;
95 String authorString = null;
d0114000
NR
96 String chapString = null;
97 String target = null;
2070ced5 98 String key = null;
333f0e7b 99 MainAction action = MainAction.START;
d0114000 100 Boolean plusInfo = null;
b0e88ebd
NR
101 String host = null;
102 Integer port = null;
91b82a5c
NR
103 SupportType searchOn = null;
104 String search = null;
8b153400 105 List<Integer> tags = new ArrayList<Integer>();
91b82a5c
NR
106 Integer page = null;
107 Integer item = null;
73ce17ef 108
d0114000
NR
109 boolean noMoreActions = false;
110
111 int exitCode = 0;
112 for (int i = 0; exitCode == 0 && i < args.length; i++) {
113 // Action (--) handling:
114 if (!noMoreActions && args[i].startsWith("--")) {
115 if (args[i].equals("--")) {
116 noMoreActions = true;
117 } else {
118 try {
119 action = MainAction.valueOf(args[i].substring(2)
120 .toUpperCase().replace("-", "_"));
121 } catch (Exception e) {
d66deb8d
NR
122 Instance.getInstance().getTraceHandler()
123 .error(new IllegalArgumentException("Unknown action: " + args[i], e));
d0114000
NR
124 exitCode = 255;
125 }
126 }
08fe2e33 127
d0114000
NR
128 continue;
129 }
130
131 switch (action) {
132 case IMPORT:
133 if (urlString == null) {
134 urlString = args[i];
135 } else {
136 exitCode = 255;
137 }
138 break;
139 case EXPORT:
140 if (luid == null) {
141 luid = args[i];
b0e88ebd
NR
142 } else if (sourceString == null) {
143 sourceString = args[i];
d0114000
NR
144 } else if (target == null) {
145 target = args[i];
146 } else {
147 exitCode = 255;
148 }
149 break;
150 case CONVERT:
151 if (urlString == null) {
152 urlString = args[i];
b0e88ebd
NR
153 } else if (sourceString == null) {
154 sourceString = args[i];
d0114000
NR
155 } else if (target == null) {
156 target = args[i];
157 } else if (plusInfo == null) {
158 if ("+info".equals(args[i])) {
159 plusInfo = true;
160 } else {
161 exitCode = 255;
162 }
163 } else {
164 exitCode = 255;
08fe2e33 165 }
d0114000
NR
166 break;
167 case LIST:
b0e88ebd
NR
168 if (sourceString == null) {
169 sourceString = args[i];
d0114000
NR
170 } else {
171 exitCode = 255;
08fe2e33 172 }
d0114000 173 break;
e10b51a2
NR
174 case SET_SOURCE:
175 if (luid == null) {
176 luid = args[i];
177 } else if (sourceString == null) {
178 sourceString = args[i];
179 } else {
180 exitCode = 255;
181 }
182 break;
183 case SET_TITLE:
184 if (luid == null) {
185 luid = args[i];
186 } else if (sourceString == null) {
187 titleString = args[i];
188 } else {
189 exitCode = 255;
190 }
191 break;
192 case SET_AUTHOR:
193 if (luid == null) {
194 luid = args[i];
195 } else if (sourceString == null) {
196 authorString = args[i];
197 } else {
198 exitCode = 255;
199 }
200 break;
d0114000
NR
201 case READ:
202 if (luid == null) {
203 luid = args[i];
204 } else if (chapString == null) {
205 chapString = args[i];
206 } else {
207 exitCode = 255;
08fe2e33 208 }
d0114000
NR
209 break;
210 case READ_URL:
211 if (urlString == null) {
212 urlString = args[i];
213 } else if (chapString == null) {
214 chapString = args[i];
215 } else {
216 exitCode = 255;
08fe2e33 217 }
d0114000 218 break;
91b82a5c
NR
219 case SEARCH:
220 if (searchOn == null) {
221 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 222
91b82a5c 223 if (searchOn == null) {
d66deb8d 224 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
b31a0db0
NR
225 exitCode = 41;
226 break;
91b82a5c 227 }
8b153400 228
91b82a5c 229 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 230 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
b31a0db0
NR
231 exitCode = 42;
232 break;
91b82a5c
NR
233 }
234 } else if (search == null) {
235 search = args[i];
8b153400 236 } else if (page != null && page == -1) {
91b82a5c
NR
237 try {
238 page = Integer.parseInt(args[i]);
8b153400
NR
239 } catch (Exception e) {
240 page = -2;
91b82a5c 241 }
8b153400 242 } else if (item != null && item == -1) {
91b82a5c
NR
243 try {
244 item = Integer.parseInt(args[i]);
8b153400
NR
245 } catch (Exception e) {
246 item = -2;
247 }
248 } else if (page == null || item == null) {
249 if (page == null && "page".equals(args[i])) {
250 page = -1;
251 } else if (item == null && "item".equals(args[i])) {
252 item = -1;
253 } else {
91b82a5c
NR
254 exitCode = 255;
255 }
256 } else {
257 exitCode = 255;
258 }
259 break;
8141d7ac 260 case SEARCH_TAG:
91b82a5c
NR
261 if (searchOn == null) {
262 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 263
91b82a5c 264 if (searchOn == null) {
d66deb8d 265 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
91b82a5c
NR
266 exitCode = 255;
267 }
8b153400 268
91b82a5c 269 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 270 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
91b82a5c
NR
271 exitCode = 255;
272 }
8b153400
NR
273 } else if (page == null && item == null) {
274 if ("page".equals(args[i])) {
275 page = -1;
276 } else if ("item".equals(args[i])) {
277 item = -1;
278 } else {
279 try {
280 int index = Integer.parseInt(args[i]);
281 tags.add(index);
282 } catch (NumberFormatException e) {
d66deb8d 283 Instance.getInstance().getTraceHandler().error("Invalid tag index: " + args[i]);
8b153400
NR
284 exitCode = 255;
285 }
286 }
287 } else if (page != null && page == -1) {
288 try {
289 page = Integer.parseInt(args[i]);
290 } catch (Exception e) {
291 page = -2;
292 }
293 } else if (item != null && item == -1) {
294 try {
295 item = Integer.parseInt(args[i]);
296 } catch (Exception e) {
297 item = -2;
298 }
299 } else if (page == null || item == null) {
300 if (page == null && "page".equals(args[i])) {
301 page = -1;
302 } else if (item == null && "item".equals(args[i])) {
303 item = -1;
304 } else {
305 exitCode = 255;
306 }
91b82a5c 307 } else {
8b153400 308 exitCode = 255;
91b82a5c
NR
309 }
310 break;
d0114000
NR
311 case HELP:
312 exitCode = 255;
313 break;
333f0e7b
NR
314 case START:
315 exitCode = 255; // not supposed to be selected by user
316 break;
39c3c689
NR
317 case VERSION:
318 exitCode = 255; // no arguments for this option
b0e88ebd
NR
319 break;
320 case SERVER:
fb25273c
NR
321 exitCode = 255; // no arguments for this option
322 break;
5e848e6a 323 case STOP_SERVER:
fb25273c 324 exitCode = 255; // no arguments for this option
b0e88ebd
NR
325 break;
326 case REMOTE:
2070ced5
NR
327 if (key == null) {
328 key = args[i];
329 } else if (host == null) {
b0e88ebd
NR
330 host = args[i];
331 } else if (port == null) {
332 port = Integer.parseInt(args[i]);
ff05b828 333
2070ced5 334 BasicLibrary lib = new RemoteLibrary(key, host, port);
9b75402f
NR
335 lib = new CacheLibrary(
336 Instance.getInstance().getRemoteDir(host), lib,
d66deb8d 337 Instance.getInstance().getUiConfig());
ff05b828 338
9b75402f 339 Instance.getInstance().setLibrary(lib);
5e848e6a 340
b0e88ebd
NR
341 action = MainAction.START;
342 } else {
343 exitCode = 255;
344 }
345 break;
d0114000
NR
346 }
347 }
348
92fb0719
NR
349 final Progress mainProgress = new Progress(0, 80);
350 mainProgress.addProgressListener(new Progress.ProgressListener() {
351 private int current = mainProgress.getMin();
352
211f7ddb 353 @Override
92fb0719
NR
354 public void progress(Progress progress, String name) {
355 int diff = progress.getProgress() - current;
356 current += diff;
357
1822d603
NR
358 if (diff <= 0)
359 return;
360
92fb0719
NR
361 StringBuilder builder = new StringBuilder();
362 for (int i = 0; i < diff; i++) {
363 builder.append('.');
364 }
365
366 System.err.print(builder.toString());
367
368 if (progress.isDone()) {
369 System.err.println("");
370 }
371 }
372 });
373 Progress pg = new Progress();
374 mainProgress.addProgress(pg, mainProgress.getMax());
375
b42117f1
NR
376 VersionCheck updates = VersionCheck.check();
377 if (updates.isNewVersionAvailable()) {
378 // Sent to syserr so not to cause problem if one tries to capture a
379 // story content in text mode
380 System.err
381 .println("A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
382 System.err.println("");
383 for (Version v : updates.getNewer()) {
384 System.err.println("\tVersion " + v);
385 System.err.println("\t-------------");
386 System.err.println("");
91b82a5c
NR
387 for (String it : updates.getChanges().get(v)) {
388 System.err.println("\t- " + it);
b42117f1
NR
389 }
390 System.err.println("");
391 }
392 }
393
b31a0db0 394 if (exitCode == 0) {
d0114000
NR
395 switch (action) {
396 case IMPORT:
92fb0719 397 exitCode = imprt(urlString, pg);
b42117f1 398 updates.ok(); // we consider it read
d0114000
NR
399 break;
400 case EXPORT:
b0e88ebd 401 exitCode = export(luid, sourceString, target, pg);
b42117f1 402 updates.ok(); // we consider it read
d0114000
NR
403 break;
404 case CONVERT:
b0e88ebd 405 exitCode = convert(urlString, sourceString, target,
92fb0719 406 plusInfo == null ? false : plusInfo, pg);
b42117f1 407 updates.ok(); // we consider it read
d0114000
NR
408 break;
409 case LIST:
b0e88ebd 410 exitCode = list(sourceString);
d0114000 411 break;
e10b51a2
NR
412 case SET_SOURCE:
413 try {
d66deb8d 414 Instance.getInstance().getLibrary().changeSource(luid, sourceString, pg);
e10b51a2 415 } catch (IOException e1) {
d66deb8d 416 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
417 exitCode = 21;
418 }
419 break;
420 case SET_TITLE:
421 try {
d66deb8d 422 Instance.getInstance().getLibrary().changeTitle(luid, titleString, pg);
e10b51a2 423 } catch (IOException e1) {
d66deb8d 424 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
425 exitCode = 22;
426 }
427 break;
428 case SET_AUTHOR:
429 try {
d66deb8d 430 Instance.getInstance().getLibrary().changeAuthor(luid, authorString, pg);
e10b51a2 431 } catch (IOException e1) {
d66deb8d 432 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
433 exitCode = 23;
434 }
435 break;
d0114000 436 case READ:
9b75402f
NR
437 if (luid == null || luid.isEmpty()) {
438 syntax(false);
439 exitCode = 255;
99ccbdf6
NR
440 break;
441 }
9b75402f
NR
442
443 try {
444 BasicLibrary lib = Instance.getInstance().getLibrary();
445 exitCode = read(lib.getStory(luid, null), chapString);
446 } catch (IOException e) {
447 Instance.getInstance().getTraceHandler()
448 .error(new IOException("Failed to read book", e));
449 exitCode = 2;
450 }
451
d0114000
NR
452 break;
453 case READ_URL:
9b75402f
NR
454 if (urlString == null || urlString.isEmpty()) {
455 syntax(false);
456 exitCode = 255;
99ccbdf6
NR
457 break;
458 }
9b75402f
NR
459
460 try {
461 BasicSupport support = BasicSupport
462 .getSupport(BasicReader.getUrl(urlString));
463 if (support == null) {
464 Instance.getInstance().getTraceHandler()
465 .error("URL not supported: " + urlString);
466 exitCode = 2;
467 break;
468 }
469
470 exitCode = read(support.process(null), chapString);
471 } catch (IOException e) {
472 Instance.getInstance().getTraceHandler()
473 .error(new IOException("Failed to read book", e));
474 exitCode = 2;
475 }
476
91b82a5c
NR
477 break;
478 case SEARCH:
8b153400
NR
479 page = page == null ? 1 : page;
480 if (page < 0) {
d66deb8d 481 Instance.getInstance().getTraceHandler().error("Incorrect page number");
91b82a5c
NR
482 exitCode = 255;
483 break;
484 }
8b153400
NR
485
486 item = item == null ? 0 : item;
487 if (item < 0) {
d66deb8d 488 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
489 exitCode = 255;
490 break;
91b82a5c 491 }
8b153400 492
b31a0db0
NR
493 try {
494 if (searchOn == null) {
9b75402f 495 new CliReader().listSearchables();
b31a0db0
NR
496 } else if (search != null) {
497
9b75402f
NR
498 new CliReader().searchBooksByKeyword(searchOn, search, page,
499 item);
b31a0db0
NR
500 } else {
501 exitCode = 255;
8b153400 502 }
b31a0db0 503 } catch (IOException e1) {
d66deb8d 504 Instance.getInstance().getTraceHandler().error(e1);
b31a0db0 505 exitCode = 20;
91b82a5c 506 }
8b153400 507
91b82a5c 508 break;
8141d7ac 509 case SEARCH_TAG:
91b82a5c
NR
510 if (searchOn == null) {
511 exitCode = 255;
512 break;
513 }
91b82a5c 514
8b153400
NR
515 page = page == null ? 1 : page;
516 if (page < 0) {
d66deb8d 517 Instance.getInstance().getTraceHandler().error("Incorrect page number");
8b153400
NR
518 exitCode = 255;
519 break;
91b82a5c 520 }
8b153400
NR
521
522 item = item == null ? 0 : item;
523 if (item < 0) {
d66deb8d 524 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
525 exitCode = 255;
526 break;
527 }
528
91b82a5c 529 try {
9b75402f
NR
530 new CliReader().searchBooksByTag(searchOn, page, item,
531 tags.toArray(new Integer[] {}));
91b82a5c 532 } catch (IOException e1) {
d66deb8d 533 Instance.getInstance().getTraceHandler().error(e1);
91b82a5c 534 }
8b153400 535
d0114000
NR
536 break;
537 case HELP:
538 syntax(true);
539 exitCode = 0;
540 break;
39c3c689
NR
541 case VERSION:
542 System.out
543 .println(String.format("Fanfix version %s"
9fe3f177
NR
544 + "%nhttps://github.com/nikiroo/fanfix/"
545 + "%n\tWritten by Nikiroo",
39c3c689 546 Version.getCurrentVersion()));
b42117f1 547 updates.ok(); // we consider it read
39c3c689 548 break;
333f0e7b 549 case START:
0bb51c9c 550 try {
9b75402f 551 new CliReader().listBooks(null);
0bb51c9c 552 } catch (IOException e) {
d66deb8d 553 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
554 exitCode = 66;
555 }
b0e88ebd
NR
556 break;
557 case SERVER:
d66deb8d
NR
558 key = Instance.getInstance().getConfig().getString(Config.SERVER_KEY);
559 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
b0e88ebd 560 if (port == null) {
fb25273c
NR
561 System.err.println("No port configured in the config file");
562 exitCode = 15;
b0e88ebd
NR
563 break;
564 }
565 try {
62c63b07 566 ServerObject server = new RemoteLibraryServer(key, port);
d66deb8d 567 server.setTraceHandler(Instance.getInstance().getTraceHandler());
edf79e5e 568 server.run();
b0e88ebd 569 } catch (IOException e) {
d66deb8d 570 Instance.getInstance().getTraceHandler().error(e);
b0e88ebd
NR
571 }
572 return;
5e848e6a 573 case STOP_SERVER:
aad0e5ae
NR
574 // Can be given via "--remote XX XX XX"
575 if (key == null)
d66deb8d 576 key = Instance.getInstance().getConfig().getString(Config.SERVER_KEY);
aad0e5ae 577 if (port == null)
d66deb8d 578 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
aad0e5ae 579
5e848e6a 580 if (port == null) {
aad0e5ae 581 System.err.println("No port given nor configured in the config file");
fb25273c 582 exitCode = 15;
5e848e6a
NR
583 break;
584 }
0bb51c9c
NR
585 try {
586 new RemoteLibrary(key, host, port).exit();
587 } catch (SSLException e) {
d66deb8d 588 Instance.getInstance().getTraceHandler().error(
0bb51c9c
NR
589 "Bad access key for remote library");
590 exitCode = 43;
591 } catch (IOException e) {
d66deb8d 592 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
593 exitCode = 44;
594 }
5e848e6a 595
5e848e6a 596 break;
b0e88ebd 597 case REMOTE:
99ccbdf6 598 exitCode = 255; // should not be reachable (REMOTE -> START)
333f0e7b 599 break;
08fe2e33
NR
600 }
601 }
602
350bc060 603 try {
d66deb8d 604 Instance.getInstance().getTempFiles().close();
350bc060 605 } catch (IOException e) {
d66deb8d 606 Instance.getInstance().getTraceHandler().error(new IOException("Cannot dispose of the temporary files", e));
2aac79c7
NR
607 }
608
08fe2e33 609 if (exitCode == 255) {
d0114000 610 syntax(false);
08fe2e33
NR
611 }
612
31e28683 613 System.exit(exitCode);
08fe2e33
NR
614 }
615
08fe2e33 616 /**
68e2c6d2 617 * Import the given resource into the {@link LocalLibrary}.
08fe2e33 618 *
d0114000 619 * @param urlString
08fe2e33 620 * the resource to import
92fb0719
NR
621 * @param pg
622 * the optional progress reporter
08fe2e33
NR
623 *
624 * @return the exit return code (0 = success)
625 */
92fb0719 626 public static int imprt(String urlString, Progress pg) {
08fe2e33 627 try {
d66deb8d
NR
628 MetaData meta = Instance.getInstance().getLibrary().imprt(BasicReader.getUrl(urlString), pg);
629 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
08fe2e33 630 } catch (IOException e) {
d66deb8d 631 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
632 return 1;
633 }
634
635 return 0;
636 }
637
638 /**
68e2c6d2
NR
639 * Export the {@link Story} from the {@link LocalLibrary} to the given
640 * target.
08fe2e33 641 *
73ce17ef 642 * @param luid
08fe2e33
NR
643 * the story LUID
644 * @param typeString
645 * the {@link OutputType} to use
646 * @param target
647 * the target
92fb0719
NR
648 * @param pg
649 * the optional progress reporter
08fe2e33
NR
650 *
651 * @return the exit return code (0 = success)
652 */
92fb0719
NR
653 public static int export(String luid, String typeString, String target,
654 Progress pg) {
e604986c 655 OutputType type = OutputType.valueOfNullOkUC(typeString, null);
08fe2e33 656 if (type == null) {
d66deb8d 657 Instance.getInstance().getTraceHandler().error(new Exception(trans(StringId.OUTPUT_DESC, typeString)));
08fe2e33
NR
658 return 1;
659 }
660
661 try {
d66deb8d 662 Instance.getInstance().getLibrary().export(luid, type, target, pg);
08fe2e33 663 } catch (IOException e) {
d66deb8d 664 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
665 return 4;
666 }
667
668 return 0;
669 }
670
671 /**
68e2c6d2
NR
672 * List the stories of the given source from the {@link LocalLibrary}
673 * (unless NULL is passed, in which case all stories will be listed).
08fe2e33 674 *
b0e88ebd
NR
675 * @param source
676 * the source to list the known stories of, or NULL to list all
333f0e7b 677 * stories
08fe2e33
NR
678 *
679 * @return the exit return code (0 = success)
680 */
b0e88ebd 681 private static int list(String source) {
0bb51c9c 682 try {
9b75402f 683 new CliReader().listBooks(source);
0bb51c9c 684 } catch (IOException e) {
d66deb8d 685 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c 686 return 66;
f569d249 687 }
0bb51c9c 688
08fe2e33
NR
689 return 0;
690 }
691
692 /**
350bc060 693 * Start the current reader for this {@link Story}.
08fe2e33
NR
694 *
695 * @param story
9b75402f 696 * the story to read
d0114000 697 * @param chapString
08fe2e33
NR
698 * which {@link Chapter} to read (starting at 1), or NULL to get
699 * the {@link Story} description
08fe2e33
NR
700 *
701 * @return the exit return code (0 = success)
702 */
9b75402f
NR
703 private static int read(Story story, String chapString) {
704 Integer chap = null;
705 if (chapString != null) {
706 try {
707 chap = Integer.parseInt(chapString);
708 } catch (NumberFormatException e) {
709 Instance.getInstance().getTraceHandler().error(new IOException(
710 "Chapter number cannot be parsed: " + chapString, e));
711 return 2;
08fe2e33 712 }
9b75402f 713 }
08fe2e33 714
9b75402f
NR
715 if (story != null) {
716 try {
717 if (chap == null) {
718 new CliReader().listChapters(story);
719 } else {
720 new CliReader().printChapter(story, chap);
d0114000 721 }
9b75402f
NR
722 } catch (IOException e) {
723 Instance.getInstance().getTraceHandler()
724 .error(new IOException("Failed to read book", e));
725 return 2;
08fe2e33 726 }
9b75402f
NR
727 } else {
728 Instance.getInstance().getTraceHandler()
729 .error("Cannot find book: " + chapString);
730 return 2;
08fe2e33
NR
731 }
732
733 return 0;
734 }
735
736 /**
737 * Convert the {@link Story} into another format.
738 *
d0114000 739 * @param urlString
08fe2e33
NR
740 * the source {@link Story} to convert
741 * @param typeString
742 * the {@link OutputType} to convert to
d0114000 743 * @param target
08fe2e33
NR
744 * the target file
745 * @param infoCover
746 * TRUE to also export the cover and info file, even if the given
747 * {@link OutputType} does not usually save them
92fb0719
NR
748 * @param pg
749 * the optional progress reporter
08fe2e33
NR
750 *
751 * @return the exit return code (0 = success)
752 */
f7460e4c 753 public static int convert(String urlString, String typeString,
92fb0719 754 String target, boolean infoCover, Progress pg) {
08fe2e33
NR
755 int exitCode = 0;
756
d66deb8d 757 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
d0114000 758 String sourceName = urlString;
08fe2e33 759 try {
3b2b638f 760 URL source = BasicReader.getUrl(urlString);
08fe2e33 761 sourceName = source.toString();
3ddb5591 762 if (sourceName.startsWith("file://")) {
08fe2e33
NR
763 sourceName = sourceName.substring("file://".length());
764 }
765
e604986c 766 OutputType type = OutputType.valueOfAllOkUC(typeString, null);
08fe2e33 767 if (type == null) {
d66deb8d
NR
768 Instance.getInstance().getTraceHandler()
769 .error(new IOException(trans(StringId.ERR_BAD_OUTPUT_TYPE, typeString)));
08fe2e33
NR
770
771 exitCode = 2;
772 } else {
773 try {
774 BasicSupport support = BasicSupport.getSupport(source);
333f0e7b 775
08fe2e33 776 if (support != null) {
d66deb8d 777 Instance.getInstance().getTraceHandler().trace("Support found: " + support.getClass());
bee7dffe
NR
778 Progress pgIn = new Progress();
779 Progress pgOut = new Progress();
780 if (pg != null) {
781 pg.setMax(2);
782 pg.addProgress(pgIn, 1);
783 pg.addProgress(pgOut, 1);
784 }
08fe2e33 785
0ffa4754 786 Story story = support.process(pgIn);
08fe2e33 787 try {
d0114000 788 target = new File(target).getAbsolutePath();
d66deb8d 789 BasicOutput.getOutput(type, infoCover, infoCover).process(story, target, pgOut);
08fe2e33 790 } catch (IOException e) {
d66deb8d
NR
791 Instance.getInstance().getTraceHandler()
792 .error(new IOException(trans(StringId.ERR_SAVING, target), e));
08fe2e33
NR
793 exitCode = 5;
794 }
795 } else {
d66deb8d
NR
796 Instance.getInstance().getTraceHandler()
797 .error(new IOException(trans( StringId.ERR_NOT_SUPPORTED, source)));
08fe2e33
NR
798
799 exitCode = 4;
800 }
801 } catch (IOException e) {
d66deb8d
NR
802 Instance.getInstance().getTraceHandler()
803 .error(new IOException(trans(StringId.ERR_LOADING, sourceName), e));
08fe2e33
NR
804 exitCode = 3;
805 }
806 }
807 } catch (MalformedURLException e) {
d66deb8d 808 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
08fe2e33
NR
809 exitCode = 1;
810 }
811
812 return exitCode;
813 }
814
815 /**
816 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
817 *
818 * @param id
819 * the ID to translate
820 *
821 * @return the translated result
822 */
823 private static String trans(StringId id, Object... params) {
d66deb8d 824 return Instance.getInstance().getTrans().getString(id, params);
08fe2e33
NR
825 }
826
827 /**
d0114000
NR
828 * Display the correct syntax of the program to the user to stdout, or an
829 * error message if the syntax used was wrong on stderr.
830 *
831 * @param showHelp
832 * TRUE to show the syntax help, FALSE to show "syntax error"
08fe2e33 833 */
d0114000
NR
834 private static void syntax(boolean showHelp) {
835 if (showHelp) {
836 StringBuilder builder = new StringBuilder();
837 for (SupportType type : SupportType.values()) {
838 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
839 type.getDesc()));
840 builder.append('\n');
841 }
08fe2e33 842
d0114000
NR
843 String typesIn = builder.toString();
844 builder.setLength(0);
08fe2e33 845
d0114000
NR
846 for (OutputType type : OutputType.values()) {
847 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
4d205683 848 type.getDesc(true)));
d0114000
NR
849 builder.append('\n');
850 }
08fe2e33 851
d0114000 852 String typesOut = builder.toString();
08fe2e33 853
d0114000
NR
854 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
855 } else {
856 System.err.println(trans(StringId.ERR_SYNTAX));
857 }
858 }
08fe2e33 859}