]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/App.java
Print stack trace of exception causes in verbose mode
[signal-cli] / src / main / java / org / asamk / signal / App.java
index 873e96bd3ae20653f1c5685a9584822fdf6ccef8..4aa510d61d2d967fd96df08d33c8d609dc27ba81 100644 (file)
@@ -14,7 +14,9 @@ import org.asamk.signal.commands.LocalCommand;
 import org.asamk.signal.commands.MultiLocalCommand;
 import org.asamk.signal.commands.ProvisioningCommand;
 import org.asamk.signal.commands.RegistrationCommand;
+import org.asamk.signal.commands.SignalCreator;
 import org.asamk.signal.commands.exceptions.CommandException;
+import org.asamk.signal.commands.exceptions.IOErrorException;
 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
 import org.asamk.signal.commands.exceptions.UserErrorException;
 import org.asamk.signal.manager.Manager;
@@ -23,6 +25,7 @@ import org.asamk.signal.manager.ProvisioningManager;
 import org.asamk.signal.manager.RegistrationManager;
 import org.asamk.signal.manager.config.ServiceConfig;
 import org.asamk.signal.manager.config.ServiceEnvironment;
+import org.asamk.signal.manager.storage.identities.TrustNewIdentity;
 import org.asamk.signal.util.IOUtils;
 import org.freedesktop.dbus.connections.impl.DBusConnection;
 import org.freedesktop.dbus.exceptions.DBusException;
