Version 1.0.0
[fanfix.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.output.BasicOutput;
12 import be.nikiroo.fanfix.output.BasicOutput.OutputType;
13 import be.nikiroo.fanfix.reader.BasicReader;
14 import be.nikiroo.fanfix.reader.BasicReader.ReaderType;
15 import be.nikiroo.fanfix.supported.BasicSupport;
16 import be.nikiroo.fanfix.supported.BasicSupport.SupportType;
17 import be.nikiroo.utils.UIUtils;
18
19 /**
20 * Main program entry point.
21 *
22 * @author niki
23 */
24 public class Main {
25 private enum MainAction {
26 IMPORT, EXPORT, CONVERT, READ, READ_URL, LIST, HELP, SET_READER, START,
27 }
28
29 /**
30 * Main program entry point.
31 * <p>
32 * Known environment variables:
33 * <ul>
34 * <li>NOUTF: if set to 1 or 'true', the program will prefer non-unicode
35 * {@link String}s when possible</li>
36 * <li>CONFIG_DIR: a path where to look for the <tt>.properties</tt> files
37 * before taking the included ones; they will also be saved/updated into
38 * this path when the program starts</li>
39 * <li>DEBUG: if set to 1 or 'true', the program will override the DEBUG_ERR
40 * configuration value with 'true'</li>
41 * </ul>
42 * <p>
43 * <ul>
44 * <li>--import [URL]: import into library</li>
45 * <li>--export [id] [output_type] [target]: export story to target</li>
46 * <li>--convert [URL] [output_type] [target] (+info): convert URL into
47 * target</li>
48 * <li>--read [id] ([chapter number]): read the given story from the library
49 * </li>
50 * <li>--read-url [URL] ([chapter number]): convert on the fly and read the
51 * story, without saving it</li>
52 * <li>--list ([type]): list the stories present in the library</li>
53 * <li>--set-reader [reader type]: set the reader type to CLI or LOCAL for
54 * this command</li>
55 * </ul>
56 *
57 * @param args
58 * see method description
59 */
60 public static void main(String[] args) {
61 String urlString = null;
62 String luid = null;
63 String typeString = null;
64 String chapString = null;
65 String target = null;
66 MainAction action = MainAction.START;
67 Boolean plusInfo = null;
68
69 boolean noMoreActions = false;
70
71 int exitCode = 0;
72 for (int i = 0; exitCode == 0 && i < args.length; i++) {
73 // Action (--) handling:
74 if (!noMoreActions && args[i].startsWith("--")) {
75 if (args[i].equals("--")) {
76 noMoreActions = true;
77 } else {
78 try {
79 action = MainAction.valueOf(args[i].substring(2)
80 .toUpperCase().replace("-", "_"));
81 } catch (Exception e) {
82 Instance.syserr(new IllegalArgumentException(
83 "Unknown action: " + args[i], e));
84 exitCode = 255;
85 }
86 }
87
88 continue;
89 }
90
91 switch (action) {
92 case IMPORT:
93 if (urlString == null) {
94 urlString = args[i];
95 } else {
96 exitCode = 255;
97 }
98 break;
99 case EXPORT:
100 if (luid == null) {
101 luid = args[i];
102 } else if (typeString == null) {
103 typeString = args[i];
104 } else if (target == null) {
105 target = args[i];
106 } else {
107 exitCode = 255;
108 }
109 break;
110 case CONVERT:
111 if (urlString == null) {
112 urlString = args[i];
113 } else if (typeString == null) {
114 typeString = args[i];
115 } else if (target == null) {
116 target = args[i];
117 } else if (plusInfo == null) {
118 if ("+info".equals(args[i])) {
119 plusInfo = true;
120 } else {
121 exitCode = 255;
122 }
123 } else {
124 exitCode = 255;
125 }
126 break;
127 case LIST:
128 if (typeString == null) {
129 typeString = args[i];
130 } else {
131 exitCode = 255;
132 }
133 break;
134 case READ:
135 if (luid == null) {
136 luid = args[i];
137 } else if (chapString == null) {
138 chapString = args[i];
139 } else {
140 exitCode = 255;
141 }
142 break;
143 case READ_URL:
144 if (urlString == null) {
145 urlString = args[i];
146 } else if (chapString == null) {
147 chapString = args[i];
148 } else {
149 exitCode = 255;
150 }
151 break;
152 case HELP:
153 exitCode = 255;
154 break;
155 case SET_READER:
156 exitCode = setReaderType(args[i]);
157 break;
158 case START:
159 exitCode = 255; // not supposed to be selected by user
160 break;
161 }
162 }
163
164 if (exitCode != 255) {
165 switch (action) {
166 case IMPORT:
167 exitCode = imprt(urlString);
168 break;
169 case EXPORT:
170 exitCode = export(luid, typeString, target);
171 break;
172 case CONVERT:
173 exitCode = convert(urlString, typeString, target,
174 plusInfo == null ? false : plusInfo);
175 break;
176 case LIST:
177 exitCode = list(typeString);
178 break;
179 case READ:
180 exitCode = read(luid, chapString, true);
181 break;
182 case READ_URL:
183 exitCode = read(urlString, chapString, false);
184 break;
185 case HELP:
186 syntax(true);
187 exitCode = 0;
188 break;
189 case SET_READER:
190 break;
191 case START:
192 UIUtils.setLookAndFeel();
193 BasicReader.setDefaultReaderType(ReaderType.LOCAL);
194 BasicReader.getReader().start(null);
195 break;
196 }
197 }
198
199 if (exitCode == 255) {
200 syntax(false);
201 }
202
203 if (exitCode != 0) {
204 System.exit(exitCode);
205 }
206 }
207
208 /**
209 * Return an {@link URL} from this {@link String}, be it a file path or an
210 * actual {@link URL}.
211 *
212 * @param sourceString
213 * the source
214 *
215 * @return the corresponding {@link URL}
216 *
217 * @throws MalformedURLException
218 * if this is neither a file nor a conventional {@link URL}
219 */
220 private static URL getUrl(String sourceString) throws MalformedURLException {
221 if (sourceString == null || sourceString.isEmpty()) {
222 throw new MalformedURLException("Empty url");
223 }
224
225 URL source = null;
226 try {
227 source = new URL(sourceString);
228 } catch (MalformedURLException e) {
229 File sourceFile = new File(sourceString);
230 source = sourceFile.toURI().toURL();
231 }
232
233 return source;
234 }
235
236 /**
237 * Import the given resource into the {@link Library}.
238 *
239 * @param urlString
240 * the resource to import
241 *
242 * @return the exit return code (0 = success)
243 */
244 public static int imprt(String urlString) {
245 try {
246 Story story = Instance.getLibrary().imprt(getUrl(urlString));
247 System.out.println(story.getMeta().getLuid() + ": \""
248 + story.getMeta().getTitle() + "\" imported.");
249 } catch (IOException e) {
250 Instance.syserr(e);
251 return 1;
252 }
253
254 return 0;
255 }
256
257 /**
258 * Export the {@link Story} from the {@link Library} to the given target.
259 *
260 * @param luid
261 * the story LUID
262 * @param typeString
263 * the {@link OutputType} to use
264 * @param target
265 * the target
266 *
267 * @return the exit return code (0 = success)
268 */
269 public static int export(String luid, String typeString, String target) {
270 OutputType type = OutputType.valueOfNullOkUC(typeString);
271 if (type == null) {
272 Instance.syserr(new Exception(trans(StringId.OUTPUT_DESC,
273 typeString)));
274 return 1;
275 }
276
277 try {
278 Instance.getLibrary().export(luid, type, target);
279 } catch (IOException e) {
280 Instance.syserr(e);
281 return 4;
282 }
283
284 return 0;
285 }
286
287 /**
288 * List the stories of the given type from the {@link Library} (unless NULL
289 * is passed, in which case all stories will be listed).
290 *
291 * @param typeString
292 * the type to list the known stories of, or NULL to list all
293 * stories
294 *
295 * @return the exit return code (0 = success)
296 */
297 private static int list(String type) {
298 BasicReader.getReader().start(type);
299 return 0;
300 }
301
302 /**
303 * Start the CLI reader for this {@link Story}.
304 *
305 * @param story
306 * the LUID of the {@link Story} in the {@link Library} <b>or</b>
307 * the {@link Story} {@link URL}
308 * @param chapString
309 * which {@link Chapter} to read (starting at 1), or NULL to get
310 * the {@link Story} description
311 * @param library
312 * TRUE if the source is the {@link Story} LUID, FALSE if it is a
313 * {@link URL}
314 *
315 * @return the exit return code (0 = success)
316 */
317 private static int read(String story, String chapString, boolean library) {
318 try {
319 BasicReader reader = BasicReader.getReader();
320 if (library) {
321 reader.setStory(story);
322 } else {
323 reader.setStory(getUrl(story));
324 }
325
326 if (chapString != null) {
327 try {
328 reader.read(Integer.parseInt(chapString));
329 } catch (NumberFormatException e) {
330 Instance.syserr(new IOException(
331 "Chapter number cannot be parsed: " + chapString, e));
332 return 2;
333 }
334 } else {
335 reader.read();
336 }
337 } catch (IOException e) {
338 Instance.syserr(e);
339 return 1;
340 }
341
342 return 0;
343 }
344
345 /**
346 * Convert the {@link Story} into another format.
347 *
348 * @param urlString
349 * the source {@link Story} to convert
350 * @param typeString
351 * the {@link OutputType} to convert to
352 * @param target
353 * the target file
354 * @param infoCover
355 * TRUE to also export the cover and info file, even if the given
356 * {@link OutputType} does not usually save them
357 *
358 * @return the exit return code (0 = success)
359 */
360 private static int convert(String urlString, String typeString,
361 String target, boolean infoCover) {
362 int exitCode = 0;
363
364 String sourceName = urlString;
365 try {
366 URL source = getUrl(urlString);
367 sourceName = source.toString();
368 if (source.toString().startsWith("file://")) {
369 sourceName = sourceName.substring("file://".length());
370 }
371
372 OutputType type = OutputType.valueOfAllOkUC(typeString);
373 if (type == null) {
374 Instance.syserr(new IOException(trans(
375 StringId.ERR_BAD_OUTPUT_TYPE, typeString)));
376
377 exitCode = 2;
378 } else {
379 try {
380 BasicSupport support = BasicSupport.getSupport(source);
381
382 if (support != null) {
383 Story story = support.process(source);
384
385 try {
386 target = new File(target).getAbsolutePath();
387 BasicOutput.getOutput(type, infoCover).process(
388 story, target);
389 } catch (IOException e) {
390 Instance.syserr(new IOException(trans(
391 StringId.ERR_SAVING, target), e));
392 exitCode = 5;
393 }
394 } else {
395 Instance.syserr(new IOException(trans(
396 StringId.ERR_NOT_SUPPORTED, source)));
397
398 exitCode = 4;
399 }
400 } catch (IOException e) {
401 Instance.syserr(new IOException(trans(StringId.ERR_LOADING,
402 sourceName), e));
403 exitCode = 3;
404 }
405 }
406 } catch (MalformedURLException e) {
407 Instance.syserr(new IOException(trans(StringId.ERR_BAD_URL,
408 sourceName), e));
409 exitCode = 1;
410 }
411
412 return exitCode;
413 }
414
415 /**
416 * Simple shortcut method to call {link Instance#getTrans()#getString()}.
417 *
418 * @param id
419 * the ID to translate
420 *
421 * @return the translated result
422 */
423 private static String trans(StringId id, Object... params) {
424 return Instance.getTrans().getString(id, params);
425 }
426
427 /**
428 * Display the correct syntax of the program to the user to stdout, or an
429 * error message if the syntax used was wrong on stderr.
430 *
431 * @param showHelp
432 * TRUE to show the syntax help, FALSE to show "syntax error"
433 */
434 private static void syntax(boolean showHelp) {
435 if (showHelp) {
436 StringBuilder builder = new StringBuilder();
437 for (SupportType type : SupportType.values()) {
438 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
439 type.getDesc()));
440 builder.append('\n');
441 }
442
443 String typesIn = builder.toString();
444 builder.setLength(0);
445
446 for (OutputType type : OutputType.values()) {
447 builder.append(trans(StringId.ERR_SYNTAX_TYPE, type.toString(),
448 type.getDesc()));
449 builder.append('\n');
450 }
451
452 String typesOut = builder.toString();
453
454 System.out.println(trans(StringId.HELP_SYNTAX, typesIn, typesOut));
455 } else {
456 System.err.println(trans(StringId.ERR_SYNTAX));
457 }
458 }
459
460 /**
461 * Set the default reader type for this session only (it can be changed in
462 * the configuration file, too, but this value will override it).
463 *
464 * @param readerTypeString
465 * the type
466 */
467 private static int setReaderType(String readerTypeString) {
468 try {
469 ReaderType readerType = ReaderType.valueOf(readerTypeString
470 .toUpperCase());
471 BasicReader.setDefaultReaderType(readerType);
472 return 0;
473 } catch (IllegalArgumentException e) {
474 Instance.syserr(new IOException("Unknown reader type: "
475 + readerTypeString, e));
476 return 1;
477 }
478 }
479 }