merge from master
[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;
6d465e88 22import be.nikiroo.fanfix.library.WebLibrary;
f433d153 23import be.nikiroo.fanfix.library.WebLibraryServer;
08fe2e33
NR
24import be.nikiroo.fanfix.output.BasicOutput;
25import be.nikiroo.fanfix.output.BasicOutput.OutputType;
3727aae2 26import be.nikiroo.fanfix.reader.BasicReader;
9b75402f 27import be.nikiroo.fanfix.reader.CliReader;
91b82a5c 28import be.nikiroo.fanfix.searchable.BasicSearchable;
08fe2e33 29import be.nikiroo.fanfix.supported.BasicSupport;
0ffa4754 30import be.nikiroo.fanfix.supported.SupportType;
3b2b638f 31import be.nikiroo.utils.Progress;
39c3c689 32import be.nikiroo.utils.Version;
bb0c30ac 33import be.nikiroo.utils.VersionCheck;
08fe2e33
NR
34
35/**
36 * Main program entry point.
37 *
38 * @author niki
39 */
40public class Main {
d0114000 41 private enum MainAction {
9b75402f 42 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
43 }
44
08fe2e33
NR
45 /**
46 * Main program entry point.
47 * <p>
48 * Known environment variables:
49 * <ul>
d0114000 50 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
08fe2e33
NR
51 * {@link String}s when possible</li>
52 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
edd46289
NR
53 * before taking the usual ones; they will also be saved/updated into this
54 * path when the program starts</li>
d0114000
NR
55 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
56 * configuration value with 'true'</li>
57 * </ul>
58 * <p>
59 * <ul>
60 * <li>--import [URL]: import into library</li>
61 * <li>--export [id] [output_type] [target]: export story to target</li>
62 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
63 * target</li>
64 * <li>--read [id] ([chapter number]): read the given story from the library
65 * </li>
333f0e7b 66 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
d0114000 67 * story, without saving it</li>
8b153400
NR
68 * <li>--search: list the supported websites (where)</li>
69 * <li>--search [where] [keywords] (page [page]) (item [item]): search on
70 * the supported website and display the given results page of stories it
71 * found, or the story details if asked</li>
8141d7ac
NR
72 * <li>--search-tag [where]: list all the tags supported by this website</li>
73 * <li>--search-tag [index 1]... (page [page]) (item [item]): search for the
74 * given stories or subtags, tag by tag, and display information about a
75 * specific page of results or about a specific item if requested</li>
333f0e7b 76 * <li>--list ([type]): list the stories present in the library</li>
e10b51a2
NR
77 * <li>--set-source [id] [new source]: change the source of the given story</li>
78 * <li>--set-title [id] [new title]: change the title of the given story</li>
79 * <li>--set-author [id] [new author]: change the author of the given story</li>
39c3c689 80 * <li>--version: get the version of the program</li>
fb25273c
NR
81 * <li>--server: start the server mode (see config file for parameters)</li>
82 * <li>--stop-server: stop the running server on this port if any</li>
f433d153 83 * <li>--remote [key] [host] [port]: use the given remote library</li>
08fe2e33
NR
84 * </ul>
85 *
86 * @param args
d0114000 87 * see method description
08fe2e33
NR
88 */
89 public static void main(String[] args) {
9a553563
NR
90 new Main().start(args);
91 }
92
93 /**
94 * Start the default handling for the application.
95 * <p>
96 * If specific actions were asked (with correct parameters), they will be
97 * forwarded to the different protected methods that you can override.
98 * <p>
99 * At the end of the method, {@link Main#exit(int)} will be called; by
100 * default, it calls {@link System#exit(int)} if the status is not 0.
101 *
102 * @param args
103 * the arguments received from the system
104 */
105 public void start(String [] args) {
ee9b7083
NR
106 // Only one line, but very important:
107 Instance.init();
108
d0114000
NR
109 String urlString = null;
110 String luid = null;
b0e88ebd 111 String sourceString = null;
e10b51a2
NR
112 String titleString = null;
113 String authorString = null;
d0114000
NR
114 String chapString = null;
115 String target = null;
2070ced5 116 String key = null;
333f0e7b 117 MainAction action = MainAction.START;
d0114000 118 Boolean plusInfo = null;
b0e88ebd
NR
119 String host = null;
120 Integer port = null;
91b82a5c
NR
121 SupportType searchOn = null;
122 String search = null;
8b153400 123 List<Integer> tags = new ArrayList<Integer>();
91b82a5c
NR
124 Integer page = null;
125 Integer item = null;
73ce17ef 126
d0114000
NR
127 boolean noMoreActions = false;
128
129 int exitCode = 0;
130 for (int i = 0; exitCode == 0 && i < args.length; i++) {
59f1f1bf
NR
131 if (args[i] == null)
132 continue;
133
d0114000
NR
134 // Action (--) handling:
135 if (!noMoreActions && args[i].startsWith("--")) {
136 if (args[i].equals("--")) {
137 noMoreActions = true;
138 } else {
139 try {
140 action = MainAction.valueOf(args[i].substring(2)
141 .toUpperCase().replace("-", "_"));
142 } catch (Exception e) {
d66deb8d
NR
143 Instance.getInstance().getTraceHandler()
144 .error(new IllegalArgumentException("Unknown action: " + args[i], e));
d0114000
NR
145 exitCode = 255;
146 }
147 }
08fe2e33 148
d0114000
NR
149 continue;
150 }
151
152 switch (action) {
153 case IMPORT:
154 if (urlString == null) {
155 urlString = args[i];
156 } else {
157 exitCode = 255;
158 }
159 break;
160 case EXPORT:
161 if (luid == null) {
162 luid = args[i];
b0e88ebd
NR
163 } else if (sourceString == null) {
164 sourceString = args[i];
d0114000
NR
165 } else if (target == null) {
166 target = args[i];
167 } else {
168 exitCode = 255;
169 }
170 break;
171 case CONVERT:
172 if (urlString == null) {
173 urlString = args[i];
b0e88ebd
NR
174 } else if (sourceString == null) {
175 sourceString = args[i];
d0114000
NR
176 } else if (target == null) {
177 target = args[i];
178 } else if (plusInfo == null) {
179 if ("+info".equals(args[i])) {
180 plusInfo = true;
181 } else {
182 exitCode = 255;
183 }
184 } else {
185 exitCode = 255;
08fe2e33 186 }
d0114000
NR
187 break;
188 case LIST:
b0e88ebd
NR
189 if (sourceString == null) {
190 sourceString = args[i];
d0114000
NR
191 } else {
192 exitCode = 255;
08fe2e33 193 }
d0114000 194 break;
e10b51a2
NR
195 case SET_SOURCE:
196 if (luid == null) {
197 luid = args[i];
198 } else if (sourceString == null) {
199 sourceString = args[i];
200 } else {
201 exitCode = 255;
202 }
203 break;
204 case SET_TITLE:
205 if (luid == null) {
206 luid = args[i];
207 } else if (sourceString == null) {
208 titleString = args[i];
209 } else {
210 exitCode = 255;
211 }
212 break;
213 case SET_AUTHOR:
214 if (luid == null) {
215 luid = args[i];
216 } else if (sourceString == null) {
217 authorString = args[i];
218 } else {
219 exitCode = 255;
220 }
221 break;
d0114000
NR
222 case READ:
223 if (luid == null) {
224 luid = args[i];
225 } else if (chapString == null) {
226 chapString = args[i];
227 } else {
228 exitCode = 255;
08fe2e33 229 }
d0114000
NR
230 break;
231 case READ_URL:
232 if (urlString == null) {
233 urlString = args[i];
234 } else if (chapString == null) {
235 chapString = args[i];
236 } else {
237 exitCode = 255;
08fe2e33 238 }
d0114000 239 break;
91b82a5c
NR
240 case SEARCH:
241 if (searchOn == null) {
242 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 243
91b82a5c 244 if (searchOn == null) {
d66deb8d 245 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
b31a0db0
NR
246 exitCode = 41;
247 break;
91b82a5c 248 }
8b153400 249
91b82a5c 250 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 251 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
b31a0db0
NR
252 exitCode = 42;
253 break;
91b82a5c
NR
254 }
255 } else if (search == null) {
256 search = args[i];
8b153400 257 } else if (page != null && page == -1) {
91b82a5c
NR
258 try {
259 page = Integer.parseInt(args[i]);
8b153400
NR
260 } catch (Exception e) {
261 page = -2;
91b82a5c 262 }
8b153400 263 } else if (item != null && item == -1) {
91b82a5c
NR
264 try {
265 item = Integer.parseInt(args[i]);
8b153400
NR
266 } catch (Exception e) {
267 item = -2;
268 }
269 } else if (page == null || item == null) {
270 if (page == null && "page".equals(args[i])) {
271 page = -1;
272 } else if (item == null && "item".equals(args[i])) {
273 item = -1;
274 } else {
91b82a5c
NR
275 exitCode = 255;
276 }
277 } else {
278 exitCode = 255;
279 }
280 break;
8141d7ac 281 case SEARCH_TAG:
91b82a5c
NR
282 if (searchOn == null) {
283 searchOn = SupportType.valueOfAllOkUC(args[i]);
8b153400 284
91b82a5c 285 if (searchOn == null) {
d66deb8d 286 Instance.getInstance().getTraceHandler().error("Website not known: <" + args[i] + ">");
91b82a5c
NR
287 exitCode = 255;
288 }
8b153400 289
91b82a5c 290 if (BasicSearchable.getSearchable(searchOn) == null) {
d66deb8d 291 Instance.getInstance().getTraceHandler().error("Website not supported: " + searchOn);
91b82a5c
NR
292 exitCode = 255;
293 }
8b153400
NR
294 } else if (page == null && item == null) {
295 if ("page".equals(args[i])) {
296 page = -1;
297 } else if ("item".equals(args[i])) {
298 item = -1;
299 } else {
300 try {
301 int index = Integer.parseInt(args[i]);
302 tags.add(index);
303 } catch (NumberFormatException e) {
d66deb8d 304 Instance.getInstance().getTraceHandler().error("Invalid tag index: " + args[i]);
8b153400
NR
305 exitCode = 255;
306 }
307 }
308 } else if (page != null && page == -1) {
309 try {
310 page = Integer.parseInt(args[i]);
311 } catch (Exception e) {
312 page = -2;
313 }
314 } else if (item != null && item == -1) {
315 try {
316 item = Integer.parseInt(args[i]);
317 } catch (Exception e) {
318 item = -2;
319 }
320 } else if (page == null || item == null) {
321 if (page == null && "page".equals(args[i])) {
322 page = -1;
323 } else if (item == null && "item".equals(args[i])) {
324 item = -1;
325 } else {
326 exitCode = 255;
327 }
91b82a5c 328 } else {
8b153400 329 exitCode = 255;
91b82a5c
NR
330 }
331 break;
d0114000
NR
332 case HELP:
333 exitCode = 255;
334 break;
333f0e7b
NR
335 case START:
336 exitCode = 255; // not supposed to be selected by user
337 break;
39c3c689
NR
338 case VERSION:
339 exitCode = 255; // no arguments for this option
b0e88ebd
NR
340 break;
341 case SERVER:
fb25273c
NR
342 exitCode = 255; // no arguments for this option
343 break;
5e848e6a 344 case STOP_SERVER:
fb25273c 345 exitCode = 255; // no arguments for this option
b0e88ebd
NR
346 break;
347 case REMOTE:
2070ced5
NR
348 if (key == null) {
349 key = args[i];
350 } else if (host == null) {
b0e88ebd
NR
351 host = args[i];
352 } else if (port == null) {
353 port = Integer.parseInt(args[i]);
ff05b828 354
6d465e88
NR
355 BasicLibrary lib;
356 if (host.startsWith("http://")
357 || host.startsWith("https://")) {
358 lib = new WebLibrary(key, host, port);
359 } else {
360 lib = new RemoteLibrary(key, host, port);
361 }
362
9b75402f
NR
363 lib = new CacheLibrary(
364 Instance.getInstance().getRemoteDir(host), lib,
d66deb8d 365 Instance.getInstance().getUiConfig());
ff05b828 366
9b75402f 367 Instance.getInstance().setLibrary(lib);
5e848e6a 368
b0e88ebd
NR
369 action = MainAction.START;
370 } else {
371 exitCode = 255;
372 }
373 break;
d0114000
NR
374 }
375 }
376
92fb0719
NR
377 final Progress mainProgress = new Progress(0, 80);
378 mainProgress.addProgressListener(new Progress.ProgressListener() {
379 private int current = mainProgress.getMin();
380
211f7ddb 381 @Override
92fb0719
NR
382 public void progress(Progress progress, String name) {
383 int diff = progress.getProgress() - current;
384 current += diff;
385
1822d603
NR
386 if (diff <= 0)
387 return;
388
92fb0719
NR
389 StringBuilder builder = new StringBuilder();
390 for (int i = 0; i < diff; i++) {
391 builder.append('.');
392 }
393
394 System.err.print(builder.toString());
395
396 if (progress.isDone()) {
397 System.err.println("");
398 }
399 }
400 });
401 Progress pg = new Progress();
402 mainProgress.addProgress(pg, mainProgress.getMax());
403
9a553563 404 VersionCheck updates = checkUpdates();
b42117f1 405
b31a0db0 406 if (exitCode == 0) {
d0114000
NR
407 switch (action) {
408 case IMPORT:
bb0c30ac
NR
409 if (updates != null) {
410 // we consider it read
411 Instance.getInstance().setVersionChecked();
412 }
9a553563
NR
413
414 try {
415 exitCode = imprt(BasicReader.getUrl(urlString), pg);
416 } catch (MalformedURLException e) {
417 Instance.getInstance().getTraceHandler().error(e);
418 exitCode = 1;
419 }
420
d0114000
NR
421 break;
422 case EXPORT:
bb0c30ac
NR
423 if (updates != null) {
424 // we consider it read
425 Instance.getInstance().setVersionChecked();
426 }
9a553563
NR
427
428 OutputType exportType = OutputType.valueOfNullOkUC(sourceString, null);
429 if (exportType == null) {
430 Instance.getInstance().getTraceHandler().error(new Exception(trans(StringId.OUTPUT_DESC, sourceString)));
431 exitCode = 1;
432 break;
433 }
434
435 exitCode = export(luid, exportType, target, pg);
436
d0114000
NR
437 break;
438 case CONVERT:
bb0c30ac
NR
439 if (updates != null) {
440 // we consider it read
441 Instance.getInstance().setVersionChecked();
442 }
9a553563
NR
443
444 OutputType convertType = OutputType.valueOfAllOkUC(sourceString, null);
445 if (convertType == null) {
446 Instance.getInstance().getTraceHandler()
447 .error(new IOException(trans(StringId.ERR_BAD_OUTPUT_TYPE, sourceString)));
448
449 exitCode = 2;
450 break;
451 }
452
453 exitCode = convert(urlString, convertType, target,
92fb0719 454 plusInfo == null ? false : plusInfo, pg);
9a553563 455
d0114000
NR
456 break;
457 case LIST:
b0e88ebd 458 exitCode = list(sourceString);
d0114000 459 break;
e10b51a2
NR
460 case SET_SOURCE:
461 try {
d66deb8d 462 Instance.getInstance().getLibrary().changeSource(luid, sourceString, pg);
e10b51a2 463 } catch (IOException e1) {
d66deb8d 464 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
465 exitCode = 21;
466 }
467 break;
468 case SET_TITLE:
469 try {
d66deb8d 470 Instance.getInstance().getLibrary().changeTitle(luid, titleString, pg);
e10b51a2 471 } catch (IOException e1) {
d66deb8d 472 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
473 exitCode = 22;
474 }
475 break;
476 case SET_AUTHOR:
477 try {
d66deb8d 478 Instance.getInstance().getLibrary().changeAuthor(luid, authorString, pg);
e10b51a2 479 } catch (IOException e1) {
d66deb8d 480 Instance.getInstance().getTraceHandler().error(e1);
e10b51a2
NR
481 exitCode = 23;
482 }
483 break;
d0114000 484 case READ:
9b75402f
NR
485 if (luid == null || luid.isEmpty()) {
486 syntax(false);
487 exitCode = 255;
99ccbdf6
NR
488 break;
489 }
9b75402f
NR
490
491 try {
9a553563
NR
492 Integer chap = null;
493 if (chapString != null) {
494 try {
495 chap = Integer.parseInt(chapString);
496 } catch (NumberFormatException e) {
497 Instance.getInstance().getTraceHandler().error(new IOException(
498 "Chapter number cannot be parsed: " + chapString, e));
499 exitCode = 2;
500 break;
501 }
502 }
503
9b75402f 504 BasicLibrary lib = Instance.getInstance().getLibrary();
9a553563 505 exitCode = read(lib.getStory(luid, null), chap);
9b75402f
NR
506 } catch (IOException e) {
507 Instance.getInstance().getTraceHandler()
508 .error(new IOException("Failed to read book", e));
509 exitCode = 2;
510 }
511
d0114000
NR
512 break;
513 case READ_URL:
9b75402f
NR
514 if (urlString == null || urlString.isEmpty()) {
515 syntax(false);
516 exitCode = 255;
99ccbdf6
NR
517 break;
518 }
9b75402f
NR
519
520 try {
9a553563
NR
521 Integer chap = null;
522 if (chapString != null) {
523 try {
524 chap = Integer.parseInt(chapString);
525 } catch (NumberFormatException e) {
526 Instance.getInstance().getTraceHandler().error(new IOException(
527 "Chapter number cannot be parsed: " + chapString, e));
528 exitCode = 2;
529 break;
530 }
531 }
532
9b75402f
NR
533 BasicSupport support = BasicSupport
534 .getSupport(BasicReader.getUrl(urlString));
535 if (support == null) {
536 Instance.getInstance().getTraceHandler()
537 .error("URL not supported: " + urlString);
538 exitCode = 2;
539 break;
540 }
541
9a553563 542 exitCode = read(support.process(null), chap);
9b75402f
NR
543 } catch (IOException e) {
544 Instance.getInstance().getTraceHandler()
545 .error(new IOException("Failed to read book", e));
546 exitCode = 2;
547 }
548
91b82a5c
NR
549 break;
550 case SEARCH:
8b153400
NR
551 page = page == null ? 1 : page;
552 if (page < 0) {
d66deb8d 553 Instance.getInstance().getTraceHandler().error("Incorrect page number");
91b82a5c
NR
554 exitCode = 255;
555 break;
556 }
8b153400
NR
557
558 item = item == null ? 0 : item;
559 if (item < 0) {
d66deb8d 560 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
561 exitCode = 255;
562 break;
91b82a5c 563 }
8b153400 564
9a553563
NR
565 if (searchOn == null) {
566 try {
567 search();
568 } catch (IOException e) {
569 Instance.getInstance().getTraceHandler().error(e);
570 exitCode = 1;
8b153400 571 }
9a553563
NR
572 } else if (search != null) {
573 try {
574 searchKeywords(searchOn, search, page, item);
575 } catch (IOException e) {
576 Instance.getInstance().getTraceHandler().error(e);
577 exitCode = 20;
578 }
579 } else {
580 exitCode = 255;
91b82a5c 581 }
8b153400 582
91b82a5c 583 break;
8141d7ac 584 case SEARCH_TAG:
91b82a5c
NR
585 if (searchOn == null) {
586 exitCode = 255;
587 break;
588 }
91b82a5c 589
8b153400
NR
590 page = page == null ? 1 : page;
591 if (page < 0) {
d66deb8d 592 Instance.getInstance().getTraceHandler().error("Incorrect page number");
8b153400
NR
593 exitCode = 255;
594 break;
91b82a5c 595 }
8b153400
NR
596
597 item = item == null ? 0 : item;
598 if (item < 0) {
d66deb8d 599 Instance.getInstance().getTraceHandler().error("Incorrect item number");
8b153400
NR
600 exitCode = 255;
601 break;
602 }
603
91b82a5c 604 try {
9a553563
NR
605 searchTags(searchOn, page, item,
606 tags.toArray(new Integer[] {}));
607 } catch (IOException e) {
608 Instance.getInstance().getTraceHandler().error(e);
91b82a5c 609 }
8b153400 610
d0114000
NR
611 break;
612 case HELP:
613 syntax(true);
614 exitCode = 0;
615 break;
39c3c689 616 case VERSION:
bb0c30ac
NR
617 if (updates != null) {
618 // we consider it read
619 Instance.getInstance().setVersionChecked();
620 }
9a553563 621
39c3c689
NR
622 System.out
623 .println(String.format("Fanfix version %s"
9fe3f177
NR
624 + "%nhttps://github.com/nikiroo/fanfix/"
625 + "%n\tWritten by Nikiroo",
39c3c689
NR
626 Version.getCurrentVersion()));
627 break;
333f0e7b 628 case START:
0bb51c9c 629 try {
9a553563 630 start();
0bb51c9c 631 } catch (IOException e) {
d66deb8d 632 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
633 exitCode = 66;
634 }
b0e88ebd
NR
635 break;
636 case SERVER:
b0e88ebd 637 try {
f433d153 638 startServer();
b0e88ebd 639 } catch (IOException e) {
d66deb8d 640 Instance.getInstance().getTraceHandler().error(e);
b0e88ebd 641 }
9a553563
NR
642
643 break;
5e848e6a 644 case STOP_SERVER:
aad0e5ae
NR
645 // Can be given via "--remote XX XX XX"
646 if (key == null)
d66deb8d 647 key = Instance.getInstance().getConfig().getString(Config.SERVER_KEY);
aad0e5ae 648 if (port == null)
d66deb8d 649 port = Instance.getInstance().getConfig().getInteger(Config.SERVER_PORT);
aad0e5ae 650
5e848e6a 651 if (port == null) {
aad0e5ae 652 System.err.println("No port given nor configured in the config file");
fb25273c 653 exitCode = 15;
5e848e6a
NR
654 break;
655 }
0bb51c9c 656 try {
9a553563 657 stopServer(key, host, port);
0bb51c9c 658 } catch (SSLException e) {
d66deb8d 659 Instance.getInstance().getTraceHandler().error(
0bb51c9c
NR
660 "Bad access key for remote library");
661 exitCode = 43;
662 } catch (IOException e) {
d66deb8d 663 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c
NR
664 exitCode = 44;
665 }
5e848e6a 666
5e848e6a 667 break;
b0e88ebd 668 case REMOTE:
99ccbdf6 669 exitCode = 255; // should not be reachable (REMOTE -> START)
333f0e7b 670 break;
08fe2e33
NR
671 }
672 }
673
350bc060 674 try {
d66deb8d 675 Instance.getInstance().getTempFiles().close();
350bc060 676 } catch (IOException e) {
9a553563
NR
677 Instance.getInstance().getTraceHandler().error(new IOException(
678 "Cannot dispose of the temporary files", e));
2aac79c7
NR
679 }
680
08fe2e33 681 if (exitCode == 255) {
d0114000 682 syntax(false);
08fe2e33
NR
683 }
684
9a553563
NR
685 exit(exitCode);
686 }
687
688 /**
689 * A normal invocation of the program (without parameters or at least
690 * without "action" parameters).
691 * <p>
692 * You will probably want to override that one if you offer a user
693 * interface.
694 *
695 * @throws IOException
696 * in case of I/O error
697 */
698 protected void start() throws IOException {
699 new CliReader().listBooks(null);
700 }
701
702 /**
98b95fb8 703 * Will check if updates are available, synchronously.
9a553563
NR
704 * <p>
705 * For this, it will simply forward the call to
706 * {@link Main#checkUpdates(String)} with a value of "nikiroo/fanfix".
98b95fb8
NR
707 * <p>
708 * You may want to override it so you call the forward method with the right
709 * parameters (or also if you want it to be asynchronous).
9a553563
NR
710 *
711 * @return the newer version information or NULL if nothing new
712 */
713 protected VersionCheck checkUpdates() {
714 return checkUpdates("nikiroo/fanfix");
715 }
716
717 /**
718 * Will check if updates are available on a specific GitHub project.
719 * <p>
720 * Will be called by {@link Main#checkUpdates()}, but if you override that
721 * one you mall call it with another project.
722 *
723 * @param githubProject
724 * the GitHub project, for instance "nikiroo/fanfix"
725 *
726 * @return the newer version information or NULL if nothing new
727 */
728 protected VersionCheck checkUpdates(String githubProject) {
bb0c30ac
NR
729 try {
730 VersionCheck updates = VersionCheck.check(githubProject,
731 Instance.getInstance().getTrans().getLocale());
732 if (updates.isNewVersionAvailable()) {
733 notifyUpdates(updates);
734 return updates;
735 }
736 } catch (IOException e) {
737 // Maybe no internet. Do not report any update.
9a553563 738 }
bb0c30ac 739
9a553563 740 return null;
08fe2e33
NR
741 }
742
9a553563
NR
743 /**
744 * Notify the user about available updates.
745 * <p>
746 * Will only be called when a version is available.
747 * <p>
bb0c30ac
NR
748 * Note that you can call {@link Instance#setVersionChecked()} on it if the
749 * user has read the information (by default, it is marked read only on
750 * certain other actions).
9a553563
NR
751 *
752 * @param updates
753 * the new version information
754 */
755 protected void notifyUpdates(VersionCheck updates) {
756 // Sent to syserr so not to cause problem if one tries to capture a
757 // story content in text mode
758 System.err.println(
759 "A new version of the program is available at https://github.com/nikiroo/fanfix/releases");
760 System.err.println("");
761 for (Version v : updates.getNewer()) {
762 System.err.println("\tVersion " + v);
763 System.err.println("\t-------------");
764 System.err.println("");
765 for (String it : updates.getChanges().get(v)) {
766 System.err.println("\t- " + it);
767 }
768 System.err.println("");
769 }
770 }
771
08fe2e33 772 /**
68e2c6d2 773 * Import the given resource into the {@link LocalLibrary}.
08fe2e33 774 *
9a553563 775 * @param url
08fe2e33 776 * the resource to import
92fb0719
NR
777 * @param pg
778 * the optional progress reporter
08fe2e33
NR
779 *
780 * @return the exit return code (0 = success)
781 */
9a553563 782 protected static int imprt(URL url, Progress pg) {
08fe2e33 783 try {
9a553563 784 MetaData meta = Instance.getInstance().getLibrary().imprt(url, pg);
d66deb8d 785 System.out.println(meta.getLuid() + ": \"" + meta.getTitle() + "\" imported.");
08fe2e33 786 } catch (IOException e) {
d66deb8d 787 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
788 return 1;
789 }
790
791 return 0;
792 }
793
794 /**
68e2c6d2
NR
795 * Export the {@link Story} from the {@link LocalLibrary} to the given
796 * target.
08fe2e33 797 *
73ce17ef 798 * @param luid
08fe2e33 799 * the story LUID
9a553563 800 * @param type
08fe2e33
NR
801 * the {@link OutputType} to use
802 * @param target
803 * the target
92fb0719
NR
804 * @param pg
805 * the optional progress reporter
08fe2e33
NR
806 *
807 * @return the exit return code (0 = success)
808 */
9a553563 809 protected static int export(String luid, OutputType type, String target,
92fb0719 810 Progress pg) {
08fe2e33 811 try {
d66deb8d 812 Instance.getInstance().getLibrary().export(luid, type, target, pg);
08fe2e33 813 } catch (IOException e) {
d66deb8d 814 Instance.getInstance().getTraceHandler().error(e);
08fe2e33
NR
815 return 4;
816 }
817
818 return 0;
819 }
9a553563 820
08fe2e33 821 /**
68e2c6d2
NR
822 * List the stories of the given source from the {@link LocalLibrary}
823 * (unless NULL is passed, in which case all stories will be listed).
08fe2e33 824 *
b0e88ebd
NR
825 * @param source
826 * the source to list the known stories of, or NULL to list all
333f0e7b 827 * stories
08fe2e33
NR
828 *
829 * @return the exit return code (0 = success)
830 */
9a553563 831 protected int list(String source) {
0bb51c9c 832 try {
9b75402f 833 new CliReader().listBooks(source);
0bb51c9c 834 } catch (IOException e) {
d66deb8d 835 Instance.getInstance().getTraceHandler().error(e);
0bb51c9c 836 return 66;
f569d249 837 }
0bb51c9c 838
08fe2e33
NR
839 return 0;
840 }
841
842 /**
350bc060 843 * Start the current reader for this {@link Story}.
08fe2e33
NR
844 *
845 * @param story
9b75402f 846 * the story to read
9a553563 847 * @param chap
08fe2e33
NR
848 * which {@link Chapter} to read (starting at 1), or NULL to get
849 * the {@link Story} description
08fe2e33
NR
850 *
851 * @return the exit return code (0 = success)
852 */
9a553563 853 protected int read(Story story, Integer chap) {
9b75402f
NR
854 if (story != null) {
855 try {
856 if (chap == null) {
857 new CliReader().listChapters(story);
858 } else {
859 new CliReader().printChapter(story, chap);
d0114000 860 }
9b75402f
NR
861 } catch (IOException e) {
862 Instance.getInstance().getTraceHandler()
863 .error(new IOException("Failed to read book", e));
864 return 2;
08fe2e33 865 }
9b75402f
NR
866 } else {
867 Instance.getInstance().getTraceHandler()
9a553563 868 .error("Cannot find book: " + story);
9b75402f 869 return 2;
08fe2e33
NR
870 }
871
872 return 0;
873 }
874
875 /**
876 * Convert the {@link Story} into another format.
877 *
d0114000 878 * @param urlString
08fe2e33 879 * the source {@link Story} to convert
9a553563 880 * @param type
08fe2e33 881 * the {@link OutputType} to convert to
d0114000 882 * @param target
08fe2e33
NR
883 * the target file
884 * @param infoCover
885 * TRUE to also export the cover and info file, even if the given
886 * {@link OutputType} does not usually save them
92fb0719
NR
887 * @param pg
888 * the optional progress reporter
08fe2e33
NR
889 *
890 * @return the exit return code (0 = success)
891 */
9a553563 892 protected int convert(String urlString, OutputType type,
92fb0719 893 String target, boolean infoCover, Progress pg) {
08fe2e33
NR
894 int exitCode = 0;
895
d66deb8d 896 Instance.getInstance().getTraceHandler().trace("Convert: " + urlString);
d0114000 897 String sourceName = urlString;
08fe2e33 898 try {
3b2b638f 899 URL source = BasicReader.getUrl(urlString);
08fe2e33 900 sourceName = source.toString();
3ddb5591 901 if (sourceName.startsWith("file://")) {
08fe2e33
NR
902 sourceName = sourceName.substring("file://".length());
903 }
904
9a553563
NR
905 try {
906 BasicSupport support = BasicSupport.getSupport(source);
08fe2e33 907
9a553563
NR
908 if (support != null) {
909 Instance.getInstance().getTraceHandler()
910 .trace("Support found: " + support.getClass());
911 Progress pgIn = new Progress();
912 Progress pgOut = new Progress();
913 if (pg != null) {
914 pg.setMax(2);
915 pg.addProgress(pgIn, 1);
916 pg.addProgress(pgOut, 1);
917 }
08fe2e33 918
9a553563
NR
919 Story story = support.process(pgIn);
920 try {
921 target = new File(target).getAbsolutePath();
922 BasicOutput.getOutput(type, infoCover, infoCover)
923 .process(story, target, pgOut);
924 } catch (IOException e) {
d66deb8d 925 Instance.getInstance().getTraceHandler()
9a553563
NR
926 .error(new IOException(
927 trans(StringId.ERR_SAVING, target), e));
928 exitCode = 5;
08fe2e33 929 }
9a553563 930 } else {
d66deb8d 931 Instance.getInstance().getTraceHandler()
9a553563
NR
932 .error(new IOException(
933 trans(StringId.ERR_NOT_SUPPORTED, source)));
934
935 exitCode = 4;
08fe2e33 936 }
9a553563
NR
937 } catch (IOException e) {
938 Instance.getInstance().getTraceHandler().error(new IOException(
939 trans(StringId.ERR_LOADING, sourceName), e));
940 exitCode = 3;
08fe2e33
NR
941 }
942 } catch (MalformedURLException e) {
d66deb8d 943 Instance.getInstance().getTraceHandler().error(new IOException(trans(StringId.ERR_BAD_URL, sourceName), e));
08fe2e33
NR
944 exitCode = 1;
945 }
946
947 return exitCode;
948 }
949
08fe2e33 950 /**
d0114000
NR
951 * Display the correct syntax of the program to the user to stdout, or an
952 * error message if the syntax used was wrong on stderr.
953 *
954 * @param showHelp
955 * TRUE to show the syntax help, FALSE to show "syntax error"
08fe2e33 956 */
9a553563 957 protected void syntax(boolean showHelp) {
d0114000
NR
958 if (showHelp) {
959 StringBuilder builder = new StringBuilder();
960 for (SupportType type : SupportType.values()) {
961 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
962 type.getDesc()));
963 builder.append('\n');
964 }
08fe2e33 965
d0114000
NR
966 String typesIn = builder.toString();
967 builder.setLength(0);
08fe2e33 968
d0114000
NR
969 for (OutputType type : OutputType.values()) {
970 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
4d205683 971 type.getDesc(true)));
d0114000
NR
972 builder.append('\n');
973 }
08fe2e33 974
d0114000 975 String typesOut = builder.toString();
08fe2e33 976
d0114000
NR
977 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
978 } else {
979 System.err.println(trans(StringId.ERR_SYNTAX));
980 }
981 }
9a553563
NR
982
983 /**
984 * Starts a search operation (i.e., list the available web sites we can
985 * search on).
986 *
987 * @throws IOException
988 * in case of I/O errors
989 */
990 protected void search() throws IOException {
991 new CliReader().listSearchables();
992 }
993
994 /**
995 * Search for books by keywords on the given supported web site.
996 *
997 * @param searchOn
998 * the web site to search on
999 * @param search
1000 * the keyword to look for
1001 * @param page
1002 * the page of results to get, or 0 to inquire about the number
1003 * of pages
1004 * @param item
1005 * the index of the book we are interested by, or 0 to query
1006 * about how many books are in that page of results
1007 *
1008 * @throws IOException
1009 * in case of I/O error
1010 */
1011 protected void searchKeywords(SupportType searchOn, String search,
1012 int page, Integer item) throws IOException {
1013 new CliReader().searchBooksByKeyword(searchOn, search, page, item);
1014 }
1015
1016 /**
1017 * Search for books by tags on the given supported web site.
1018 *
1019 * @param searchOn
1020 * the web site to search on
1021 * @param page
1022 * the page of results to get, or 0 to inquire about the number
1023 * of pages
1024 * @param item
1025 * the index of the book we are interested by, or 0 to query
1026 * about how many books are in that page of results
1027 * @param tags
1028 * the tags to look for
1029 *
1030 * @throws IOException
1031 * in case of I/O error
1032 */
1033 protected void searchTags(SupportType searchOn, Integer page, Integer item,
1034 Integer[] tags) throws IOException {
1035 new CliReader().searchBooksByTag(searchOn, page, item, tags);
1036 }
1037
1038 /**
1039 * Start a Fanfix server.
1040 *
9a553563
NR
1041 * @throws IOException
1042 * in case of I/O errors
1043 * @throws SSLException
1044 * when the key was not accepted
1045 */
f433d153
NR
1046 private void startServer() throws IOException {
1047 String mode = Instance.getInstance().getConfig()
1048 .getString(Config.SERVER_MODE, "fanfix");
1049 if (mode.equals("fanfix")) {
1050 RemoteLibraryServer server = new RemoteLibraryServer();
1051 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1052 server.run();
1053 } else if (mode.equals("http")) {
1054 WebLibraryServer server = new WebLibraryServer(false);
1055 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1056 server.run();
1057 } else if (mode.equals("https")) {
1058 WebLibraryServer server = new WebLibraryServer(true);
1059 server.setTraceHandler(Instance.getInstance().getTraceHandler());
1060 server.run();
1061 } else {
1062 throw new IOException("Unknown server mode: " + mode);
1063 }
9a553563
NR
1064 }
1065
1066 /**
1067 * Stop a running Fanfix server.
1068 *
1069 * @param key
1070 * the key to contact the Fanfix server
1071 * @param host
1072 * the host on which it runs (NULL means localhost)
1073 * @param port
1074 * the port on which it runs
1075 *
1076 * @throws IOException
1077 * in case of I/O errors
1078 * @throws SSLException
1079 * when the key was not accepted
1080 */
6d465e88 1081 private void stopServer(String key, String host, Integer port)
9a553563 1082 throws IOException, SSLException {
6d465e88
NR
1083 if (host.startsWith("http://") || host.startsWith("https://")) {
1084 new WebLibrary(key, host, port).stop();
1085 } else {
1086 new RemoteLibrary(key, host, port).stop();
1087 }
9a553563
NR
1088 }
1089
1090 /**
1091 * We are done and ready to exit.
1092 * <p>
1093 * By default, it will call {@link System#exit(int)} if the status is not 0.
1094 *
1095 * @param status
1096 * the exit status
1097 */
1098 protected void exit(int status) {
1099 if (status != 0) {
1100 System.exit(status);
1101 }
1102 }
1103
1104 /**
1105 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
1106 *
1107 * @param id
1108 * the ID to translate
1109 *
1110 * @return the translated result
1111 */
1112 static private String trans(StringId id, Object... params) {
1113 return Instance.getInstance().getTrans().getString(id, params);
1114 }
08fe2e33 1115}