@@ -35,6 +38,8 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 
+import static net.sourceforge.argparse4j.DefaultSettings.VERSION_0_9_0_DEFAULT_SETTINGS;
+
 public class App {
 
     private final static Logger logger = LoggerFactory.getLogger(App.class);
@@ -42,7 +47,8 @@ public class App {
     private final Namespace ns;
 
     static ArgumentParser buildArgumentParser() {
-        var parser = ArgumentParsers.newFor("signal-cli")
+        var parser = ArgumentParsers.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS)
+                .includeArgumentNamesAsKeysInResult(true)
                 .build()
                 .defaultHelp(true)
                 .description("Commandline interface for Signal.")
@@ -55,7 +61,7 @@ public class App {
         parser.addArgument("--config")
                 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
 
-        parser.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
+        parser.addArgument("-u", "--username").help("Specify your phone number, that will be your identifier.");
 
         var mut = parser.addMutuallyExclusiveGroup();
         mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
@@ -63,16 +69,24 @@ public class App {
 
         parser.addArgument("-o", "--output")
                 .help("Choose to output in plain text or JSON")
-                .type(Arguments.enumStringType(OutputType.class))
-                .setDefault(OutputType.PLAIN_TEXT);
+                .type(Arguments.enumStringType(OutputType.class));
+
+        parser.addArgument("--service-environment")
+                .help("Choose the server environment to use.")
+                .type(Arguments.enumStringType(ServiceEnvironmentCli.class))
+                .setDefault(ServiceEnvironmentCli.LIVE);
+
+        parser.addArgument("--trust-new-identities")
+                .help("Choose when to trust new identities.")
+                .type(Arguments.enumStringType(TrustNewIdentityCli.class))
+                .setDefault(TrustNewIdentityCli.ON_FIRST_USE);
 
         var subparsers = parser.addSubparsers().title("subcommands").dest("command");
 
-        final var commands = Commands.getCommands();
-        for (var entry : commands.entrySet()) {
-            var subparser = subparsers.addParser(entry.getKey());
-            entry.getValue().attachToSubparser(subparser);
-        }
+        Commands.getCommandSubparserAttachers().forEach((key, value) -> {
+            var subparser = subparsers.addParser(key);
+            value.attachToSubparser(subparser);
+        });
 
         return parser;
     }
@@ -88,18 +102,25 @@ public class App {
             throw new UserErrorException("Command not implemented!");
         }
 
-        OutputType outputType = ns.get("output");
-        if (!command.getSupportedOutputTypes().contains(outputType)) {
-            throw new UserErrorException("Command doesn't support output type " + outputType.toString());
+        var outputTypeInput = ns.<OutputType>get("output");
+        var outputType = outputTypeInput == null
+                ? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
+                : outputTypeInput;
+        var outputWriter = outputType == null
+                ? null
+                : outputType == OutputType.JSON ? new JsonWriterImpl(System.out) : new PlainTextWriterImpl(System.out);
+
+        if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
+            throw new UserErrorException("Command doesn't support output type " + outputType);
         }
 
         var username = ns.getString("username");
 
-        final boolean useDbus = ns.getBoolean("dbus");
-        final boolean useDbusSystem = ns.getBoolean("dbus_system");
+        final var useDbus = ns.getBoolean("dbus");
+        final var useDbusSystem = ns.getBoolean("dbus-system");
         if (useDbus || useDbusSystem) {
             // If username is null, it will connect to the default object path
-            initDbusClient(command, username, useDbusSystem);
+            initDbusClient(command, username, useDbusSystem, outputWriter);
             return;
         }
 
@@ -111,8 +132,6 @@ public class App {
             dataPath = getDefaultDataPath();
         }
 
-        final var serviceEnvironment = ServiceEnvironment.LIVE;
-
         if (!ServiceConfig.getCapabilities().isGv2()) {
             logger.warn("WARNING: Support for new group V2 is disabled,"
                     + " because the required native library dependency is missing: libzkgroup");
@@ -122,12 +141,22 @@ public class App {
             throw new UserErrorException("Missing required native library dependency: libsignal-client");
         }
 
+        final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
+        final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
+                ? ServiceEnvironment.LIVE
+                : ServiceEnvironment.SANDBOX;
+
+        final var trustNewIdentityCli = ns.<TrustNewIdentityCli>get("trust-new-identities");
+        final var trustNewIdentity = trustNewIdentityCli == TrustNewIdentityCli.ON_FIRST_USE
+                ? TrustNewIdentity.ON_FIRST_USE
+                : trustNewIdentityCli == TrustNewIdentityCli.ALWAYS ? TrustNewIdentity.ALWAYS : TrustNewIdentity.NEVER;
+
         if (command instanceof ProvisioningCommand) {
             if (username != null) {
                 throw new UserErrorException("You cannot specify a username (phone number) when linking");
             }
 
-            handleProvisioningCommand((ProvisioningCommand) command, dataPath, serviceEnvironment);
+            handleProvisioningCommand((ProvisioningCommand) command, dataPath, serviceEnvironment, outputWriter);
             return;
         }
 
@@ -135,7 +164,12 @@ public class App {
             var usernames = Manager.getAllLocalUsernames(dataPath);
 
             if (command instanceof MultiLocalCommand) {
-                handleMultiLocalCommand((MultiLocalCommand) command, dataPath, serviceEnvironment, usernames);
+                handleMultiLocalCommand((MultiLocalCommand) command,
+                        dataPath,
+                        serviceEnvironment,
+                        usernames,
+                        outputWriter,
+                        trustNewIdentity);
                 return;
             }
 
@@ -160,14 +194,22 @@ public class App {
             throw new UserErrorException("Command only works via dbus");
         }
 
-        handleLocalCommand((LocalCommand) command, username, dataPath, serviceEnvironment);
+        handleLocalCommand((LocalCommand) command,
+                username,
+                dataPath,
+                serviceEnvironment,
+                outputWriter,
+                trustNewIdentity);
     }
 
     private void handleProvisioningCommand(
-            final ProvisioningCommand command, final File dataPath, final ServiceEnvironment serviceEnvironment
+            final ProvisioningCommand command,
+            final File dataPath,
+            final ServiceEnvironment serviceEnvironment,
+            final OutputWriter outputWriter
     ) throws CommandException {
         var pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
-        command.handleCommand(ns, pm);
+        command.handleCommand(ns, pm, outputWriter);
     }
 
     private void handleRegistrationCommand(
@@ -184,7 +226,7 @@ public class App {
                     + e.getMessage()
                     + " ("
                     + e.getClass().getSimpleName()
-                    + ")");
+                    + ")", e);
         }
         try (var m = manager) {
             command.handleCommand(ns, m);
@@ -197,10 +239,12 @@ public class App {
             final LocalCommand command,
             final String username,
             final File dataPath,
-            final ServiceEnvironment serviceEnvironment
+            final ServiceEnvironment serviceEnvironment,
+            final OutputWriter outputWriter,
+            final TrustNewIdentity trustNewIdentity
     ) throws CommandException {
-        try (var m = loadManager(username, dataPath, serviceEnvironment)) {
-            command.handleCommand(ns, m);
+        try (var m = loadManager(username, dataPath, serviceEnvironment, trustNewIdentity)) {
+            command.handleCommand(ns, m, outputWriter);
         } catch (IOException e) {
             logger.warn("Cleanup failed", e);
         }
@@ -210,18 +254,30 @@ public class App {
             final MultiLocalCommand command,
             final File dataPath,
             final ServiceEnvironment serviceEnvironment,
-            final List<String> usernames
+            final List<String> usernames,
+            final OutputWriter outputWriter,
+            final TrustNewIdentity trustNewIdentity
     ) throws CommandException {
         final var managers = new ArrayList<Manager>();
         for (String u : usernames) {
             try {
-                managers.add(loadManager(u, dataPath, serviceEnvironment));
+                managers.add(loadManager(u, dataPath, serviceEnvironment, trustNewIdentity));
             } catch (CommandException e) {
                 logger.warn("Ignoring {}: {}", u, e.getMessage());
             }
         }
 
-        command.handleCommand(ns, managers);
+        command.handleCommand(ns, managers, new SignalCreator() {
+            @Override
+            public ProvisioningManager getNewProvisioningManager() {
+                return ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
+            }
+
+            @Override
+            public RegistrationManager getNewRegistrationManager(String username) throws IOException {
+                return RegistrationManager.init(username, dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
+            }
+        }, outputWriter);
 
         for (var m : managers) {
             try {
@@ -233,11 +289,14 @@ public class App {
     }
 
     private Manager loadManager(
-            final String username, final File dataPath, final ServiceEnvironment serviceEnvironment
+            final String username,
+            final File dataPath,
+            final ServiceEnvironment serviceEnvironment,
+            final TrustNewIdentity trustNewIdentity
     ) throws CommandException {
         Manager manager;
         try {
-            manager = Manager.init(username, dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
+            manager = Manager.init(username, dataPath, serviceEnvironment, BaseConfig.USER_AGENT, trustNewIdentity);
         } catch (NotRegisteredException e) {
             throw new UserErrorException("User " + username + " is not registered.");
         } catch (Throwable e) {
@@ -247,20 +306,20 @@ public class App {
                     + e.getMessage()
                     + " ("
                     + e.getClass().getSimpleName()
-                    + ")");
+                    + ")", e);
         }
 
         try {
             manager.checkAccountState();
         } catch (IOException e) {
-            throw new UnexpectedErrorException("Error while checking account " + username + ": " + e.getMessage());
+            throw new IOErrorException("Error while checking account " + username + ": " + e.getMessage(), e);
         }
 
         return manager;
     }
 
     private void initDbusClient(
-            final Command command, final String username, final boolean systemBus
+            final Command command, final String username, final boolean systemBus, final OutputWriter outputWriter
     ) throws CommandException {
         try {
             DBusConnection.DBusBusType busType;
@@ -274,49 +333,30 @@ public class App {
                         DbusConfig.getObjectPath(username),
                         Signal.class);
 
-                handleCommand(command, ts, dBusConn);
+                handleCommand(command, ts, dBusConn, outputWriter);
             }
         } catch (DBusException | IOException e) {
             logger.error("Dbus client failed", e);
-            throw new UnexpectedErrorException("Dbus client failed");
+            throw new UnexpectedErrorException("Dbus client failed", e);
         }
     }
 
-    private void handleCommand(Command command, Signal ts, DBusConnection dBusConn) throws CommandException {
+    private void handleCommand(
+            Command command, Signal ts, DBusConnection dBusConn, OutputWriter outputWriter
+    ) throws CommandException {
         if (command instanceof ExtendedDbusCommand) {
-            ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
+            ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn, outputWriter);
         } else if (command instanceof DbusCommand) {
-            ((DbusCommand) command).handleCommand(ns, ts);
+            ((DbusCommand) command).handleCommand(ns, ts, outputWriter);
         } else {
             throw new UserErrorException("Command is not yet implemented via dbus");
         }
     }
 
     /**
-     * Uses $XDG_DATA_HOME/signal-cli if it exists, or if none of the legacy directories exist:
-     * - $HOME/.config/signal
-     * - $HOME/.config/textsecure
-     *
-     * @return the data directory to be used by signal-cli.
+     * @return the default data directory to be used by signal-cli.
      */
     private static File getDefaultDataPath() {
-        var dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
-        if (dataPath.exists()) {
-            return dataPath;
-        }
-
-        var configPath = new File(System.getProperty("user.home"), ".config");
-
-        var legacySettingsPath = new File(configPath, "signal");
-        if (legacySettingsPath.exists()) {
-            return legacySettingsPath;
-        }
-
-        legacySettingsPath = new File(configPath, "textsecure");
-        if (legacySettingsPath.exists()) {
-            return legacySettingsPath;
-        }
-
-        return dataPath;
+        return new File(IOUtils.getDataHomeDir(), "signal-cli");
     }
 }