]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/App.java
Extend updateContact command with nick given/family name and note
[signal-cli] / src / main / java / org / asamk / signal / App.java
index 564e08d24bf6a68e89f5e1101d007b9e383dcd76..e494d201016189cec989f6ef0372962fefc9f1b2 100644 (file)
@@ -5,8 +5,8 @@ import net.sourceforge.argparse4j.impl.Arguments;
 import net.sourceforge.argparse4j.inf.ArgumentParser;
 import net.sourceforge.argparse4j.inf.Namespace;
 
-import org.asamk.Signal;
 import org.asamk.signal.commands.Command;
+import org.asamk.signal.commands.CommandHandler;
 import org.asamk.signal.commands.Commands;
 import org.asamk.signal.commands.LocalCommand;
 import org.asamk.signal.commands.MultiLocalCommand;
@@ -16,22 +16,18 @@ 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.dbus.DbusManagerImpl;
 import org.asamk.signal.manager.Manager;
-import org.asamk.signal.manager.MultiAccountManagerImpl;
-import org.asamk.signal.manager.NotRegisteredException;
-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.manager.Settings;
+import org.asamk.signal.manager.SignalAccountFiles;
+import org.asamk.signal.manager.api.AccountCheckException;
+import org.asamk.signal.manager.api.NotRegisteredException;
+import org.asamk.signal.manager.api.ServiceEnvironment;
+import org.asamk.signal.manager.api.TrustNewIdentity;
 import org.asamk.signal.output.JsonWriterImpl;
 import org.asamk.signal.output.OutputWriter;
 import org.asamk.signal.output.PlainTextWriterImpl;
 import org.asamk.signal.util.IOUtils;
-import org.freedesktop.dbus.connections.impl.DBusConnection;
-import org.freedesktop.dbus.exceptions.DBusException;
-import org.freedesktop.dbus.exceptions.DBusExecutionException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -39,15 +35,14 @@ import java.io.BufferedWriter;
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.Set;
 
 import static net.sourceforge.argparse4j.DefaultSettings.VERSION_0_9_0_DEFAULT_SETTINGS;
