image --load now store the file as is
[jvcard.git] / src / be / nikiroo / jvcard / launcher / Main.java
CommitLineData
7da41ecd
NR
1package be.nikiroo.jvcard.launcher;
2
3import java.io.File;
4import java.io.IOException;
5import java.lang.reflect.Field;
7da41ecd
NR
6import java.net.Socket;
7import java.nio.charset.Charset;
8import java.util.LinkedList;
9import java.util.List;
10
26d254a3
NR
11import javax.imageio.ImageIO;
12
7da41ecd 13import be.nikiroo.jvcard.Card;
26d254a3
NR
14import be.nikiroo.jvcard.Contact;
15import be.nikiroo.jvcard.Data;
16import be.nikiroo.jvcard.TypeInfo;
5ad0e17e 17import be.nikiroo.jvcard.launcher.CardResult.MergeCallback;
7da41ecd 18import be.nikiroo.jvcard.parsers.Format;
845fb1d7 19import be.nikiroo.jvcard.remote.Command;
7da41ecd
NR
20import be.nikiroo.jvcard.remote.SimpleSocket;
21import be.nikiroo.jvcard.resources.Bundles;
22import be.nikiroo.jvcard.resources.StringUtils;
e119a1c1
NR
23import be.nikiroo.jvcard.resources.bundles.ColorBundle;
24import be.nikiroo.jvcard.resources.bundles.DisplayBundle;
25import be.nikiroo.jvcard.resources.bundles.RemoteBundle;
26import be.nikiroo.jvcard.resources.bundles.TransBundle;
27import be.nikiroo.jvcard.resources.enums.DisplayOption;
28import be.nikiroo.jvcard.resources.enums.StringId;
7da41ecd
NR
29
30/**
31 * This class contains the runnable Main method. It will parse the user supplied
32 * parameters and take action based upon those. Most of the time, it will start
33 * a MainWindow.
34 *
35 * @author niki
36 *
37 */
38public class Main {
39 static public final String APPLICATION_TITLE = "jVcard";
6435013a 40 static public final String APPLICATION_VERSION = "1.0-dev";
7da41ecd
NR
41
42 static private final int ERR_NO_FILE = 1;
43 static private final int ERR_SYNTAX = 2;
44 static private final int ERR_INTERNAL = 3;
e119a1c1 45 static private TransBundle transService;
7da41ecd 46
30a4aa17
NR
47 static private String defaultFn;
48 static private boolean forceComputedFn;
49
26d254a3 50 enum Mode {
88eb8122 51 CONTACT_MANAGER, I18N, SERVER, LOAD_PHOTO, SAVE_PHOTO, SAVE_CONFIG, HELP
26d254a3
NR
52 }
53
7da41ecd 54 /**
9b8cb729 55 * Translate the given {@link StringId} into user text.
7da41ecd 56 *
9b8cb729 57 * @param stringId
7da41ecd 58 * the ID to translate
9b8cb729
NR
59 * @param values
60 * the values to insert instead of the place holders in the
61 * translation
7da41ecd 62 *
9b8cb729 63 * @return the translated text with the given value where required
7da41ecd 64 */
e119a1c1 65 static public String trans(StringId id, Object... values) {
59597d59 66 return transService.getString(id, values);
7da41ecd
NR
67 }
68
69 /**
70 * Check if unicode characters should be used.
71 *
72 * @return TRUE to allow unicode
73 */
74 static public boolean isUnicode() {
75 return transService.isUnicode();
76 }
77
78 /**
79 * Start the application.
80 *
81 * <p>
82 * The returned exit codes are:
83 * <ul>
84 * <li>1: no files to open</li>
85 * <li>2: invalid syntax</li>
86 * <li>3: internal error</li>
87 * </ul>
88 * </p>
89 *
90 * @param args
91 * the parameters (see <tt>--help</tt> to know which are
92 * supported)
93 */
94 public static void main(String[] args) {
95 Boolean textMode = null;
96 boolean noMoreParams = false;
97 boolean filesTried = false;
98
99 // get the "system default" language to help translate the --help
100 // message if needed
101 String language = null;
e119a1c1 102 transService = new TransBundle(language);
7da41ecd
NR
103
104 boolean unicode = transService.isUnicode();
26d254a3 105 String dir = null;
7da41ecd 106 List<String> files = new LinkedList<String>();
26d254a3
NR
107 int port = -1;
108 Mode mode = Mode.CONTACT_MANAGER;
109 String format = null;
7da41ecd
NR
110 for (int index = 0; index < args.length; index++) {
111 String arg = args[index];
112 if (!noMoreParams && arg.equals("--")) {
113 noMoreParams = true;
114 } else if (!noMoreParams && arg.equals("--help")) {
88eb8122
NR
115 if (mode != Mode.CONTACT_MANAGER) {
116 SERR(StringId.CLI_SERR_MODES);
117 return;
118 }
119 mode = Mode.HELP;
7da41ecd
NR
120 } else if (!noMoreParams && arg.equals("--tui")) {
121 textMode = true;
122 } else if (!noMoreParams && arg.equals("--gui")) {
123 textMode = false;
124 } else if (!noMoreParams && arg.equals("--noutf")) {
125 unicode = false;
126 transService.setUnicode(unicode);
127 } else if (!noMoreParams && arg.equals("--lang")) {
128 index++;
129 if (index >= args.length) {
88eb8122 130 SERR(StringId.CLI_SERR_NOLANG);
7da41ecd
NR
131 return;
132 }
133
134 language = args[index];
e119a1c1 135 transService = new TransBundle(language);
7da41ecd
NR
136 transService.setUnicode(unicode);
137 } else if (!noMoreParams && arg.equals("--config")) {
138 index++;
139 if (index >= args.length) {
88eb8122 140 SERR(StringId.CLI_SERR_NODIR);
7da41ecd
NR
141 return;
142 }
143
144 Bundles.setDirectory(args[index]);
e119a1c1 145 transService = new TransBundle(language);
7da41ecd 146 transService.setUnicode(unicode);
e119a1c1
NR
147 } else if (!noMoreParams && arg.equals("--save-config")) {
148 index++;
149 if (index >= args.length) {
88eb8122 150 SERR(StringId.CLI_SERR_NODIR);
e119a1c1
NR
151 return;
152 }
153 dir = args[index];
154
155 if (mode != Mode.CONTACT_MANAGER) {
88eb8122 156 SERR(StringId.CLI_SERR_MODES);
e119a1c1
NR
157 return;
158 }
159 mode = Mode.SAVE_CONFIG;
7da41ecd 160 } else if (!noMoreParams && arg.equals("--server")) {
26d254a3 161 if (mode != Mode.CONTACT_MANAGER) {
88eb8122 162 SERR(StringId.CLI_SERR_MODES);
26d254a3
NR
163 return;
164 }
165 mode = Mode.SERVER;
166
7da41ecd
NR
167 index++;
168 if (index >= args.length) {
88eb8122 169 SERR(StringId.CLI_SERR_NOPORT);
7da41ecd
NR
170 return;
171 }
172
173 try {
174 port = Integer.parseInt(args[index]);
175 } catch (NumberFormatException e) {
88eb8122 176 SERR(StringId.CLI_SERR_BADPORT, "" + args[index]);
7da41ecd
NR
177 return;
178 }
179 } else if (!noMoreParams && arg.equals("--i18n")) {
26d254a3 180 if (mode != Mode.CONTACT_MANAGER) {
88eb8122 181 SERR(StringId.CLI_SERR_MODES);
26d254a3
NR
182 return;
183 }
184 mode = Mode.I18N;
185
7da41ecd
NR
186 index++;
187 if (index >= args.length) {
88eb8122 188 SERR(StringId.CLI_SERR_NODIR);
7da41ecd
NR
189 return;
190 }
9b8cb729 191
26d254a3
NR
192 dir = args[index];
193 } else if (!noMoreParams
194 && (arg.equals("--load-photo")
195 || arg.equals("--save-photo") || arg
196 .equals("--only-photo"))) {
197 if (mode != Mode.CONTACT_MANAGER) {
88eb8122 198 SERR(StringId.CLI_SERR_MODES);
26d254a3
NR
199 return;
200 }
201
202 if (arg.equals("--load-photo")) {
203 mode = Mode.LOAD_PHOTO;
204 } else if (arg.equals("--save-photo")) {
205 mode = Mode.SAVE_PHOTO;
26d254a3
NR
206 }
207
208 index++;
209 if (index >= args.length) {
88eb8122 210 SERR(StringId.CLI_SERR_NODIR);
26d254a3
NR
211 return;
212 }
213
214 dir = args[index];
215
216 index++;
217 if (index >= args.length) {
88eb8122 218 SERR(StringId.CLI_SERR_NOFORMAT);
26d254a3
NR
219 return;
220 }
221
222 format = args[index];
7da41ecd
NR
223 } else {
224 filesTried = true;
225 files.addAll(open(arg));
226 }
227 }
9b8cb729 228
f578f3af 229 // Force headless mode if we run in forced-text mode
26d254a3 230 if (mode != Mode.CONTACT_MANAGER || (textMode != null && textMode)) {
f578f3af
NR
231 // same as -Djava.awt.headless=true
232 System.setProperty("java.awt.headless", "true");
233 }
7da41ecd
NR
234
235 if (unicode) {
236 utf8();
237 }
238
30a4aa17
NR
239 // N/FN fix information:
240 readNFN();
241
7da41ecd 242 // Error management:
26d254a3 243 if (mode == Mode.SERVER && files.size() > 0) {
88eb8122
NR
244 SERR(StringId.CLI_SERR_NOLANG, "--server");
245 return;
26d254a3 246 } else if (mode == Mode.I18N && files.size() > 0) {
88eb8122
NR
247 SERR(StringId.CLI_SERR_NOLANG, "--i18n");
248 return;
26d254a3 249 } else if (mode == Mode.I18N && language == null) {
88eb8122 250 SERR(StringId.CLI_SERR_NOLANG);
26d254a3
NR
251 } else if ((mode == Mode.CONTACT_MANAGER || mode == Mode.SAVE_PHOTO || mode == Mode.LOAD_PHOTO)
252 && files.size() == 0) {
7da41ecd
NR
253 if (files.size() == 0 && !filesTried) {
254 files.addAll(open("."));
255 }
256
257 if (files.size() == 0) {
88eb8122 258 ERR(StringId.CLI_ERR, StringId.CLI_ERR_NOFILES, ERR_NO_FILE);
7da41ecd
NR
259 return;
260 }
261 }
262 //
263
26d254a3 264 switch (mode) {
e119a1c1
NR
265 case SAVE_CONFIG: {
266 try {
267 if (!new File(dir).isDirectory()) {
268 if (!new File(dir).mkdir()) {
88eb8122
NR
269 System.err.println(trans(
270 StringId.CLI_ERR_CANNOT_CREATE_CONFDIR, dir));
e119a1c1
NR
271 }
272 }
273
274 transService.updateFile(dir); // current lang TransBundle
275 new TransBundle().updateFile(dir);
276 new ColorBundle().updateFile(dir);
277 new DisplayBundle().updateFile(dir);
278 new RemoteBundle().updateFile(dir);
279 } catch (IOException e) {
280 e.printStackTrace();
59597d59 281 System.err.flush();
e119a1c1
NR
282 System.exit(ERR_INTERNAL);
283 }
284 break;
285 }
26d254a3 286 case SERVER: {
7da41ecd 287 try {
02b341aa 288 Optional.runServer(port);
7da41ecd
NR
289 } catch (Exception e) {
290 if (e instanceof IOException) {
291 System.err
292 .println("I/O Exception: Cannot start the server");
293 } else {
88eb8122
NR
294 ERR(StringId.CLI_ERR, StringId.CLI_ERR_NO_REMOTING,
295 ERR_INTERNAL);
296 return;
7da41ecd
NR
297 }
298 }
26d254a3
NR
299 break;
300 }
301 case I18N: {
7da41ecd 302 try {
e119a1c1 303 transService.updateFile(dir);
7da41ecd 304 } catch (IOException e) {
88eb8122
NR
305 System.err.println(trans(StringId.CLI_ERR_CANNOT_CREATE_LANG,
306 dir));
e119a1c1 307 e.printStackTrace();
7da41ecd 308 }
26d254a3
NR
309 break;
310 }
26d254a3
NR
311 case LOAD_PHOTO: {
312 for (String file : files) {
313 try {
314 Card card = getCard(file, null).getCard();
315 for (Contact contact : card) {
316 String filename = contact.toString(format, "");
f29274a7 317 File f = new File(dir, filename);
26d254a3
NR
318
319 if (f.exists()) {
e3fe9834 320 System.out.println("Loading " + f);
26d254a3 321 try {
a1783d00
NR
322 String type = "jpeg";
323 int dotIndex = filename.indexOf('.');
324 if (dotIndex >= 0
325 && (dotIndex + 1) < filename.length()) {
326 type = filename.substring(dotIndex + 1)
327 .toLowerCase();
328 }
329
330 String b64 = StringUtils.fromImage(f);
26d254a3 331
88eb8122
NR
332 // remove previous photos:
333 for (Data photo = contact
334 .getPreferredData("PHOTO"); photo != null; photo = contact
335 .getPreferredData("PHOTO")) {
336 photo.delete();
26d254a3 337 }
88eb8122 338 //
26d254a3
NR
339
340 List<TypeInfo> types = new LinkedList<TypeInfo>();
341 types.add(new TypeInfo("ENCODING", "b"));
a1783d00 342 types.add(new TypeInfo("TYPE", type));
26d254a3
NR
343 Data photo = new Data(types, "PHOTO", b64, null);
344 contact.add(photo);
345 } catch (IOException e) {
346 System.err.println("Cannot read photo: "
347 + filename);
348 }
349 }
350 }
351 card.save();
352 } catch (IOException e) {
88eb8122
NR
353 System.err
354 .println(trans(StringId.CLI_ERR_CANNOT_OPEN, file));
26d254a3
NR
355 }
356 }
357 break;
358 }
359 case SAVE_PHOTO: {
360 for (String file : files) {
361 try {
362 Card card = getCard(file, null).getCard();
363 for (Contact contact : card) {
364 Data photo = contact.getPreferredData("PHOTO");
365 if (photo != null) {
366 String filename = contact.toString(format, "");
367 File f = new File(dir, filename + ".png");
e3fe9834 368 System.out.println("Saving " + f);
26d254a3
NR
369 try {
370 ImageIO.write(
371 StringUtils.toImage(photo.getValue()),
372 "png", f);
373 } catch (IOException e) {
88eb8122
NR
374 System.err.println(trans(
375 StringId.CLI_ERR_CANNOT_SAVE_PHOTO,
376 contact.getPreferredDataValue("FN")));
26d254a3
NR
377 }
378 }
379 }
380 } catch (IOException e) {
88eb8122
NR
381 System.err
382 .println(trans(StringId.CLI_ERR_CANNOT_OPEN, file));
26d254a3
NR
383 }
384 }
385 break;
386 }
387 case CONTACT_MANAGER: {
7da41ecd 388 try {
02b341aa 389 Optional.startTui(textMode, files);
7da41ecd
NR
390 } catch (Exception e) {
391 if (e instanceof IOException) {
88eb8122
NR
392 ERR(StringId.CLI_ERR, StringId.CLI_ERR_CANNOT_START,
393 ERR_NO_FILE);
394 return;
7da41ecd 395 } else {
88eb8122
NR
396 ERR(StringId.CLI_ERR, StringId.CLI_ERR_NO_TUI, ERR_INTERNAL);
397 return;
7da41ecd
NR
398 }
399 }
26d254a3
NR
400 break;
401 }
88eb8122
NR
402 case HELP: {
403 System.out.println(APPLICATION_TITLE + " " + APPLICATION_VERSION);
404 System.out.println();
405
406 System.out.println(trans(StringId.CLI_HELP));
407 System.out.println();
408
409 System.out.println(trans(StringId.CLI_HELP_MODES));
410 System.out.println("\t--help : "
411 + trans(StringId.CLI_HELP_MODE_HELP));
412 System.out.println("\t(--tui|--gui) (--noutf) ... : "
413 + trans(StringId.CLI_HELP_MODE_CONTACT_MANAGER));
414 System.out.println("\t--server PORT ... : "
415 + trans(StringId.CLI_HELP_MODE_SERVER));
416 System.out.println("\t--save-config DIR : "
417 + trans(StringId.CLI_HELP_MODE_SAVE_CONFIG));
418 System.out.println("\t--i18n DIR ---lang LANG : "
419 + trans(StringId.CLI_HELP_MODE_I18N));
420 System.out.println("\t--load-photo DIR FORMAT ... : "
421 + trans(StringId.CLI_HELP_MODE_LOAD_PHOTO));
422 System.out.println("\t--save-photo DIR FORMAT ... : "
423 + trans(StringId.CLI_HELP_MODE_SAVE_PHOTO));
424 System.out.println();
425
426 System.out.println(trans(StringId.CLI_HELP_OPTIONS));
427 System.out.println("\t-- : " + trans(StringId.CLI_HELP_DD));
428 System.out.println("\t--lang LANG : "
429 + trans(StringId.CLI_HELP_LANG));
430 System.out.println("\t--tui : " + trans(StringId.CLI_HELP_TUI));
431 System.out.println("\t--gui : " + trans(StringId.CLI_HELP_GUI));
432 System.out.println("\t--noutf : " + trans(StringId.CLI_HELP_NOUTF));
433 System.out.println("\t--config : "
434 + trans(StringId.CLI_HELP_CONFIG));
435 System.out.println();
436
437 System.out.println(trans(StringId.CLI_HELP_FOOTER));
438 System.out.println();
439
440 }
7da41ecd
NR
441 }
442 }
443
444 /**
445 * Return the {@link Card} corresponding to the given resource name -- a
30a4aa17
NR
446 * file or a remote jvcard URL.
447 *
448 * <p>
449 * Will also fix the FN if required (see display.properties).
450 * </p>
7da41ecd
NR
451 *
452 * @param input
453 * a filename or a remote jvcard url with named resource (e.g.:
454 * <tt>jvcard://localhost:4444/coworkers.vcf</tt>)
5ad0e17e
NR
455 * @param callback
456 * the {@link MergeCallback} to call in case of conflict, or NULL
457 * to disallow conflict management (the {@link Card} will not be
458 * allowed to synchronise in case of conflicts)
7da41ecd
NR
459 *
460 * @return the {@link Card}
461 *
462 * @throws IOException
463 * in case of IO error or remoting not available
464 */
5ad0e17e
NR
465 static public CardResult getCard(String input, MergeCallback callback)
466 throws IOException {
7da41ecd
NR
467 boolean remote = false;
468 Format format = Format.Abook;
469 String ext = input;
470 if (ext.contains(".")) {
471 String tab[] = ext.split("\\.");
472 if (tab.length > 1 && tab[tab.length - 1].equalsIgnoreCase("vcf")) {
473 format = Format.VCard21;
474 }
475 }
476
477 if (input.contains("://")) {
478 format = Format.VCard21;
479 remote = true;
480 }
481
5ad0e17e 482 CardResult card = null;
7da41ecd
NR
483 try {
484 if (remote) {
5ad0e17e 485 card = Optional.syncCard(input, callback);
7da41ecd 486 } else {
5ad0e17e
NR
487 card = new CardResult(new Card(new File(input), format), false,
488 false, false);
7da41ecd
NR
489 }
490 } catch (IOException ioe) {
491 throw ioe;
492 } catch (Exception e) {
4298276a 493 throw new IOException("Remoting support not available", e);
7da41ecd
NR
494 }
495
30a4aa17
NR
496 // Fix the FN value
497 if (defaultFn != null) {
498 try {
499 for (Contact contact : card.getCard()) {
500 Data name = contact.getPreferredData("FN");
501 if (name == null || name.getValue().length() == 0
502 || forceComputedFn) {
503 name.setValue(contact.toString(defaultFn, ""));
504 }
505 }
506 } catch (Exception e) {
507 // sync failed -> getCard() throws.
508 // do not update.
509 }
510 }
511
7da41ecd
NR
512 return card;
513 }
514
7da41ecd
NR
515 /**
516 * Open the given path and add all its files if it is a directory or just
517 * this one if not to the returned list.
518 *
519 * @param path
520 * the path to open
521 *
522 * @return the list of opened files
523 */
524 static private List<String> open(String path) {
525 List<String> files = new LinkedList<String>();
526
527 if (path != null && path.startsWith("jvcard://")) {
528 if (path.endsWith("/")) {
529 files.addAll(list(path));
530 } else {
531 files.add(path);
532 }
533 } else {
534 File file = new File(path);
535 if (file.exists()) {
536 if (file.isDirectory()) {
537 for (File subfile : file.listFiles()) {
538 if (!subfile.isDirectory())
539 files.add(subfile.getAbsolutePath());
540 }
541 } else {
542 files.add(file.getAbsolutePath());
543 }
544 } else {
545 System.err.println("File or directory not found: \"" + path
546 + "\"");
547 }
548 }
549
550 return files;
551 }
552
553 /**
554 * List all the available {@link Card}s on the given network location (which
555 * is expected to be a jVCard remote server, obviously).
556 *
557 * @param path
558 * the jVCard remote server path (e.g.:
559 * <tt>jvcard://localhost:4444/</tt>)
560 *
561 * @return the list of {@link Card}s
562 */
563 static private List<String> list(String path) {
564 List<String> files = new LinkedList<String>();
565
566 try {
567 String host = path.split("\\:")[1].substring(2);
568 int port = Integer.parseInt(path.split("\\:")[2].replaceAll("/$",
569 ""));
570 SimpleSocket s = new SimpleSocket(new Socket(host, port),
571 "sync client");
572 s.open(true);
573
845fb1d7 574 s.sendCommand(Command.LIST_CARD);
7da41ecd
NR
575 for (String p : s.receiveBlock()) {
576 files.add(path
577 + p.substring(StringUtils.fromTime(0).length() + 1));
578 }
579 s.close();
580 } catch (Exception e) {
581 e.printStackTrace();
582 }
583
584 return files;
585 }
586
587 /**
588 * Really, really ask for UTF-8 encoding.
589 */
590 static private void utf8() {
591 try {
592 System.setProperty("file.encoding", "UTF-8");
593 Field charset = Charset.class.getDeclaredField("defaultCharset");
594 charset.setAccessible(true);
595 charset.set(null, null);
596 } catch (SecurityException e) {
597 } catch (NoSuchFieldException e) {
598 } catch (IllegalArgumentException e) {
599 } catch (IllegalAccessException e) {
600 }
601 }
30a4aa17
NR
602
603 /**
604 * Read display.properties to know if we should fix the FN field when empty,
605 * or always, or never.
606 */
607 static private void readNFN() {
e119a1c1 608 DisplayBundle map = new DisplayBundle();
30a4aa17 609
e119a1c1
NR
610 defaultFn = map.getString(DisplayOption.CONTACT_DETAILS_DEFAULT_FN);
611
612 forceComputedFn = map.getBoolean(
613 DisplayOption.CONTACT_DETAILS_SHOW_COMPUTED_FN, false);
30a4aa17 614 }
88eb8122
NR
615
616 /**
617 * Syntax error detected, closing the application with an error message.
618 *
619 * @param err
620 * the syntax error case
621 */
622 static private void SERR(StringId err, Object... values) {
623 ERR(StringId.CLI_SERR, err, ERR_SYNTAX, values);
624 }
625
626 /**
627 * Error detected, closing the application with an error message.
628 *
629 * @param err
630 * the error case
631 * @param suberr
632 * the suberror or NULL if none
633 * @param CODE
634 * the error code as declared above
635 */
636 static private void ERR(StringId err, StringId suberr, int CODE,
637 Object... subvalues) {
638 if (suberr == null)
639 System.err.println(trans(err));
640 else
641 System.err.println(trans(err, trans(suberr, subvalues)));
642
59597d59 643 System.err.flush();
88eb8122
NR
644 System.exit(CODE);
645 }
7da41ecd 646}