+import static org.asamk.signal.dbus.DbusCommandHandler.initDbusClient;
 
 public class App {
 
-    private final static Logger logger = LoggerFactory.getLogger(App.class);
+    private static final Logger logger = LoggerFactory.getLogger(App.class);
 
     private final Namespace ns;
 
@@ -59,11 +54,17 @@ public class App {
                 .description("Commandline interface for Signal.")
                 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
 
-        parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
-        parser.addArgument("--verbose")
-                .help("Raise log level and include lib signal logs.")
-                .action(Arguments.storeTrue());
-        parser.addArgument("--config")
+        parser.addArgument("--version").help("Show package version.").action(Arguments.version());
+        parser.addArgument("-v", "--verbose")
+                .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
+                .action(Arguments.count());
+        parser.addArgument("--log-file")
+                .type(File.class)
+                .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
+        parser.addArgument("--scrub-log")
+                .action(Arguments.storeTrue())
+                .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
+        parser.addArgument("-c", "--config")
                 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
 
         parser.addArgument("-a", "--account", "-u", "--username")
@@ -75,6 +76,10 @@ public class App {
                 .dest("global-dbus-system")
                 .help("Make request via system dbus.")
                 .action(Arguments.storeTrue());
+        parser.addArgument("--bus-name")
+                .dest("global-bus-name")
+                .setDefault(DbusConfig.getBusname())
+                .help("Specify the D-Bus bus name to connect to.");
 
         parser.addArgument("-o", "--output")
                 .help("Choose to output in plain text or JSON")
@@ -90,6 +95,13 @@ public class App {
                 .type(Arguments.enumStringType(TrustNewIdentityCli.class))
                 .setDefault(TrustNewIdentityCli.ON_FIRST_USE);
 
+        parser.addArgument("--disable-send-log")
+                .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
+                .action(Arguments.storeTrue());
+
+        parser.epilog(
+                "The global arguments are shown with 'signal-cli -h' and need to come before the subcommand, while the subcommand-specific arguments (shown with 'signal-cli SUBCOMMAND -h') need to be given after the subcommand.");
+
         var subparsers = parser.addSubparsers().title("subcommands").dest("command");
 
         Commands.getCommandSubparserAttachers().forEach((key, value) -> {
@@ -105,136 +117,155 @@ public class App {
     }
 
     public void init() throws CommandException {
+        logger.debug("Starting {}", BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
         var commandKey = ns.getString("command");
         var command = Commands.getCommand(commandKey);
         if (command == null) {
             throw new UserErrorException("Command not implemented!");
         }
 
-        var outputTypeInput = ns.<OutputType>get("output");
-        var outputType = outputTypeInput == null
-                ? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
-                : outputTypeInput;
-        var writer = new BufferedWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()));
-        var outputWriter = outputType == null
-                ? null
-                : outputType == OutputType.JSON ? new JsonWriterImpl(writer) : new PlainTextWriterImpl(writer);
-
-        if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
-            throw new UserErrorException("Command doesn't support output type " + outputType);
-        }
+        final var outputWriter = getOutputWriter(command);
+        final var commandHandler = new CommandHandler(ns, outputWriter);
 
         var account = ns.getString("account");
 
         final var useDbus = Boolean.TRUE.equals(ns.getBoolean("global-dbus"));
         final var useDbusSystem = Boolean.TRUE.equals(ns.getBoolean("global-dbus-system"));
         if (useDbus || useDbusSystem) {
+            final var busName = ns.getString("global-bus-name");
             // If account is null, it will connect to the default object path
-            initDbusClient(command, account, useDbusSystem, outputWriter);
+            initDbusClient(command, account, useDbusSystem, busName, commandHandler);
             return;
         }
 
-        final File dataPath;
-        var config = ns.getString("config");
-        if (config != null) {
-            dataPath = new File(config);
-        } else {
-            dataPath = getDefaultDataPath();
-        }
-
-        if (!ServiceConfig.isSignalClientAvailable()) {
+        if (!Manager.isSignalClientAvailable()) {
             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 signalAccountFiles = loadSignalAccountFiles();
 
-        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;
+        handleCommand(command, commandHandler, account, signalAccountFiles);
+    }
 
+    private void handleCommand(
+            final Command command,
+            final CommandHandler commandHandler,
+            String account,
+            final SignalAccountFiles signalAccountFiles
+    ) throws CommandException {
         if (command instanceof ProvisioningCommand provisioningCommand) {
             if (account != null) {
                 throw new UserErrorException("You cannot specify a account (phone number) when linking");
             }
 
-            handleProvisioningCommand(provisioningCommand, dataPath, serviceEnvironment, outputWriter);
+            handleProvisioningCommand(provisioningCommand, signalAccountFiles, commandHandler);
             return;
         }
 
         if (account == null) {
-            var accounts = Manager.getAllLocalAccountNumbers(dataPath);
-
             if (command instanceof MultiLocalCommand multiLocalCommand) {
-                handleMultiLocalCommand(multiLocalCommand,
-                        dataPath,
-                        serviceEnvironment,
-                        accounts,
-                        outputWriter,
-                        trustNewIdentity);
+                handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, commandHandler);
                 return;
             }
 
-            if (accounts.size() == 0) {
-                throw new UserErrorException("No local users found, you first need to register or link an account");
-            } else if (accounts.size() > 1) {
-                throw new UserErrorException(
-                        "Multiple users found, you need to specify an account (phone number) with -a");
-            }
-
-            account = accounts.get(0);
+            account = getAccountIfOnlyOne(signalAccountFiles);
         } else if (!Manager.isValidNumber(account, null)) {
             throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
         }
 
         if (command instanceof RegistrationCommand registrationCommand) {
-            handleRegistrationCommand(registrationCommand, account, dataPath, serviceEnvironment);
+            handleRegistrationCommand(registrationCommand, account, signalAccountFiles, commandHandler);
             return;
         }
 
-        if (!(command instanceof LocalCommand)) {
-            throw new UserErrorException("Command only works via dbus");
+        if (command instanceof LocalCommand localCommand) {
+            handleLocalCommand(localCommand, account, signalAccountFiles, commandHandler);
+            return;
+        }
+
+        throw new UserErrorException("Command only works in multi-account mode");
+    }
+
+    private static String getAccountIfOnlyOne(final SignalAccountFiles signalAccountFiles) throws IOErrorException, UserErrorException {
+        Set<String> accounts;
+        try {
+            accounts = signalAccountFiles.getAllLocalAccountNumbers();
+        } catch (IOException e) {
+            throw new IOErrorException("Failed to load local accounts file", e);
+        }
+        if (accounts.isEmpty()) {
+            throw new UserErrorException("No local users found, you first need to register or link an account");
+        } else if (accounts.size() > 1) {
+            throw new UserErrorException("Multiple users found, you need to specify an account (phone number) with -a");
         }
+        return accounts.stream().findFirst().get();
+    }
+
+    private OutputWriter getOutputWriter(final Command command) throws UserErrorException {
+        final var outputTypeInput = ns.<OutputType>get("output");
+        final var outputType = outputTypeInput == null ? command.getSupportedOutputTypes()
+                .stream()
+                .findFirst()
+                .orElse(null) : outputTypeInput;
+        final var writer = new BufferedWriter(new OutputStreamWriter(System.out, IOUtils.getConsoleCharset()));
+        final var outputWriter = outputType == null
+                ? null
+                : outputType == OutputType.JSON ? new JsonWriterImpl(writer) : new PlainTextWriterImpl(writer);
+
+        if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
+            throw new UserErrorException("Command doesn't support output type " + outputType);
+        }
+        return outputWriter;
+    }
+
+    private SignalAccountFiles loadSignalAccountFiles() throws IOErrorException {
+        final File configPath;
+        final var config = ns.getString("config");
+        if (config != null) {
+            configPath = new File(config);
+        } else {
+            configPath = getDefaultConfigPath();
+        }
+
+        final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
+        final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
+                ? ServiceEnvironment.LIVE
+                : ServiceEnvironment.STAGING;
+
+        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;
 
-        handleLocalCommand((LocalCommand) command,
-                account,
-                dataPath,
-                serviceEnvironment,
-                outputWriter,
-                trustNewIdentity);
+        final var disableSendLog = Boolean.TRUE.equals(ns.getBoolean("disable-send-log"));
+
+        try {
+            return new SignalAccountFiles(configPath,
+                    serviceEnvironment,
+                    BaseConfig.USER_AGENT,
+                    new Settings(trustNewIdentity, disableSendLog));
+        } catch (IOException e) {
+            throw new IOErrorException("Failed to read local accounts list", e);
+        }
     }
 
     private void handleProvisioningCommand(
             final ProvisioningCommand command,
-            final File dataPath,
-            final ServiceEnvironment serviceEnvironment,
-            final OutputWriter outputWriter
+            final SignalAccountFiles signalAccountFiles,
+            final CommandHandler commandHandler
     ) throws CommandException {
-        var pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
-        command.handleCommand(ns, pm, outputWriter);
+        var pm = signalAccountFiles.initProvisioningManager();
+        commandHandler.handleProvisioningCommand(command, pm);
     }
 
     private void handleRegistrationCommand(
             final RegistrationCommand command,
             final String account,
-            final File dataPath,
-            final ServiceEnvironment serviceEnvironment
+            final SignalAccountFiles signalAccountFiles,
+            final CommandHandler commandHandler
     ) throws CommandException {
-        final RegistrationManager manager;
-        try {
-            manager = RegistrationManager.init(account, dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
-        } catch (Throwable e) {
-            throw new UnexpectedErrorException("Error loading or creating state file: "
-                    + e.getMessage()
-                    + " ("
-                    + e.getClass().getSimpleName()
-                    + ")", e);
-        }
-        try (manager) {
-            command.handleCommand(ns, manager);
+        try (final var rm = loadRegistrationManager(account, signalAccountFiles)) {
+            commandHandler.handleRegistrationCommand(command, rm);
         } catch (IOException e) {
             logger.warn("Cleanup failed", e);
         }
@@ -243,54 +274,57 @@ public class App {
     private void handleLocalCommand(
             final LocalCommand command,
             final String account,
-            final File dataPath,
-            final ServiceEnvironment serviceEnvironment,
-            final OutputWriter outputWriter,
-            final TrustNewIdentity trustNewIdentity
+            final SignalAccountFiles signalAccountFiles,
+            final CommandHandler commandHandler
     ) throws CommandException {
-        try (var m = loadManager(account, dataPath, serviceEnvironment, trustNewIdentity)) {
-            command.handleCommand(ns, m, outputWriter);
-        } catch (IOException e) {
-            logger.warn("Cleanup failed", e);
+        try (var m = loadManager(account, signalAccountFiles)) {
+            commandHandler.handleLocalCommand(command, m);
         }
     }
 
     private void handleMultiLocalCommand(
             final MultiLocalCommand command,
-            final File dataPath,
-            final ServiceEnvironment serviceEnvironment,
-            final List<String> accounts,
-            final OutputWriter outputWriter,
-            final TrustNewIdentity trustNewIdentity
+            final SignalAccountFiles signalAccountFiles,
+            final CommandHandler commandHandler
     ) throws CommandException {
-        final var managers = new ArrayList<Manager>();
-        for (String a : accounts) {
-            try {
-                managers.add(loadManager(a, dataPath, serviceEnvironment, trustNewIdentity));
-            } catch (CommandException e) {
-                logger.warn("Ignoring {}: {}", a, e.getMessage());
-            }
+        try (var multiAccountManager = signalAccountFiles.initMultiAccountManager()) {
+            commandHandler.handleMultiLocalCommand(command, multiAccountManager);
+        } catch (IOException e) {
+            throw new IOErrorException("Failed to load local accounts file", e);
         }
+    }
 
-        try (var multiAccountManager = new MultiAccountManagerImpl(managers,
-                dataPath,
-                serviceEnvironment,
-                BaseConfig.USER_AGENT)) {
-            command.handleCommand(ns, multiAccountManager, outputWriter);
+    private RegistrationManager loadRegistrationManager(
+            final String account,
+            final SignalAccountFiles signalAccountFiles
+    ) throws UnexpectedErrorException {
+        try {
+            return signalAccountFiles.initRegistrationManager(account);
+        } catch (Throwable e) {
+            throw new UnexpectedErrorException("Error loading or creating state file: "
+                    + e.getMessage()
+                    + " ("
+                    + e.getClass().getSimpleName()
+                    + ")", e);
         }
     }
 
     private Manager loadManager(
             final String account,
-            final File dataPath,
-            final ServiceEnvironment serviceEnvironment,
-            final TrustNewIdentity trustNewIdentity
+            final SignalAccountFiles signalAccountFiles
     ) throws CommandException {
-        Manager manager;
+        logger.trace("Loading account file for {}", account);
         try {
-            manager = Manager.init(account, dataPath, serviceEnvironment, BaseConfig.USER_AGENT, trustNewIdentity);
+            return signalAccountFiles.initManager(account);
         } catch (NotRegisteredException e) {
             throw new UserErrorException("User " + account + " is not registered.");
+        } catch (AccountCheckException ace) {
+            if (ace.getCause() instanceof IOException e) {
+                throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
+            } else {
+                throw new UnexpectedErrorException("Error while checking account " + account + ": " + ace.getMessage(),
+                        ace);
+            }
         } catch (Throwable e) {
             throw new UnexpectedErrorException("Error loading state file for user "
                     + account
@@ -300,64 +334,12 @@ public class App {
                     + e.getClass().getSimpleName()
                     + ")", e);
         }
-
-        try {
-            manager.checkAccountState();
-        } catch (IOException e) {
-            try {
-                manager.close();
-            } catch (IOException ie) {
-                logger.warn("Failed to close broken account", ie);
-            }
-            throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
-        }
-
-        return manager;
-    }
-
-    private void initDbusClient(
-            final Command command, final String account, final boolean systemBus, final OutputWriter outputWriter
-    ) throws CommandException {
-        try {
-            DBusConnection.DBusBusType busType;
-            if (systemBus) {
-                busType = DBusConnection.DBusBusType.SYSTEM;
-            } else {
-                busType = DBusConnection.DBusBusType.SESSION;
-            }
-            try (var dBusConn = DBusConnection.getConnection(busType)) {
-                var ts = dBusConn.getRemoteObject(DbusConfig.getBusname(),
-                        DbusConfig.getObjectPath(account),
-                        Signal.class);
-
-                handleCommand(command, ts, dBusConn, outputWriter);
-            }
-        } catch (DBusException | IOException e) {
-            logger.error("Dbus client failed", e);
-            throw new UnexpectedErrorException("Dbus client failed", e);
-        }
-    }
-
-    private void handleCommand(
-            Command command, Signal ts, DBusConnection dBusConn, OutputWriter outputWriter
-    ) throws CommandException {
-        if (command instanceof LocalCommand localCommand) {
-            try (final var m = new DbusManagerImpl(ts, dBusConn)) {
-                localCommand.handleCommand(ns, m, outputWriter);
-            } catch (UnsupportedOperationException e) {
-                throw new UserErrorException("Command is not yet implemented via dbus", e);
-            } catch (IOException | DBusExecutionException e) {
-                throw new UnexpectedErrorException(e.getMessage(), e);
-            }
-        } else {
-            throw new UserErrorException("Command is not yet implemented via dbus");
-        }
     }
 
     /**
      * @return the default data directory to be used by signal-cli.
      */
-    private static File getDefaultDataPath() {
+    private static File getDefaultConfigPath() {
         return new File(IOUtils.getDataHomeDir(), "signal-cli");
     }
 }